@0xmonaco/mcp-server 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +3 -3
- 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 wx($){return{not:h4($)}}function Mx($){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 wx(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 Mx(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 w={...N,relatedRequestId:$.id};if(X&&!w.relatedTask)w.relatedTask={taskId:X};let M=w.relatedTask?.taskId??X;if(M&&D)await D.updateTaskStatus(M,"input_required");return await this.request(K,O,w)},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++,w={...$,jsonrpc:"2.0",id:N};if(Q?.onprogress)this._progressHandlers.set(N,Q.onprogress),w.params={...$.params,_meta:{...$.params?._meta||{},progressToken:N}};if(W)w.params={...w.params,task:W};if(D)w.params={...w.params,_meta:{...w.params?._meta||{},[L8]:D}};let M=(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",()=>{M(Q?.signal?.reason)});let z=Q?.timeout??k0$,q=()=>M(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:w,timestamp:Date.now()}).catch((E)=>{this._cleanupTimeout(N),K(E)})}else this._transport.send(w,{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 M=K.error instanceof Error?K.error.message:String(K.error);throw new B$(E$.InvalidParams,`Invalid tools/call request: ${M}`)}let{params:O}=K.data,N=await Promise.resolve(J(D,V));if(O.task){let M=I8(I5,N);if(!M.success){let z=M.error instanceof Error?M.error.message:String(M.error);throw new B$(E$.InvalidParams,`Invalid task creation result: ${z}`)}return M.data}let w=I8(dN,N);if(!w.success){let M=w.error instanceof Error?w.error.message:String(w.error);throw new B$(E$.InvalidParams,`Invalid tools/call result: ${M}`)}return w.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:ML,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 wh 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($=wh.stdin,J=wh.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 Pw={name:"@0xmonaco/mcp-server",version:"1.0.2",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.2","@0xmonaco/types":"1.0.2","@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();M9();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 w(_,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(!w(J.Gx,J.Gy))throw Error("bad curve params: generator point");let M=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$),M4=O(Z4*Z4),p4=O(Z$*C),a4=O(Z4*O(p4+W4)),Y1=O(M4+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=MQ(Q,_.map((m)=>m.ez));return _.map((m,V$)=>m.toAffine(C[V$])).map(L.fromAffine)}static msm(_,C){return mw(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$),M4=O(z$*V$);return Z$===W4&&Z4===M4}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$),M4=Z$+z$,p4=M4-R$,a4=Z$-z$,Y1=O(Z4*p4),d1=O(M4*a4),s4=O(Z4*a4),L6=O(p4*M4);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:M4}=_,p4=O(V$*Z$),a4=O(K$*W4),Y1=O(R$*m*M4),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$),M4=O(Z4-U6),p4=O(m*Z4-V$),{isValid:a4,value:Y1}=M(M4,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=uw(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 M4=A1(Z$,h5(Z4,Q.BYTES));return A4("result",M4,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,M4;try{W4=L.fromHex(m,z$),Z4=L.fromHex(_.slice(0,R$),z$),M4=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(M4).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}}}}M9();/*! 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,w=u4(N,Q,G)*N%G,M=u4(w,Y,G)*w%G,z=u4(M,X,G)*M%G,q=u4(z,X,G)*M%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),w=D===G4(-$*Wu,Q);if(O)W=V;if(N||w)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$}))(),lw=(()=>Ju(n7$))();QV();W0();function dw(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=lw.utils.randomPrivateKey();return{publicKey:lw.getPublicKey($),privateKey:$}}function pw($){return Y9($.publicKey)}function nw($){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($=wh.stdin,J=wh.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 Pw={name:"@0xmonaco/mcp-server",version:"1.0.3",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.3","@0xmonaco/types":"1.0.3","@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();M9();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 w(_,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(!w(J.Gx,J.Gy))throw Error("bad curve params: generator point");let M=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$),M4=O(Z4*Z4),p4=O(Z$*C),a4=O(Z4*O(p4+W4)),Y1=O(M4+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=MQ(Q,_.map((m)=>m.ez));return _.map((m,V$)=>m.toAffine(C[V$])).map(L.fromAffine)}static msm(_,C){return mw(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$),M4=O(z$*V$);return Z$===W4&&Z4===M4}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$),M4=Z$+z$,p4=M4-R$,a4=Z$-z$,Y1=O(Z4*p4),d1=O(M4*a4),s4=O(Z4*a4),L6=O(p4*M4);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:M4}=_,p4=O(V$*Z$),a4=O(K$*W4),Y1=O(R$*m*M4),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$),M4=O(Z4-U6),p4=O(m*Z4-V$),{isValid:a4,value:Y1}=M(M4,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=uw(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 M4=A1(Z$,h5(Z4,Q.BYTES));return A4("result",M4,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,M4;try{W4=L.fromHex(m,z$),Z4=L.fromHex(_.slice(0,R$),z$),M4=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(M4).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}}}}M9();/*! 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,w=u4(N,Q,G)*N%G,M=u4(w,Y,G)*w%G,z=u4(M,X,G)*M%G,q=u4(z,X,G)*M%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),w=D===G4(-$*Wu,Q);if(O)W=V;if(N||w)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$}))(),lw=(()=>Ju(n7$))();QV();W0();function dw(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=lw.utils.randomPrivateKey();return{publicKey:lw.getPublicKey($),privateKey:$}}function pw($){return Y9($.publicKey)}function nw($){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
|
|
@@ -143,7 +143,7 @@ ${J}`}function cw($,J){return Y9(lw.sign(b5(J),$))}var DV=[0.0001,0.001,0.01,0.1
|
|
|
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 wS extends h{constructor({domain:$}){super(`Invalid domain "${D4($)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class MS 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],w=O.match(NM);if(w&&(typeof N==="number"||typeof N==="bigint")){let[q,F,Z]=w;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 M=O.match(pm);if(M){let[q,F]=M;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 wS({domain:J});G(X.EIP712Domain,J)}if(Y!=="EIP712Domain")if(X[Y])G(X[Y],Q);else throw new MS({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 w6(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(w6(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((w)=>w.id===Y))return;let N=ln.get($);if(O.length===1&&N){let w=N();if(w instanceof Promise)w.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 w=X();if(w.length===0)return;for(let M of w)M.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},(w)=>PJ(async()=>{try{let M=await W$($,CJ,"getBlockNumber")({cacheTime:0});if(V!==void 0){if(M===V)return;if(M-V>1&&Q)for(let z=V+1n;z<M;z++)w.onBlockNumber(z,V),V=z}if(V===void 0||M>V)w.onBlockNumber(M,V),V=M}catch(M){w.onError?.(M)}},{emitOnBegin:J,interval:W}))})():(()=>{let N=D4(["watchBlockNumber",$.uid,J,Q]);return y6(N,{onBlockNumber:Y,onError:X},(w)=>{let M=!0,z=()=>M=!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(!M)return;let E=f1(Z.result?.number);w.onBlockNumber(E,V),V=E},onError(Z){w.onError?.(Z)}});if(z=F,!M)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,w,M,z=!1,q,F,{promise:Z,resolve:E,reject:B}=lM(),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(M=await W$($,dG,"getTransactionReceipt")({hash:X}).catch(()=>{return}),M&&Y<=1){clearTimeout(L),j.resolve(M),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(M){if(Y>1&&(!M.blockNumber||f-M.blockNumber+1n<Y))return;x(()=>j.resolve(M));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(M=await W$($,dG,"getTransactionReceipt")({hash:X}),Y>1&&(!M.blockNumber||f-M.blockNumber+1n<Y))return;x(()=>j.resolve(M))}catch(u){if(u instanceof EV||u instanceof SV){if(!N){z=!1;return}try{w=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$===w.from&&c===w.nonce);if(!d)return;if(M=await W$($,dG,"getTransactionReceipt")({hash:d.hash}),Y>1&&(!M.blockNumber||f-M.blockNumber+1n<Y))return;let p="replaced";if(d.to===w.to&&d.value===w.value&&d.input===w.input)p="repriced";else if(d.from===d.to&&d.value===0n)p="cancelled";x(()=>{j.onReplaced?.({reason:p,replacedTransaction:w,transaction:d,transactionReceipt:M}),j.resolve(M)})}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:w}=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=w??!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$($,oM,"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=w??!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:w}),p=L1(u,{args:d,eventName:R});L.onLogs([p])}catch(R){let d,p;if(R instanceof h8||R instanceof A9){if(w)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 w=(()=>{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})(),M=N??!1;return w?(()=>{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$($,rM,"createEventFilter")({address:J,args:Q,event:X,events:G,strict:M,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:M}),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,w=PJ(async()=>{try{if(!N)try{N=await W$($,tM,"createPendingTransactionFilter")({});return}catch(z){throw w(),z}let M=await W$($,JX,"getFilterChanges")({filter:N});if(M.length===0)return;if(J)O.onTransactions(M);else for(let z of M)O.onTransactions([z])}catch(M){O.onError?.(M)}},{emitOnBegin:!0,interval:G});return async()=>{if(N)await W$($,XX,"uninstallFilter")({filter:N});w()}})})():(()=>{let K=!0,O=()=>K=!1;return(async()=>{try{let{unsubscribe:N}=await $.transport.subscribe({params:["newPendingTransactions"],onData(w){if(!K)return;let M=w.result;Y([M])},onError(w){Q?.(w)}});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
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 w=EH(X);return GX($,{address:O.address,hash:w,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)=>iM($,J),createBlockFilter:()=>hd($),createContractEventFilter:(J)=>oM($,J),createEventFilter:(J)=>rM($,J),createPendingTransactionFilter:()=>tM($),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)=>cM($,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)=>wn($,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:w,signal:M}=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:w||"POST",signal:M||(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 vM({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 vM)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 w=N;switch(w.code){case GG.code:throw new GG(w);case WG.code:throw new WG(w);case DG.code:throw new DG(w,{method:Q.method});case VG.code:throw new VG(w);case PQ.code:throw new PQ(w);case N0.code:throw new N0(w);case KG.code:throw new KG(w);case UG.code:throw new UG(w);case OG.code:throw new OG(w);case n8.code:throw new n8(w,{method:Q.method});case T9.code:throw new T9(w);case NG.code:throw new NG(w);case R9.code:throw new R9(w);case wG.code:throw new wG(w);case MG.code:throw new MG(w);case HG.code:throw new HG(w);case AG.code:throw new AG(w);case zG.code:throw new zG(w);case IG.code:throw new IG(w);case qG.code:throw new qG(w);case ZG.code:throw new ZG(w);case LG.code:throw new LG(w);case BG.code:throw new BG(w);case FG.code:throw new FG(w);case jG.code:throw new jG(w);case 5000:throw new R9(w);case EG.code:throw new EG(w);default:if(N instanceof h)throw N;throw new pj(w)}}},{delay:({count:N,error:w})=>{if(w&&w instanceof c0){let M=w?.headers?.get("Retry-After");if(M?.match(/\d/))return Number.parseInt(M,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=aw();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:w,retryCount:M,timeout:z})=>{let{batchSize:q=1000,wait:F=0}=typeof Q==="object"?Q:{},Z=J.retryCount??M,E=z??J.timeout??1e4,B=$||w?.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}=dM({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(ow(),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:w}=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:w})}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=cw(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:
|
|
145
145
|
- ${J.join(`
|
|
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"]}),wc=A.object({orderId:S$}),Mc=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()}),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$(wc,{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$(Mc,{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:$M,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,w={hash:O,status:"pending",nonce:N};return await this.waitForTransaction(w,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})}),O=await this.pollWithdrawalCalldata(K,V);if(!O)return{withdrawalIndex:K,status:"awaiting_proof"};let{vaultAddress:N,calldata:w}=O,M;try{M=await this.walletClient.sendTransaction({to:N,data:w,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:M,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:$M,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=dw(),X={publicKey:pw(Y),privateKey:nw(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=dw(),Q={publicKey:pw(J),privateKey:nw(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,w=$.cacheTime??N,M=$.account?K4($.account):void 0,{config:z,request:q,value:F}=$.transport({account:M,chain:Q,pollingInterval:N}),Z={...z,...F},E={account:M,batch:J,cacheTime:w,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(`
|
|
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"]}),wc=A.object({orderId:S$}),Mc=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$(wc,{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$(Mc,{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:$M,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,w={hash:O,status:"pending",nonce:N};return await this.waitForTransaction(w,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:w}=O,M;try{M=await this.walletClient.sendTransaction({to:N,data:w,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:M,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:$M,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=dw(),X={publicKey:pw(Y),privateKey:nw(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=dw(),Q={publicKey:pw(J),privateKey:nw(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,w=$.cacheTime??N,M=$.account?K4($.account):void 0,{config:z,request:q,value:F}=$.transport({account:M,chain:Q,pollingInterval:N}),Z={...z,...F},E={account:M,batch:J,cacheTime:w,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 wK 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(wK,"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 MK 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(MK,"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(`
|
|
148
148
|
`),{cause:$,name:"NonceTooLowError"})}}Object.defineProperty(HK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class AK extends l{constructor({cause:$,nonce:J}={}){super(`Nonce provided for the transaction ${J?`(${J}) `:""}exceeds the maximum allowed nonce.`,{cause:$,name:"NonceMaxValueError"})}}Object.defineProperty(AK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class zK extends l{constructor({cause:$}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
|
|
149
149
|
`),{cause:$,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(zK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class IK extends l{constructor({cause:$,gas:J}={}){super(`The amount of gas ${J?`(${J}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:$,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(IK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class qK extends l{constructor({cause:$,gas:J}={}){super(`The amount of gas ${J?`(${J}) `:""}provided for the transaction is too low.`,{cause:$,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(qK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class ZK extends l{constructor({cause:$}){super("The transaction type is not supported for this chain.",{cause:$,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(ZK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class fQ extends l{constructor({cause:$,maxPriorityFeePerGas:J,maxFeePerGas:Q}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${J?` = ${I6(J)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${Q?` = ${I6(Q)} gwei`:""}).`].join(`
|
|
@@ -166,4 +166,4 @@ ${J}`}function cw($,J){return Y9(lw.sign(b5(J),$))}var DV=[0.0001,0.001,0.01,0.1
|
|
|
166
166
|
`),{name:"ChainNotFoundError"})}}class Z7 extends l{constructor({chainId:$}){super(typeof $==="number"?`Chain ID "${$}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}function L7({chain:$,currentChainId:J}){if(!$)throw new F_;if(J!==$.id)throw new B_({chain:$,currentChainId:J})}async function HA($){let J=await $.request({method:"eth_gasPrice"});return BigInt(J)}async function Li($,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 k$($,e0,"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 B1(W)}catch{let[G,W]=await Promise.all([Q?Promise.resolve(Q):k$($,e0,"getBlock")({}),k$($,HA,"getGasPrice")({})]);if(typeof G.baseFeePerGas!=="bigint")throw new c9;let D=W-G.baseFeePerGas;if(D<0n)return 0n;return D}}async function j_($,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 NK;let V=10**(W.toString().split(".")[1]?.length??0),K=(w)=>w*BigInt(Math.ceil(W*V))/BigInt(V),O=Q?Q:await k$($,e0,"getBlock")({});if(typeof Y?.fees?.estimateFeesPerGas==="function"){let w=await Y.fees.estimateFeesPerGas({block:Q,client:$,multiply:K,request:X,type:G});if(w!==null)return w}if(G==="eip1559"){if(typeof O.baseFeePerGas!=="bigint")throw new c9;let w=typeof X?.maxPriorityFeePerGas==="bigint"?X.maxPriorityFeePerGas:await Li($,{block:O,chain:Y,request:X}),M=K(O.baseFeePerGas);return{maxFeePerGas:X?.maxFeePerGas??M+w,maxPriorityFeePerGas:w}}return{gasPrice:X?.gasPrice??K(await k$($,HA,"getGasPrice")({}))}}class E_ extends l{constructor($,{account:J,docsPath:Q,chain:Y,data:X,gas:G,gasPrice:W,maxFeePerGas:D,maxPriorityFeePerGas:V,nonce:K,to:O,value:N}){let w=oG({from:J?.address,to:O,value:typeof N<"u"&&`${sH(N)} ${Y?.nativeCurrency?.symbol||"ETH"}`,data:X,gas:G,gasPrice:typeof W<"u"&&`${I6(W)} gwei`,maxFeePerGas:typeof D<"u"&&`${I6(D)} gwei`,maxPriorityFeePerGas:typeof V<"u"&&`${I6(V)} gwei`,nonce:K});super($.shortMessage,{cause:$,docsPath:Q,metaMessages:[...$.metaMessages?[...$.metaMessages," "]:[],"Estimate Gas Arguments:",w].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=$}}function Bi($,{docsPath:J,...Q}){let Y=(()=>{let X=JA($,Q);if(X instanceof i9)return $;return X})();return new E_(Y,{docsPath:J,...Q})}class S_ extends l{constructor({address:$}){super(`State for account "${$}" is set multiple times.`,{name:"AccountStateConflictError"})}}class __ extends l{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Fi($){if(!$||$.length===0)return;return $.reduce((J,{slot:Q,value:Y})=>{if(Q.length!==66)throw new YA({size:Q.length,targetSize:66,type:"hex"});if(Y.length!==66)throw new YA({size:Y.length,targetSize:66,type:"hex"});return J[Q]=Y,J},{})}function FU$($){let{balance:J,nonce:Q,state:Y,stateDiff:X,code:G}=$,W={};if(G!==void 0)W.code=G;if(J!==void 0)W.balance=X$(J);if(Q!==void 0)W.nonce=X$(Q);if(Y!==void 0)W.state=Fi(Y);if(X!==void 0){if(W.state)throw new __;W.stateDiff=Fi(X)}return W}function ji($){if(!$)return;let J={};for(let{address:Q,...Y}of $){if(!S4(Q,{strict:!1}))throw new y4({address:Q});if(J[Q])throw new S_({address:Q});J[Q]=FU$(Y)}return J}async function Ei($,J){let{account:Q=$.account,prepare:Y=!0}=J,X=Q?K4(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 q7({authorization:J.authorizationList[0]}).catch(()=>{throw new l("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:D,authorizationList:V,blobs:K,blobVersionedHashes:O,blockNumber:N,blockTag:w,data:M,gas:z,gasPrice:q,maxFeePerBlobGas:F,maxFeePerGas:Z,maxPriorityFeePerGas:E,nonce:B,value:L,stateOverride:j,...T}=Y?await AX($,{...J,parameters:G,to:W}):J;if(z&&J.gas!==z)return z;let f=(typeof N==="bigint"?X$(N):void 0)||w,u=ji(j);z0(J);let R=$.chain?.formatters?.transactionRequest?.format,p=(R||kJ)({...wX(T,{format:R}),account:X,accessList:D,authorizationList:V,blobs:K,blobVersionedHashes:O,data:M,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 Bi(W,{...J,account:X,chain:$.chain})}}function Si($){let{blockHash:J,blockNumber:Q,blockTag:Y,requireCanonical:X}=$;if(X!==void 0&&!J)throw new l("`requireCanonical` can only be provided when `blockHash` is set.");if(J)return X?{blockHash:J,requireCanonical:X}:{blockHash:J};if(typeof Q==="bigint")return X$(Q);return Y??"latest"}async function AA($,{address:J,blockHash:Q,blockNumber:Y,blockTag:X="latest",requireCanonical:G}){let W=Si({blockHash:Q,blockNumber:Y,blockTag:X,requireCanonical:G}),D=await $.request({method:"eth_getTransactionCount",params:[J,W]},{dedupe:typeof Y==="bigint"||Q!==void 0});return F1(D)}function B7($){let{kzg:J}=$,Q=$.to??(typeof $.blobs[0]==="string"?"hex":"bytes"),Y=typeof $.blobs[0]==="string"?$.blobs.map((G)=>w1(G)):$.blobs,X=[];for(let G of Y)X.push(Uint8Array.from(J.blobToKzgCommitment(G)));return Q==="bytes"?X:X.map((G)=>k4(G))}function F7($){let{kzg:J}=$,Q=$.to??(typeof $.blobs[0]==="string"?"hex":"bytes"),Y=typeof $.blobs[0]==="string"?$.blobs.map((W)=>w1(W)):$.blobs,X=typeof $.commitments[0]==="string"?$.commitments.map((W)=>w1(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)=>k4(W))}function _i($,J){let Q=J||"hex",Y=WH(u1($,{strict:!1})?H7($):$);if(Q==="bytes")return Y;return m1(Y)}function Ti($){let{commitment:J,version:Q=1}=$,Y=$.to??(typeof J==="string"?"hex":"bytes"),X=_i(J,"bytes");return X.set([Q],0),Y==="bytes"?X:k4(X)}function zA($){let{commitments:J,version:Q}=$,Y=$.to??(typeof J[0]==="string"?"hex":"bytes"),X=[];for(let G of J)X.push(Ti({commitment:G,to:Y,version:Q}));return X}var Ri=32,Ci=4096,Pi=131072,T_=761855;var IA=1;class R_ extends l{constructor({maxSize:$,size:J}){super("Blob size is too large.",{metaMessages:[`Max: ${$} bytes`,`Given: ${J} bytes`],name:"BlobSizeTooLargeError"})}}class EK extends l{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class C_ extends l{constructor({hash:$,size:J}){super(`Versioned hash "${$}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${J}`],name:"InvalidVersionedHashSizeError"})}}class P_ extends l{constructor({hash:$,version:J}){super(`Versioned hash "${$}" version is invalid.`,{metaMessages:[`Expected: ${IA}`,`Received: ${J}`],name:"InvalidVersionedHashVersionError"})}}function vi($){let J=$.to??(typeof $.data==="string"?"hex":"bytes"),Q=typeof $.data==="string"?w1($.data):$.data,Y=U4(Q);if(!Y)throw new EK;if(Y>T_)throw new R_({maxSize:T_,size:Y});let X=[],G=!0,W=0;while(G){let D=I7(new Uint8Array(Pi)),V=0;while(V<Ci){let K=Q.slice(W,W+(Ri-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)=>k4(D.bytes))}function qA($){let{data:J,kzg:Q,to:Y}=$,X=$.blobs??vi({data:J,to:Y}),G=$.commitments??B7({blobs:X,kzg:Q,to:Y}),W=$.proofs??F7({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}function ZA($){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 iS({transaction:$})}var SK=["blobVersionedHashes","chainId","fees","gas","nonce","type"],ki=new Map,v_=new o6(128);async function AX($,J){let Q=J;Q.account??=$.account,Q.parameters??=SK;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 k$($,t1,"getChainId")({}),V}let O=Y?K4(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},{client:$,phase:"beforeFillTransaction"}),N??=Q.nonce;let M=(()=>{if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&Q.kzg&&Q.blobs)return!1;if(v_.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 k$($,GA,"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 v_.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")}))v_.set($.uid,!1);return Q}):Q;N??=M.nonce,Q={...M,...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},{client:$,phase:"beforeFillParameters"});let E;async function B(){if(E)return E;return E=await k$($,e0,"getBlock")({blockTag:"latest"}),E}if(W.includes("nonce")&&typeof N>"u"&&O&&!G)Q.nonce=await k$($,AA,"getTransactionCount")({address:O.address,blockTag:"pending"});if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&z&&F){let L=B7({blobs:z,kzg:F});if(W.includes("blobVersionedHashes")){let j=zA({commitments:L,to:"hex"});Q.blobVersionedHashes=j}if(W.includes("sidecars")){let j=F7({blobs:z,commitments:L,kzg:F}),T=qA({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=ZA(Q)}catch{let L=ki.get($.uid);if(typeof L>"u")L=typeof(await B())?.baseFeePerGas==="bigint",ki.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 j_($,{block:L,chain:X,request:Q});if(typeof Q.maxPriorityFeePerGas>"u"&&Q.maxFeePerGas&&Q.maxFeePerGas<T)throw new nS({maxPriorityFeePerGas:T});Q.maxPriorityFeePerGas=T,Q.maxFeePerGas=j}}else{if(typeof Q.maxFeePerGas<"u"||typeof Q.maxPriorityFeePerGas<"u")throw new c9;if(typeof Q.gasPrice>"u"){let L=await B(),{gasPrice:j}=await j_($,{block:L,chain:X,request:Q,type:"legacy"});Q.gasPrice=j}}if(W.includes("gas")&&typeof q>"u")Q.gas=await k$($,Ei,"estimateGas")({...Q,account:O,prepare:O?.type==="local"?[]:["blobVersionedHashes"]});if(D?.fn&&D.runAt?.includes("afterFillParameters"))Q=await D.fn({...Q,chain:X},{client:$,phase:"afterFillParameters"});return z0(Q),delete Q.parameters,Q}async function LA($,{serializedTransaction:J}){return $.request({method:"eth_sendRawTransaction",params:[J]},{retryCount:0})}var k_=new o6(128);async function zX($,J){let{account:Q=$.account,assertChainId:Y=!0,chain:X=$.chain,accessList:G,authorizationList:W,blobs:D,data:V,dataSuffix:K=typeof $.dataSuffix==="string"?$.dataSuffix:$.dataSuffix?.value,gas:O,gasPrice:N,maxFeePerBlobGas:w,maxFeePerGas:M,maxPriorityFeePerGas:z,nonce:q,type:F,value:Z,...E}=J;if(typeof Q>"u")throw new l1({docsPath:"/docs/actions/wallet/sendTransaction"});let B=Q?K4(Q):null,L;try{z0(J);let j=await(async()=>{if(J.to)return J.to;if(J.to===null)return;if(W&&W.length>0)return await q7({authorization:W[0]}).catch(()=>{throw new l("`to` is required. Could not infer from `authorizationList`.")});return})();if(B?.type==="json-rpc"||B===null){let T;if(X!==null){if(T=await k$($,t1,"getChainId")({}),Y)L7({currentChainId:T,chain:X})}let x=$.chain?.formatters?.transactionRequest?.format,u=(x||kJ)({...wX(E,{format:x}),accessList:G,account:B,authorizationList:W,blobs:D,chainId:T,data:K?V1([V??"0x",K]):V,gas:O,gasPrice:N,maxFeePerBlobGas:w,maxFeePerGas:M,maxPriorityFeePerGas:z,nonce:q,to:j,type:F,value:Z},"sendTransaction"),R=k_.get($.uid),d=R?"wallet_sendTransaction":"eth_sendTransaction";try{return await $.request({method:d,params:[u]},{retryCount:0})}catch(p){if(R===!1)throw p;let Y$=p;if(Y$.name==="InvalidInputRpcError"||Y$.name==="InvalidParamsRpcError"||Y$.name==="MethodNotFoundRpcError"||Y$.name==="MethodNotSupportedRpcError")return await $.request({method:"wallet_sendTransaction",params:[u]},{retryCount:0}).then((c)=>{return k_.set($.uid,!0),c}).catch((c)=>{let k=c;if(k.name==="MethodNotFoundRpcError"||k.name==="MethodNotSupportedRpcError")throw k_.set($.uid,!1),Y$;throw k});throw Y$}}if(B?.type==="local"){if(B.nonceManager&&typeof q>"u"){let u=E.chainId,R=await(async()=>{if(typeof u==="number")return u;if(X)return X.id;return k$($,t1,"getChainId")({})})();L={address:B.address,chainId:R}}let T=await k$($,AX,"prepareTransactionRequest")({account:B,accessList:G,authorizationList:W,blobs:D,chain:X,data:K?V1([V??"0x",K]):V,gas:O,gasPrice:N,maxFeePerBlobGas:w,maxFeePerGas:M,maxPriorityFeePerGas:z,nonce:q,nonceManager:B.nonceManager,parameters:[...SK,"sidecars"],type:F,value:Z,...E,to:j}),x=X?.serializers?.transaction,f=await B.signTransaction(T,{serializer:x});return await k$($,LA,"sendRawTransaction")({serializedTransaction:f})}if(B?.type==="smart")throw new $J({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new $J({docsPath:"/docs/actions/wallet/sendTransaction",type:B?.type})}catch(j){if(j instanceof $J)throw j;if(L)B?.nonceManager?.reset(L);throw NX(j,{...J,account:B,chain:J.chain||void 0})}}function xi($,J){let{abi:Q,args:Y,bytecode:X,...G}=J,W=Hi({abi:Q,args:Y,bytecode:X});return zX($,{...G,...G.authorizationList?{to:null}:{},data:W})}async function fi($){if($.account?.type==="local")return[$.account.address];return(await $.request({method:"eth_accounts"},{dedupe:!0})).map((Q)=>uQ(Q))}function bi($,{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}:{}}}var x_={"0x0":"reverted","0x1":"success"};function BA($,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)=>bi(Y)):null,to:$.to?$.to:null,transactionIndex:$.transactionIndex?F1($.transactionIndex):null,status:$.status?x_[$.status]:null,type:$.type?Q_[$.type]||$.type:null};if($.blobGasPrice)Q.blobGasPrice=BigInt($.blobGasPrice);if($.blobGasUsed)Q.blobGasUsed=BigInt($.blobGasUsed);return Q}var jU$=($)=>D1(H7($));function gi($){return jU$($)}a5();function yi($){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",""].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 l("Unable to normalize signature.");return X}var hi=($)=>{let J=(()=>{if(typeof $==="string")return $;return EQ($)})();return yi(J)};function FA($){return gi(hi($))}var j7=($)=>mQ(FA($),0,4);var ui=FA;function jA($){let{abi:J,args:Q=[],name:Y}=$,X=u1(Y,{strict:!1}),G=J.filter((D)=>{if(X){if(D.type==="function")return j7(D)===Y;if(D.type==="event")return ui(D)===Y;return!1}return"name"in D&&D.name===Y});if(G.length===0)return;if(G.length===1)return G[0];let W;for(let D of G){if(!("inputs"in D))continue;if(!Q||Q.length===0){if(!D.inputs||D.inputs.length===0)return D;continue}if(!D.inputs)continue;if(D.inputs.length===0)continue;if(D.inputs.length!==Q.length)continue;if(Q.every((K,O)=>{let N="inputs"in D&&D.inputs[O];if(!N)return!1;return f_(K,N)})){if(W&&"inputs"in W&&W.inputs){let K=mi(D.inputs,W.inputs,Q);if(K)throw new O_({abiItem:D,type:K[0]},{abiItem:W,type:K[1]})}W=D}}if(W)return W;return G[0]}function f_($,J){let Q=typeof $,Y=J.type;switch(Y){case"address":return S4($,{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 Q==="object"&&f_(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)=>f_(X,{...J,type:Y.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function mi($,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 mi(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 S4(Q[Y],{strict:!1});if(W.includes("address")&&W.includes("bytes"))return S4(Q[Y],{strict:!1});return!1})())return W}return}var li="/docs/contract/encodeFunctionData";function di($){let{abi:J,args:Q,functionName:Y}=$,X=J[0];if(Y){let G=jA({abi:J,args:Q,name:Y});if(!G)throw new VA(Y,{docsPath:li});X=G}if(X.type!=="function")throw new VA(void 0,{docsPath:li});return{abi:[X],functionName:j7(xJ(X))}}function EA($){let{args:J}=$,{abi:Q,functionName:Y}=(()=>{if($.abi.length===1&&$.functionName?.startsWith("0x"))return $;return di($)})(),X=Q[0],G=Y,W="inputs"in X&&X.inputs?e9(X.inputs,J??[]):void 0;return I0([G,W??"0x"])}var b_="0x5792579257925792579257925792579257925792579257925792579257925792",g_=X$(0,{size:32});async function SA($,J){let{account:Q=$.account,chain:Y=$.chain,experimental_fallback:X,experimental_fallbackDelay:G=32,forceAtomic:W=!1,id:D,version:V="2.0.0"}=J,K=Q?K4(Q):null,O=J.capabilities;if($.dataSuffix&&!J.capabilities?.dataSuffix)if(typeof $.dataSuffix==="string")O={...J.capabilities,dataSuffix:{value:$.dataSuffix,optional:!0}};else O={...J.capabilities,dataSuffix:{value:$.dataSuffix.value,...$.dataSuffix.required?{}:{optional:!0}}};let N=J.calls.map((w)=>{let M=w,z=M.abi?EA({abi:M.abi,functionName:M.functionName,args:M.args}):M.data;return{data:M.dataSuffix&&z?V1([z,M.dataSuffix]):z,to:M.to,value:M.value?X$(M.value):void 0}});try{let w=await $.request({method:"wallet_sendCalls",params:[{atomicRequired:W,calls:N,capabilities:O,chainId:X$(Y.id),from:K?.address,id:D,version:V}]},{retryCount:0});if(typeof w==="string")return{id:w};return w}catch(w){let M=w;if(X&&(M.name==="MethodNotFoundRpcError"||M.name==="MethodNotSupportedRpcError"||M.name==="UnknownRpcError"||M.details.toLowerCase().includes("does not exist / is not available")||M.details.toLowerCase().includes("missing or invalid. request()")||M.details.toLowerCase().includes("did not match any variant of untagged enum")||M.details.toLowerCase().includes("account upgraded to unsupported contract")||M.details.toLowerCase().includes("eip-7702 not supported")||M.details.toLowerCase().includes("unsupported wc_ method")||M.details.toLowerCase().includes("feature toggled misconfigured")||M.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(O){if(Object.values(O).some((Z)=>!Z.optional))throw new UX(new l("non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.",{details:"non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`."}))}if(W&&N.length>1)throw new OX(new l("`forceAtomic` is not supported on fallback to `eth_sendTransaction`.",{details:"`forceAtomic` is not supported on fallback to `eth_sendTransaction`."}));let z=[];for(let F of N){try{let Z=await zX($,{account:K,chain:Y,data:F.data,to:F.to,value:F.value?B1(F.value):void 0});z.push({status:"fulfilled",value:Z})}catch(Z){z.push({reason:Z,status:"rejected"})}if(G>0)await new Promise((Z)=>setTimeout(Z,G))}if(z.every((F)=>F.status==="rejected"))throw z[0].reason;let q=z.map((F)=>{if(F.status==="fulfilled")return F.value;return g_});return{id:V1([...q,X$(Y.id,{size:32}),b_])}}throw NX(w,{...J,account:K,chain:J.chain})}}async function _A($,J){async function Q(O){if(O.endsWith(b_.slice(2))){let w=A0(KA(O,-64,-32)),M=KA(O,0,-64).slice(2).match(/.{1,64}/g),z=await Promise.all(M.map((F)=>g_.slice(2)!==F?$.request({method:"eth_getTransactionReceipt",params:[`0x${F}`]},{dedupe:!0}):void 0)),q=(()=>{if(z.some((F)=>F===null))return 100;if(z.every((F)=>F?.status==="0x1"))return 200;if(z.every((F)=>F?.status==="0x0"))return 500;return 600})();return{atomic:!1,chainId:F1(w),receipts:z.filter(Boolean),status:q,version:"2.0.0"}}return $.request({method:"wallet_getCallsStatus",params:[O]})}let{atomic:Y=!1,chainId:X,receipts:G,version:W="2.0.0",...D}=await Q(J.id),[V,K]=(()=>{let O=D.status;if(O>=100&&O<200)return["pending",O];if(O>=200&&O<300)return["success",O];if(O>=300&&O<700)return["failure",O];if(O==="CONFIRMED")return["success",200];if(O==="PENDING")return["pending",100];return[void 0,O]})();return{...D,atomic:Y,chainId:X?F1(X):void 0,receipts:G?.map((O)=>({...O,blockNumber:B1(O.blockNumber),gasUsed:B1(O.gasUsed),status:x_[O.status]}))??[],statusCode:K,status:V,version:W}}async function pi($,J={}){let{account:Q=$.account,chainId:Y}=J,X=Q?K4(Q):void 0,G=Y?[X?.address,[X$(Y)]]:[X?.address],W=await $.request({method:"wallet_getCapabilities",params:G}),D={};for(let[V,K]of Object.entries(W)){D[Number(V)]={};for(let[O,N]of Object.entries(K)){if(O==="addSubAccount")O="unstable_addSubAccount";D[Number(V)][O]=N}}return typeof Y==="number"?D[Y]:D}async function ni($){return await $.request({method:"wallet_getPermissions"},{dedupe:!0})}function ci($,J){if(!S4($,{strict:!1}))throw new y4({address:$});if(!S4(J,{strict:!1}))throw new y4({address:J});return $.toLowerCase()===J.toLowerCase()}async function TA($,J){let{account:Q=$.account,chainId:Y,nonce:X}=J;if(!Q)throw new l1({docsPath:"/docs/eip7702/prepareAuthorization"});let G=K4(Q),W=(()=>{if(!J.executor)return;if(J.executor==="self")return J.executor;return K4(J.executor)})(),D={address:J.contractAddress??J.address,chainId:Y,nonce:X};if(typeof D.chainId>"u")D.chainId=$.chain?.id??await k$($,t1,"getChainId")({});if(typeof D.nonce>"u"){if(D.nonce=await k$($,AA,"getTransactionCount")({address:G.address,blockTag:"pending"}),W==="self"||W?.address&&ci(W.address,G.address))D.nonce+=1}return D}async function ii($){return(await $.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map((Q)=>Ki(Q))}async function oi($,J){return $.request({method:"wallet_requestPermissions",params:[J]},{retryCount:0})}class y_ extends l{constructor($){super(`Call bundle failed with status: ${$.statusCode}`,{name:"BundleFailedError"});Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=$}}var RA=new Map,h_=new Map,EU$=0;function $Y($,J,Q){let Y=++EU$,X=()=>RA.get($)||[],G=()=>{let N=X().filter((w)=>w.id!==Y);if(N.length===0){RA.delete($),h_.delete($);return}RA.set($,N)},W=()=>{let O=X();if(!O.some((w)=>w.id===Y))return;let N=h_.get($);if(O.length===1&&N){let w=N();if(w instanceof Promise)w.catch(()=>{})}G()},D=X();if(RA.set($,[...D,{id:Y,fns:J}]),D&&D.length>0)return W;let V={};for(let O in J)V[O]=(...N)=>{let w=X();if(w.length===0)return;for(let M of w)M.fns[O]?.(...N)};let K=Q(V);if(typeof K==="function")h_.set($,K);return W}async function _K($,{signal:J}={}){return new Promise((Q,Y)=>{if(J?.aborted){Y(s0(J));return}let X=()=>J?.removeEventListener("abort",W),G=setTimeout(()=>{X(),Q()},$),W=()=>{clearTimeout(G),X(),Y(s0(J))};J?.addEventListener("abort",W,{once:!0})})}function CA($,{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 _K(V);let K=async()=>{if(!X)return;await $({unpoll:G}),await _K(Y),K()};K()})(),G}function E7(){let $=()=>{return},J=()=>{return};return{promise:new Promise((Y,X)=>{$=Y,J=X}),resolve:$,reject:J}}function JY($,{delay:J=100,retryCount:Q=2,shouldRetry:Y=()=>!0,signal:X}={}){return new Promise((G,W)=>{let D=async({count:V=0}={})=>{if(X?.aborted){W(s0(X));return}let K=async({error:O})=>{let N=typeof J==="function"?J({count:V,error:O}):J;if(N)try{await _K(N,{signal:X})}catch(w){W(w);return}D({count:V+1})};try{let O=await $();G(O)}catch(O){if(X?.aborted){W(s0(X));return}if(bQ(O)){W(O);return}if(V<Q&&await Y({count:V,error:O}))return K({error:O});W(O)}};D()})}async function PA($,J){let{id:Q,pollingInterval:Y=$.pollingInterval,status:X=({statusCode:q})=>q===200||q>=300,retryCount:G=4,retryDelay:W=({count:q})=>~~(1<<q)*200,timeout:D=60000,throwOnFailure:V=!1}=J,K=i4(["waitForCallsStatus",$.uid,Q]),{promise:O,resolve:N,reject:w}=E7(),M,z=$Y(K,{resolve:N,reject:w},(q)=>{let F=CA(async()=>{let Z=(E)=>{clearTimeout(M),F(),E(),z()};try{let E=await JY(async()=>{let B=await k$($,_A,"getCallsStatus")({id:Q});if(V&&B.status==="failure")throw new y_(B);return B},{retryCount:G,delay:W});if(!X(E))return;Z(()=>q.resolve(E))}catch(E){Z(()=>q.reject(E))}},{interval:Y,emitOnBegin:!0});return F});return M=D?setTimeout(()=>{z(),clearTimeout(M),w(new ri({id:Q}))},D):void 0,await O}class ri extends l{constructor({id:$}){super(`Timed out while waiting for call bundle with id "${$}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}async function ti($,J){let{chain:Q=$.chain}=J,Y=J.timeout??Math.max((Q?.blockTime??0)*3,5000),X=await k$($,SA,"sendCalls")(J);return await k$($,PA,"waitForCallsStatus")({...J,id:X.id,timeout:Y})}async function vA($,{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||BA)(X);if(W.status==="reverted"&&Q)throw new rG({receipt:W});return W}async function ai($,{blockHash:J,blockNumber:Q,blockTag:Y,hash:X,index:G,sender:W,nonce:D}){let V=Y||"latest",K=Q!==void 0?X$(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,X$(G)]},{dedupe:!0});else if((K||V)&&typeof G==="number")O=await $.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[K||V,X$(G)]},{dedupe:Boolean(K)});else if(W&&typeof D==="number")O=await $.request({method:"eth_getTransactionBySenderAndNonce",params:[W,X$(D)]},{dedupe:!0});if(!O)throw new LK({blockHash:J,blockNumber:Q,blockTag:V,hash:X,index:G});return($.chain?.formatters?.transaction?.format||A7)(O,"getTransaction")}async function kA($,{hash:J}){let Q=await $.request({method:"eth_getTransactionReceipt",params:[J]},{dedupe:!0});if(!Q)throw new BK({hash:J});return($.chain?.formatters?.transactionReceipt?.format||BA)(Q,"getTransactionReceipt")}var SU$=new Map,_U$=new Map;function si($){let J=(X,G)=>({clear:()=>G.delete(X),get:()=>G.get(X),set:(W)=>G.set(X,W)}),Q=J($,SU$),Y=J($,_U$);return{clear:()=>{Q.clear(),Y.clear()},promise:Q,response:Y}}async function ei($,{cacheKey:J,cacheTime:Q=Number.POSITIVE_INFINITY}){let Y=si(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 TU$=($)=>`blockNumber.${$}`;async function $o($,{cacheTime:J=$.cacheTime}={}){let Q=await ei(()=>$.request({method:"eth_blockNumber"}),{cacheKey:TU$($.uid),cacheTime:J});return BigInt(Q)}function Jo($,{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=i4(["watchBlockNumber",$.uid,J,Q,W]);return $Y(N,{onBlockNumber:Y,onError:X},(w)=>CA(async()=>{try{let M=await k$($,$o,"getBlockNumber")({cacheTime:0});if(V!==void 0){if(M===V)return;if(M-V>1&&Q)for(let z=V+1n;z<M;z++)w.onBlockNumber(z,V),V=z}if(V===void 0||M>V)w.onBlockNumber(M,V),V=M}catch(M){w.onError?.(M)}},{emitOnBegin:J,interval:W}))})():(()=>{let N=i4(["watchBlockNumber",$.uid,J,Q]);return $Y(N,{onBlockNumber:Y,onError:X},(w)=>{let M=!0,z=()=>M=!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(!M)return;let E=B1(Z.result?.number);w.onBlockNumber(E,V),V=E},onError(Z){w.onError?.(Z)}});if(z=F,!M)z()}catch(q){X?.(q)}})(),()=>z()})})()}async function Qo($,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=i4(["waitForTransactionReceipt",$.uid,X]),O=(()=>{if(J.pollingInterval)return J.pollingInterval;if($.chain?.experimental_preconfirmationTime)return $.chain.experimental_preconfirmationTime;return $.pollingInterval})(),N,w,M,z=!1,q,F,{promise:Z,resolve:E,reject:B}=E7(),L=V?setTimeout(()=>{F?.(),q?.(),B(new tS({hash:X}))},V):void 0;return q=$Y(K,{onReplaced:G,resolve:E,reject:B},async(j)=>{if(M=await k$($,kA,"getTransactionReceipt")({hash:X}).catch(()=>{return}),M&&Y<=1){clearTimeout(L),j.resolve(M),q?.();return}F=k$($,Jo,"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(M){if(Y>1&&(!M.blockNumber||f-M.blockNumber+1n<Y))return;x(()=>j.resolve(M));return}if(Q&&!N)z=!0,await JY(async()=>{if(N=await k$($,ai,"getTransaction")({hash:X}),N.blockNumber)f=N.blockNumber},{delay:D,retryCount:W}),z=!1;if(M=await k$($,kA,"getTransactionReceipt")({hash:X}),Y>1&&(!M.blockNumber||f-M.blockNumber+1n<Y))return;x(()=>j.resolve(M))}catch(u){if(u instanceof LK||u instanceof BK){if(!N){z=!1;return}try{w=N,z=!0;let R=await JY(()=>k$($,e0,"getBlock")({blockNumber:f,includeTransactions:!0}),{delay:D,retryCount:W,shouldRetry:({error:Y$})=>Y$ instanceof FK});z=!1;let d=R.transactions.find(({from:Y$,nonce:c})=>Y$===w.from&&c===w.nonce);if(!d)return;if(M=await k$($,kA,"getTransactionReceipt")({hash:d.hash}),Y>1&&(!M.blockNumber||f-M.blockNumber+1n<Y))return;let p="replaced";if(d.to===w.to&&d.value===w.value&&d.input===w.input)p="repriced";else if(d.from===d.to&&d.value===0n)p="cancelled";x(()=>{j.onReplaced?.({reason:p,replacedTransaction:w,transaction:d,transactionReceipt:M}),j.resolve(M)})}catch(R){x(()=>j.reject(R))}}else x(()=>j.reject(u))}}})}),Z}var u_=new o6(128);async function xA($,J){let{account:Q=$.account,assertChainId:Y=!0,chain:X=$.chain,accessList:G,authorizationList:W,blobs:D,data:V,dataSuffix:K=typeof $.dataSuffix==="string"?$.dataSuffix:$.dataSuffix?.value,gas:O,gasPrice:N,maxFeePerBlobGas:w,maxFeePerGas:M,maxPriorityFeePerGas:z,nonce:q,pollingInterval:F,throwOnReceiptRevert:Z,type:E,value:B,...L}=J,j=J.timeout??Math.max((X?.blockTime??0)*3,5000);if(typeof Q>"u")throw new l1({docsPath:"/docs/actions/wallet/sendTransactionSync"});let T=Q?K4(Q):null,x;try{z0(J);let f=await(async()=>{if(J.to)return J.to;if(J.to===null)return;if(W&&W.length>0)return await q7({authorization:W[0]}).catch(()=>{throw new l("`to` is required. Could not infer from `authorizationList`.")});return})();if(T?.type==="json-rpc"||T===null){let u;if(X!==null){if(u=await k$($,t1,"getChainId")({}),Y)L7({currentChainId:u,chain:X})}let R=$.chain?.formatters?.transactionRequest?.format,p=(R||kJ)({...wX(L,{format:R}),accessList:G,account:T,authorizationList:W,blobs:D,chainId:u,data:K?V1([V??"0x",K]):V,gas:O,gasPrice:N,maxFeePerBlobGas:w,maxFeePerGas:M,maxPriorityFeePerGas:z,nonce:q,to:f,type:E,value:B},"sendTransaction"),Y$=u_.get($.uid),c=Y$?"wallet_sendTransaction":"eth_sendTransaction",k=await(async()=>{try{return await $.request({method:c,params:[p]},{retryCount:0})}catch(s){if(Y$===!1)throw s;let _=s;if(_.name==="InvalidInputRpcError"||_.name==="InvalidParamsRpcError"||_.name==="MethodNotFoundRpcError"||_.name==="MethodNotSupportedRpcError")return await $.request({method:"wallet_sendTransaction",params:[p]},{retryCount:0}).then((C)=>{return u_.set($.uid,!0),C}).catch((C)=>{let m=C;if(m.name==="MethodNotFoundRpcError"||m.name==="MethodNotSupportedRpcError")throw u_.set($.uid,!1),_;throw m});throw _}})(),n=await k$($,Qo,"waitForTransactionReceipt")({checkReplacement:!1,hash:k,pollingInterval:F,timeout:j});if(Z&&n.status==="reverted")throw new rG({receipt:n});return n}if(T?.type==="local"){if(T.nonceManager&&typeof q>"u"){let p=L.chainId,Y$=await(async()=>{if(typeof p==="number")return p;if(X)return X.id;return k$($,t1,"getChainId")({})})();x={address:T.address,chainId:Y$}}let u=await k$($,AX,"prepareTransactionRequest")({account:T,accessList:G,authorizationList:W,blobs:D,chain:X,data:K?V1([V??"0x",K]):V,gas:O,gasPrice:N,maxFeePerBlobGas:w,maxFeePerGas:M,maxPriorityFeePerGas:z,nonce:q,nonceManager:T.nonceManager,parameters:[...SK,"sidecars"],type:E,value:B,...L,to:f}),R=X?.serializers?.transaction,d=await T.signTransaction(u,{serializer:R});return await k$($,vA,"sendRawTransactionSync")({serializedTransaction:d,throwOnReceiptRevert:Z,timeout:J.timeout})}if(T?.type==="smart")throw new $J({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new $J({docsPath:"/docs/actions/wallet/sendTransactionSync",type:T?.type})}catch(f){if(f instanceof $J)throw f;if(x&&!(f instanceof rG))T?.nonceManager?.reset(x);throw NX(f,{...J,account:T,chain:J.chain||void 0})}}async function Xo($,J){let{id:Q}=J;await $.request({method:"wallet_showCallsStatus",params:[Q]});return}async function Yo($,J){let{account:Q=$.account}=J;if(!Q)throw new l1({docsPath:"/docs/eip7702/signAuthorization"});let Y=K4(Q);if(!Y.signAuthorization)throw new $J({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:Y.type});let X=await TA($,J);return Y.signAuthorization(X)}async function Go($,{account:J=$.account,message:Q}){if(!J)throw new l1({docsPath:"/docs/actions/wallet/signMessage"});let Y=K4(J);if(Y.signMessage)return Y.signMessage({message:Q});let X=(()=>{if(typeof Q==="string")return HX(Q);if(Q.raw instanceof Uint8Array)return m1(Q.raw);return Q.raw})();return $.request({method:"personal_sign",params:[X,Y.address]},{retryCount:0})}async function Wo($,J){let{account:Q=$.account,chain:Y=$.chain,...X}=J;if(!Q)throw new l1({docsPath:"/docs/actions/wallet/signTransaction"});let G=K4(Q);z0({account:G,...J});let W=await k$($,t1,"getChainId")({});if(Y!==null)L7({currentChainId:W,chain:Y});let V=(Y?.formatters||$.chain?.formatters)?.transactionRequest?.format||kJ;if(G.signTransaction)return G.signTransaction({...X,account:G,chainId:W},{serializer:$.chain?.serializers?.transaction});return await $.request({method:"eth_signTransaction",params:[{...V({...X,account:G},"signTransaction"),chainId:X$(W),from:G.address}]},{retryCount:0})}class m_ extends l{constructor({domain:$}){super(`Invalid domain "${i4($)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class l_ extends l{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 d_ extends l{constructor({type:$}){super(`Struct type "${$}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function Do($){let{domain:J={},message:Q,primaryType:Y}=$,X={EIP712Domain:bA({domain:J}),...$.types};fA({domain:J,message:Q,primaryType:Y,types:X});let G=["0x1901"];if(J)G.push(RU$({domain:J,types:X}));if(Y!=="EIP712Domain")G.push(Vo({data:Q,primaryType:Y,types:X}));return D1(V1(G))}function RU$({domain:$,types:J}){return Vo({data:$,primaryType:"EIP712Domain",types:J})}function Vo({data:$,primaryType:J,types:Q}){let Y=Ko({data:$,primaryType:J,types:Q});return D1(Y)}function Ko({data:$,primaryType:J,types:Q}){let Y=[{type:"bytes32"}],X=[CU$({primaryType:J,types:Q})];for(let G of Q[J]){let[W,D]=Oo({types:Q,name:G.name,type:G.type,value:$[G.name]});Y.push(W),X.push(D)}return e9(Y,X)}function CU$({primaryType:$,types:J}){let Q=m1(PU$({primaryType:$,types:J}));return D1(Q)}function PU$({primaryType:$,types:J}){let Q="",Y=Uo({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 Uo({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])Uo({primaryType:G.type,types:J},Q);return Q}function Oo({types:$,name:J,type:Q,value:Y}){if($[Q]!==void 0)return[{type:"bytes32"},D1(Ko({data:Y,primaryType:Q,types:$}))];if(Q==="bytes")return[{type:"bytes32"},D1(Y)];if(Q==="string")return[{type:"bytes32"},D1(m1(Y))];if(Q.lastIndexOf("]")===Q.length-1){let X=Q.slice(0,Q.lastIndexOf("[")),G=Y.map((W)=>Oo({name:J,type:X,types:$,value:W}));return[{type:"bytes32"},D1(e9(G.map(([W])=>W),G.map(([,W])=>W)))]}return[{type:Q},Y]}function No($){let{domain:J,message:Q,primaryType:Y,types:X}=$,G=(V,K)=>{let O={...K};for(let N of V){let{name:w,type:M}=N;if(M==="address")O[w]=O[w].toLowerCase()}return O},W=(()=>{if(!X.EIP712Domain)return{};if(!J)return{};return G(X.EIP712Domain,J)})(),D=(()=>{if(Y==="EIP712Domain")return;return G(X[Y],Q)})();return i4({domain:W,message:D,primaryType:Y,types:X})}function fA($){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],w=O.match(UA);if(w&&(typeof N==="number"||typeof N==="bigint")){let[q,F,Z]=w;X$(N,{signed:F==="int",size:Number.parseInt(Z,10)/8})}if(O==="address"&&typeof N==="string"&&!S4(N))throw new y4({address:N});let M=O.match(Mi);if(M){let[q,F]=M;if(F&&U4(N)!==Number.parseInt(F,10))throw new N_({expectedSize:Number.parseInt(F,10),givenSize:U4(N)})}let z=X[O];if(z)vU$(O),G(z,N)}};if(X.EIP712Domain&&J){if(typeof J!=="object")throw new m_({domain:J});G(X.EIP712Domain,J)}if(Y!=="EIP712Domain")if(X[Y])G(X[Y],Q);else throw new l_({primaryType:Y,types:X})}function bA({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 vU$($){if($==="address"||$==="bool"||$==="string"||$.startsWith("bytes")||$.startsWith("uint")||$.startsWith("int"))throw new d_({type:$})}async function wo($,J){let{account:Q=$.account,domain:Y,message:X,primaryType:G}=J;if(!Q)throw new l1({docsPath:"/docs/actions/wallet/signTypedData"});let W=K4(Q),D={EIP712Domain:bA({domain:Y}),...J.types};if(fA({domain:Y,message:X,primaryType:G,types:D}),W.signTypedData)return W.signTypedData({domain:Y,message:X,primaryType:G,types:D});let V=No({domain:Y,message:X,primaryType:G,types:D});return $.request({method:"eth_signTypedData_v4",params:[W.address,V]},{retryCount:0})}async function Mo($,{id:J}){await $.request({method:"wallet_switchEthereumChain",params:[{chainId:X$(J)}]},{retryCount:0})}async function Ho($,J){return await $.request({method:"wallet_watchAsset",params:J},{retryCount:0})}var Ao={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},zo={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},Io={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};function qo($,J={}){if(typeof J.size<"u")i6($,{size:J.size});let Q=k4($,J);return B1(Q,J)}function Zo($,J={}){let Q=$;if(typeof J.size<"u")i6(Q,{size:J.size}),Q=A0(Q);if(Q.length>1||Q[0]>1)throw new sS(Q);return Boolean(Q[0])}function fJ($,J={}){if(typeof J.size<"u")i6($,{size:J.size});let Q=k4($,J);return F1(Q,J)}function Lo($,J={}){let Q=$;if(typeof J.size<"u")i6(Q,{size:J.size}),Q=A0(Q,{dir:"right"});return new TextDecoder().decode(Q)}function Fo($,J){let Q=typeof J==="string"?w1(J):J,Y=I7(Q);if(U4(Q)===0&&$.length>0)throw new s9;if(U4(J)&&U4(J)<32)throw new D_({data:typeof J==="string"?J:k4(J),params:$,size:U4(J)});let X=0,G=[];for(let W=0;W<$.length;++W){let D=$[W];Y.setPosition(X);let[V,K]=S7(Y,D,{staticPosition:0});X+=K,G.push(V)}return G}function S7($,J,{staticPosition:Q}){let Y=OA(J.type);if(Y){let[X,G]=Y;return xU$($,{...J,type:G},{length:X,staticPosition:Q})}if(J.type==="tuple")return yU$($,J,{staticPosition:Q});if(J.type==="address")return kU$($);if(J.type==="bool")return fU$($);if(J.type.startsWith("bytes"))return bU$($,J,{staticPosition:Q});if(J.type.startsWith("uint")||J.type.startsWith("int"))return gU$($,J);if(J.type==="string")return hU$($,{staticPosition:Q});throw new M_(J.type,{docsPath:"/docs/contract/decodeAbiParameters"})}var Bo=32,p_=32;function kU$($){let J=$.readBytes(32);return[uQ(k4(A_(J,-20))),32]}function xU$($,J,{length:Q,staticPosition:Y}){if(!Q){let W=fJ($.readBytes(p_)),D=Y+W,V=D+Bo;$.setPosition(D);let K=fJ($.readBytes(Bo)),O=TK(J),N=0,w=[];for(let M=0;M<K;++M){$.setPosition(V+(O?M*32:N));let[z,q]=S7($,J,{staticPosition:V});N+=q,w.push(z)}return $.setPosition(Y+32),[w,32]}if(TK(J)){let W=fJ($.readBytes(p_)),D=Y+W,V=[];for(let K=0;K<Q;++K){$.setPosition(D+K*32);let[O]=S7($,J,{staticPosition:D});V.push(O)}return $.setPosition(Y+32),[V,32]}let X=0,G=[];for(let W=0;W<Q;++W){let[D,V]=S7($,J,{staticPosition:Y+X});X+=V,G.push(D)}return[G,X]}function fU$($){return[Zo($.readBytes(32),{size:32}),32]}function bU$($,J,{staticPosition:Q}){let[Y,X]=J.type.split("bytes");if(!X){let W=fJ($.readBytes(32));$.setPosition(Q+W);let D=fJ($.readBytes(32));if(D===0)return $.setPosition(Q+32),["0x",32];let V=$.readBytes(D);return $.setPosition(Q+32),[k4(V),32]}return[k4($.readBytes(Number.parseInt(X,10),32)),32]}function gU$($,J){let Q=J.type.startsWith("int"),Y=Number.parseInt(J.type.split("int")[1]||"256",10),X=$.readBytes(32);return[Y>48?qo(X,{signed:Q}):fJ(X,{signed:Q}),32]}function yU$($,J,{staticPosition:Q}){let Y=J.components.length===0||J.components.some(({name:W})=>!W),X=Y?[]:{},G=0;if(TK(J)){let W=fJ($.readBytes(p_)),D=Q+W;for(let V=0;V<J.components.length;++V){let K=J.components[V];$.setPosition(D+G);let[O,N]=S7($,K,{staticPosition:D});G+=N,X[Y?V:K?.name]=O}return $.setPosition(Q+32),[X,32]}for(let W=0;W<J.components.length;++W){let D=J.components[W],[V,K]=S7($,D,{staticPosition:Q});X[Y?W:D?.name]=V,G+=K}return[X,G]}function hU$($,{staticPosition:J}){let Q=fJ($.readBytes(32)),Y=J+Q;$.setPosition(Y);let X=fJ($.readBytes(32));if(X===0)return $.setPosition(J+32),["",32];let G=$.readBytes(X,32),W=Lo(A0(G));return $.setPosition(J+32),[W,32]}function TK($){let{type:J}=$;if(J==="string")return!0;if(J==="bytes")return!0;if(J.endsWith("[]"))return!0;if(J==="tuple")return $.components?.some(TK);let Q=OA($.type);if(Q&&TK({...$,type:Q[1]}))return!0;return!1}function jo($){let{abi:J,data:Q,cause:Y}=$,X=mQ(Q,0,4);if(X==="0x")throw new s9({cause:Y});let W=[...J||[],zo,Io].find((D)=>D.type==="error"&&X===j7(xJ(D)));if(!W)throw new jK(X,{docsPath:"/docs/contract/decodeErrorResult",cause:Y});return{abiItem:W,args:"inputs"in W&&W.inputs&&W.inputs.length>0?Fo(W.inputs,mQ(Q,4)):void 0,errorName:W.name}}function n_({abiItem:$,args:J,includeFunctionName:Q=!0,includeName:Y=!1}){if(!("name"in $))return;if(!("inputs"in $))return;if(!$.inputs)return;return`${Q?$.name:""}(${$.inputs.map((X,G)=>`${Y&&X.name?`${X.name}: `:""}${typeof J[G]==="object"?i4(J[G]):J[G]}`).join(", ")})`}class c_ extends l{constructor($,{abi:J,args:Q,contractAddress:Y,docsPath:X,functionName:G,sender:W}){let D=jA({abi:J,args:Q,name:G}),V=D?n_({abiItem:D,args:Q,includeFunctionName:!1,includeName:!1}):void 0,K=D?xJ(D,{includeName:!0}):void 0,O=oG({address:Y&&Di(Y),function:K,args:V&&V!=="()"&&`${[...Array(G?.length??0).keys()].map(()=>" ").join("")}${V}`,sender:W});super($.shortMessage||`An unknown error occurred while executing the contract function "${G}".`,{cause:$,docsPath:X,metaMessages:[...$.metaMessages?[...$.metaMessages," "]:[],O&&"Contract Call:",O].filter(Boolean),name:"ContractFunctionExecutionError"});Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=J,this.args=Q,this.cause=$,this.contractAddress=Y,this.functionName=G,this.sender=W}}class i_ extends l{constructor({abi:$,data:J,functionName:Q,message:Y,cause:X}){let G,W,D,V;if(J&&J!=="0x")try{W=jo({abi:$,data:J,cause:X});let{abiItem:O,errorName:N,args:w}=W;if(N==="Error")V=w[0];else if(N==="Panic"){let[M]=w;V=Ao[M]}else{let M=O?xJ(O,{includeName:!0}):void 0,z=O&&w?n_({abiItem:O,args:w,includeFunctionName:!1,includeName:!1}):void 0;D=[M?`Error: ${M}`:"",z&&z!=="()"?` ${[...Array(N?.length??0).keys()].map(()=>" ").join("")}${z}`:""]}}catch(O){G=O}else if(Y)V=Y;let K;if(G instanceof jK)K=G.signature,D=[`Unable to decode signature "${K}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${K}.`];super(V&&V!=="execution reverted"||K?[`The contract function "${Q}" reverted with the following ${K?"signature":"reason"}:`,V||K].join(`
|
|
167
167
|
`):`The contract function "${Q}" reverted.`,{cause:G??X,metaMessages:D,name:"ContractFunctionRevertedError"});Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=W,this.raw=J,this.reason=V,this.signature=K}}class o_ extends l{constructor({functionName:$,cause:J}){super(`The contract function "${$}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${$}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:J})}}class r_ extends l{constructor({data:$,message:J}){super(J||"",{name:"RawContractError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=$}}var uU$=3;function Eo($,{abi:J,address:Q,args:Y,docsPath:X,functionName:G,sender:W}){let D=$ instanceof r_?$:$ instanceof l?$.walk((z)=>("data"in z))||$.walk():{},{code:V,data:K,details:O,message:N,shortMessage:w}=D,M=(()=>{if($ instanceof s9)return new o_({functionName:G,cause:$});if([uU$,gQ.code].includes(V)&&(K||O||N||w)||V===VX.code&&O==="execution reverted"&&K)return new i_({abi:J,data:typeof K==="object"?K.data:K,functionName:G,message:D instanceof o9?O:w??N,cause:$});return $})();return new c_(M,{abi:J,args:Y,contractAddress:Q,docsPath:X,functionName:G,sender:W})}async function QY($,J){return QY.internal($,zX,"sendTransaction",J)}(function($){async function J(Q,Y,X,G){let{abi:W,account:D=Q.account,address:V,args:K,functionName:O,...N}=G;if(typeof D>"u")throw new l1({docsPath:"/docs/contract/writeContract"});let w=D?K4(D):null,M=EA({abi:W,args:K,functionName:O});try{return await k$(Q,Y,X)({data:M,to:V,account:w,...N})}catch(z){throw Eo(z,{abi:W,address:V,args:K,docsPath:"/docs/contract/writeContract",functionName:O,sender:w?.address})}}$.internal=J})(QY||(QY={}));async function So($,J){return QY.internal($,xA,"sendTransactionSync",J)}function _o($){return{addChain:(J)=>Oi($,J),deployContract:(J)=>xi($,J),fillTransaction:(J)=>GA($,J),getAddresses:()=>fi($),getCallsStatus:(J)=>_A($,J),getCapabilities:(J)=>pi($,J),getChainId:()=>t1($),getPermissions:()=>ni($),prepareAuthorization:(J)=>TA($,J),prepareTransactionRequest:(J)=>AX($,J),requestAddresses:()=>ii($),requestPermissions:(J)=>oi($,J),sendCalls:(J)=>SA($,J),sendCallsSync:(J)=>ti($,J),sendRawTransaction:(J)=>LA($,J),sendRawTransactionSync:(J)=>vA($,J),sendTransaction:(J)=>zX($,J),sendTransactionSync:(J)=>xA($,J),showCallsStatus:(J)=>Xo($,J),signAuthorization:(J)=>Yo($,J),signMessage:(J)=>Go($,J),signTransaction:(J)=>Wo($,J),signTypedData:(J)=>wo($,J),switchChain:(J)=>Mo($,J),waitForCallsStatus:(J)=>PA($,J),watchAsset:(J)=>Ho($,J),writeContract:(J)=>QY($,J),writeContractSync:(J)=>So($,J)}}function t_($){let{key:J="wallet",name:Q="Wallet Client",transport:Y}=$;return Xi({...$,key:J,name:Q,transport:Y,type:"walletClient"}).extend(_o)}class a_ extends l{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}var s_=new Map;function To({fn:$,id:J,shouldSplitBatch:Q,wait:Y=0,sort:X}){let G=async()=>{let O=V();W();let N=O.map(({args:w})=>w);if(N.length===0)return;$(N).then((w)=>{if(X&&Array.isArray(w))w.sort(X);for(let M=0;M<O.length;M++){let{resolve:z}=O[M];z?.([w[M],w])}}).catch((w)=>{for(let M=0;M<O.length;M++){let{reject:z}=O[M];z?.(w)}})},W=()=>s_.delete(J),D=()=>V().map(({args:O})=>O),V=()=>s_.get(J)||[],K=(O)=>s_.set(J,[...V(),O]);return{flush:W,async schedule(O){let{promise:N,resolve:w,reject:M}=E7();if(Q?.([...D(),O]))G();if(V().length>0)return K({args:O,resolve:w,reject:M}),N;return K({args:O,resolve:w,reject:M}),setTimeout(G,Y),N}}}function Ro($,{errorInstance:J=Error("timed out"),timeout:Q,signal:Y}){return new Promise((X,G)=>{(async()=>{let W,D=new AbortController;try{if(Q>0)W=setTimeout(()=>{if(Y)D.abort();else G(J)},Q);X(await $({signal:D?.signal||null}))}catch(V){if(D?.signal.aborted&&bQ(V)){G(J);return}G(V)}finally{clearTimeout(W)}})()})}function mU$(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var e_=mU$();function Co($,J={}){let{url:Q,headers:Y}=lU$($);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:w,signal:M}=O;try{let z=await Ro(async({signal:F})=>{let Z={...O,body:Array.isArray(G)?i4(G.map((j)=>({jsonrpc:"2.0",id:j.id??e_.take(),...j}))):i4({jsonrpc:"2.0",id:G.id??e_.take(),...G}),headers:{...Y,"Content-Type":"application/json",...N},method:w||"POST",signal:M||(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 $A({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 DX({body:G,details:i4(q.error)||z.statusText,headers:z.headers,status:z.status,url:Q})}return q}catch(z){if(M?.aborted)throw s0(M);if(bQ(z))throw z;if(z instanceof DX)throw z;if(z instanceof $A)throw z;throw new DX({body:G,cause:z,url:Q})}}}}function lU$($){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:$}}}var gA=new o6(8192);function Po($,{enabled:J=!0,id:Q}){if(!J||!Q)return $();if(gA.get(Q))return gA.get(Q);let Y=$().finally(()=>gA.delete(Q));return gA.set(Q,Y),Y}function vo($,J={}){return async(Q,Y={})=>{let{dedupe:X=!1,methods:G,retryDelay:W=150,retryCount:D=3,signal:V,uid:K}={...J,...Y},{method:O}=Q;if(G?.exclude?.includes(O))throw new KX(Error("method not supported"),{method:O});if(G?.include&&!G.include.includes(O))throw new KX(Error("method not supported"),{method:O});if(V?.aborted)throw s0(V);let N=X?pU$(`${K}.${i4(Q)}`):void 0;return Po(()=>JY(async()=>{try{return await $(Q,V?{signal:V}:void 0)}catch(w){if(V?.aborted)throw s0(V);if(bQ(w))throw w;let M=w;switch(M.code){case tG.code:throw new tG(M);case aG.code:throw new aG(M);case sG.code:throw new sG(M,{method:Q.method});case eG.code:throw new eG(M);case gQ.code:throw new gQ(M);case VX.code:throw new VX(M);case $7.code:throw new $7(M);case J7.code:throw new J7(M);case Q7.code:throw new Q7(M);case KX.code:throw new KX(M,{method:Q.method});case r9.code:throw new r9(M);case X7.code:throw new X7(M);case t9.code:throw new t9(M);case Y7.code:throw new Y7(M);case G7.code:throw new G7(M);case W7.code:throw new W7(M);case D7.code:throw new D7(M);case V7.code:throw new V7(M);case UX.code:throw new UX(M);case K7.code:throw new K7(M);case U7.code:throw new U7(M);case O7.code:throw new O7(M);case N7.code:throw new N7(M);case w7.code:throw new w7(M);case OX.code:throw new OX(M);case 5000:throw new t9(M);case M7.code:throw new M7(M);default:if(w instanceof l)throw w;throw new aS(M)}}},{delay:({count:w,error:M})=>{if(M&&M instanceof DX){let z=M?.headers?.get("Retry-After");if(z?.match(/\d/))return Number.parseInt(z,10)*1000}return~~(1<<w)*W},retryCount:D,signal:V,shouldRetry:({error:w})=>dU$(w)}),{enabled:X,id:N})}}function dU$($){if(bQ($))return!1;if("code"in $&&typeof $.code==="number"){if($.code===-1)return!0;if($.code===r9.code)return!0;if($.code===gQ.code)return!0;if($.code===429)return!0;return!1}if($ instanceof DX&&$.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 pU$($,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 ko({key:$,methods:J,name:Q,request:Y,retryCount:X=3,retryDelay:G=150,timeout:W,type:D},V){let K=tH();return{config:{key:$,methods:J,name:Q,request:Y,retryCount:X,retryDelay:G,timeout:W,type:D},request:vo(Y,{methods:J,retryCount:X,retryDelay:G,uid:K}),value:V}}var nU$=0,xo=new WeakMap;function cU$($){if(!$)return"default";let J=xo.get($);if(J!==void 0)return J;let Q=nU$++;return xo.set($,Q),Q}function $T($,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:w,retryCount:M,timeout:z})=>{let{batchSize:q=1000,wait:F=0}=typeof Q==="object"?Q:{},Z=J.retryCount??M,E=z??J.timeout??1e4,B=$||w?.rpcUrls.default.http[0];if(!B)throw new a_;let L=Co(B,{fetchFn:Y,fetchOptions:X,onRequest:V,onResponse:K,timeout:E});return ko({key:G,methods:W,name:D,async request({method:j,params:T},x){let f={method:j,params:T},u=x?.signal?{signal:x.signal}:void 0,{schedule:R}=To({id:`${B}.${cU$(x?.signal)}`,wait:F,shouldSplitBatch(c){return c.length>q},fn:(c)=>L.request({body:c,fetchOptions:u}),sort:(c,k)=>c.id-k.id}),d=async(c)=>Q?R(c):[await L.request({body:c,fetchOptions:u})],[{error:p,result:Y$}]=await d(f);if(N)return{error:p,result:Y$};if(p)throw new o9({body:f,error:p,url:B});return Y$},retryCount:Z,retryDelay:O,timeout:E,type:"http"},{fetchOptions:X,url:B})}}$X();function fo($){if(typeof $==="string"){if(!S4($,{strict:!1}))throw new y4({address:$});return{address:$,type:"json-rpc"}}if(!S4($.address,{strict:!1}))throw new y4({address:$.address});return{address:$.address,nonceManager:$.nonceManager,sign:$.sign,signAuthorization:$.signAuthorization,signMessage:$.signMessage,signTransaction:$.signTransaction,signTypedData:$.signTypedData,source:"custom",type:"local"}}$X();$X();function bo({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(B1($),B1(J)).toCompactHex()}${G===0?"1b":"1c"}`;if(Q==="hex")return W;return w1(W)}var JT=!1;async function bJ({hash:$,privateKey:J,to:Q="object"}){let{r:Y,s:X,recovery:G}=A6.sign($.slice(2),J.slice(2),{lowS:!0,extraEntropy:u1(JT,{strict:!1})?w1(JT):JT}),W={r:X$(Y,{size:32}),s:X$(X,{size:32}),v:G?28n:27n,yParity:G};return(()=>{if(Q==="bytes"||Q==="hex")return bo({...W,to:Q});return W})()}async function go($){let{chainId:J,nonce:Q,privateKey:Y,to:X="object"}=$,G=$.contractAddress??$.address,W=await bJ({hash:MA({address:G,chainId:J,nonce:Q}),privateKey:Y,to:X});if(X==="object")return{address:G,chainId:J,nonce:Q,...W};return W}var yo=`\x19Ethereum Signed Message:
|
|
168
168
|
`;function ho($){let J=(()=>{if(typeof $==="string")return HX($);if(typeof $.raw==="string")return $.raw;return k4($.raw)})(),Q=HX(`${yo}${U4(J)}`);return V1([Q,J])}function uo($,J){return D1(ho($),J)}async function mo({message:$,privateKey:J}){return await bJ({hash:uo($),privateKey:J,to:"hex"})}function lo($){if(!$||$.length===0)return[];let J=[];for(let Q of $){let{chainId:Y,nonce:X,...G}=Q,W=Q.address;J.push([Y?m1(Y):"0x",W,X?m1(X):"0x",..._7({},G)])}return J}function po($){let{authorizationList:J}=$;if(J)for(let Q of J){let{chainId:Y}=Q,X=Q.address;if(!S4(X))throw new y4({address:X});if(Y<0)throw new Z7({chainId:Y})}yA($)}function no($){let{blobVersionedHashes:J}=$;if(J){if(J.length===0)throw new EK;for(let Q of J){let Y=U4(Q),X=F1(mQ(Q,0,1));if(Y!==32)throw new C_({hash:Q,size:Y});if(X!==IA)throw new P_({hash:Q,version:X})}}yA($)}function yA($){let{chainId:J,maxPriorityFeePerGas:Q,maxFeePerGas:Y,to:X}=$;if(J<=0)throw new Z7({chainId:J});if(X&&!S4(X))throw new y4({address:X});if(Y&&Y>z7)throw new a0({maxFeePerGas:Y});if(Q&&Y&&Q>Y)throw new fQ({maxFeePerGas:Y,maxPriorityFeePerGas:Q})}function co($){let{chainId:J,maxPriorityFeePerGas:Q,gasPrice:Y,maxFeePerGas:X,to:G}=$;if(J<=0)throw new Z7({chainId:J});if(G&&!S4(G))throw new y4({address:G});if(Q||X)throw new l("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(Y&&Y>z7)throw new a0({maxFeePerGas:Y})}function io($){let{chainId:J,maxPriorityFeePerGas:Q,gasPrice:Y,maxFeePerGas:X,to:G}=$;if(G&&!S4(G))throw new y4({address:G});if(typeof J<"u"&&J<=0)throw new Z7({chainId:J});if(Q||X)throw new l("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(Y&&Y>z7)throw new a0({maxFeePerGas:Y})}function RK($){if(!$||$.length===0)return[];let J=[];for(let Q=0;Q<$.length;Q++){let{address:Y,storageKeys:X}=$[Q];for(let G=0;G<X.length;G++)if(X[G].length-2!==64)throw new oS({storageKey:X[G]});if(!S4(Y,{strict:!1}))throw new y4({address:Y});J.push([Y,X])}return J}function oo($,J){let Q=ZA($);if(Q==="eip1559")return rU$($,J);if(Q==="eip2930")return tU$($,J);if(Q==="eip4844")return oU$($,J);if(Q==="eip7702")return iU$($,J);return aU$($,J)}function iU$($,J){let{authorizationList:Q,chainId:Y,gas:X,nonce:G,to:W,value:D,maxFeePerGas:V,maxPriorityFeePerGas:K,accessList:O,data:N}=$;po($);let w=RK(O),M=lo(Q);return I0(["0x04",lQ([X$(Y),G?X$(G):"0x",K?X$(K):"0x",V?X$(V):"0x",X?X$(X):"0x",W??"0x",D?X$(D):"0x",N??"0x",w,M,..._7($,J)])])}function oU$($,J){let{chainId:Q,gas:Y,nonce:X,to:G,value:W,maxFeePerBlobGas:D,maxFeePerGas:V,maxPriorityFeePerGas:K,accessList:O,data:N}=$;no($);let{blobVersionedHashes:w,sidecars:M}=$;if($.blobs&&(typeof w>"u"||typeof M>"u")){let B=typeof $.blobs[0]==="string"?$.blobs:$.blobs.map((T)=>k4(T)),L=$.kzg,j=B7({blobs:B,kzg:L});if(typeof w>"u")w=zA({commitments:j});if(typeof M>"u"){let T=F7({blobs:B,commitments:j,kzg:L});M=qA({blobs:B,commitments:j,proofs:T})}}let z=RK(O),q=[X$(Q),X?X$(X):"0x",K?X$(K):"0x",V?X$(V):"0x",Y?X$(Y):"0x",G??"0x",W?X$(W):"0x",N??"0x",z,D?X$(D):"0x",w??[],..._7($,J)],F=[],Z=[],E=[];if(M)for(let B=0;B<M.length;B++){let{blob:L,commitment:j,proof:T}=M[B];F.push(L),Z.push(j),E.push(T)}return I0(["0x03",M?lQ([q,F,Z,E]):lQ(q)])}function rU$($,J){let{chainId:Q,gas:Y,nonce:X,to:G,value:W,maxFeePerGas:D,maxPriorityFeePerGas:V,accessList:K,data:O}=$;yA($);let N=RK(K),w=[X$(Q),X?X$(X):"0x",V?X$(V):"0x",D?X$(D):"0x",Y?X$(Y):"0x",G??"0x",W?X$(W):"0x",O??"0x",N,..._7($,J)];return I0(["0x02",lQ(w)])}function tU$($,J){let{chainId:Q,gas:Y,data:X,nonce:G,to:W,value:D,accessList:V,gasPrice:K}=$;co($);let O=RK(V),N=[X$(Q),G?X$(G):"0x",K?X$(K):"0x",Y?X$(Y):"0x",W??"0x",D?X$(D):"0x",X??"0x",O,..._7($,J)];return I0(["0x01",lQ(N)])}function aU$($,J){let{chainId:Q=0,gas:Y,data:X,nonce:G,to:W,value:D,gasPrice:V}=$;io($);let K=[G?X$(G):"0x",V?X$(V):"0x",Y?X$(Y):"0x",W??"0x",D?X$(D):"0x",X??"0x"];if(J){let O=(()=>{if(J.v>=35n){if((J.v-35n)/2n>0)return J.v;return 27n+(J.v===35n?0n:1n)}if(Q>0)return BigInt(Q*2)+BigInt(35n+J.v-27n);let M=27n+(J.v===27n?0n:1n);if(J.v!==M)throw new cS({v:J.v});return M})(),N=A0(J.r),w=A0(J.s);K=[...K,X$(O),N==="0x00"?"0x":N,w==="0x00"?"0x":w]}else if(Q>0)K=[...K,X$(Q),"0x","0x"];return lQ(K)}function _7($,J){let Q=J??$,{v:Y,yParity:X}=Q;if(typeof Q.r>"u")return[];if(typeof Q.s>"u")return[];if(typeof Y>"u"&&typeof X>"u")return[];let G=A0(Q.r),W=A0(Q.s);return[(()=>{if(typeof X==="number")return X?X$(1):"0x";if(Y===0n)return"0x";if(Y===1n)return X$(1);return Y===27n?"0x":X$(1)})(),G==="0x00"?"0x":G,W==="0x00"?"0x":W]}async function ro($){let{privateKey:J,transaction:Q,serializer:Y=oo}=$,X=(()=>{if(Q.type==="eip4844")return{...Q,sidecars:!1};return Q})(),G=await bJ({hash:D1(await Y(X)),privateKey:J});return await Y(Q,G)}async function to($){let{privateKey:J,...Q}=$;return await bJ({hash:Do(Q),privateKey:J,to:"hex"})}function QT($,J={}){let{nonceManager:Q}=J,Y=m1(A6.getPublicKey($.slice(2),!1)),X=NA(Y);return{...fo({address:X,nonceManager:Q,async sign({hash:W}){return bJ({hash:W,privateKey:$,to:"hex"})},async signAuthorization(W){return go({...W,privateKey:$})},async signMessage({message:W}){return mo({message:W,privateKey:$})},async signTransaction(W,{serializer:D}={}){return ro({privateKey:$,transaction:W,serializer:D})},async signTypedData(W){return to({...W,privateKey:$})}}),publicKey:Y,source:"privateKey"}}function hA($){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 XT=hA({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 YT=hA({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});var GT=null;var sU$={privateKeyToAccount:QT,createWalletClient:t_,http:$T,createMonacoSDK:lS,sei:XT,seiTestnet:YT};function eU$($,J=sU$){let Q=$.network==="mainnet"?J.sei:J.seiTestnet,Y;if($.privateKey){let X=J.privateKeyToAccount($.privateKey);Y=J.createWalletClient({account:X,chain:Q,transport:J.http($.seiRpcUrl)})}return J.createMonacoSDK({walletClient:Y,network:$.network,seiRpcUrl:$.seiRpcUrl})}function a1($){if(!GT){let J=$??P8();GT=eU$(J)}return GT}async function x$($){let J=a1($);if(!J.isAuthenticated()){let Q=$??P8();await J.login(Q.clientId),console.error(`Authenticated as ${J.getAccountAddress()}`)}return J}function A$($){return{content:[{type:"text",text:JSON.stringify($,null,2)}]}}function JJ($){return{content:[{type:"text",text:$}]}}function ao($,J){if(J.network==="mainnet")return;$.registerTool("request_faucet",{description:"Request test funds from the faucet for all active trading pairs. Only available on non-mainnet networks (development, staging, local).",inputSchema:{}},async()=>{let Q=P8(),Y=await x$(),G=Y.getAuthState()?.accessToken;if(!G)return JJ("No access token available. Please authenticate first.");let W=KV(Q.network),D=Y.getAccountAddress();if(W.includes("localhost"))return JJ("Faucet is not available for localhost.");let V=new AbortController,K=setTimeout(()=>V.abort(),30000);try{let O=await fetch(`${W}/api/v1/faucet/mint`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${G}`},body:JSON.stringify({address:D}),signal:V.signal});if(clearTimeout(K),O.ok)return JJ(`Faucet request successful. Test funds have been minted to ${D} on the ${Q.network} network.`);let N=await O.text().catch(()=>"Unknown error");return JJ(`Faucet request failed (${O.status}): ${N}`)}catch(O){if(clearTimeout(K),O instanceof Error&&O.name==="AbortError")return JJ("Faucet request timed out after 30 seconds.");return JJ(`Faucet error: ${O}`)}})}function so($,J){ao($,J)}function eo($){$.registerTool("get_my_fee_tier",{description:"Get the authenticated user's current fee tier, rolling 14-day volumes (with spot/perp breakdown), the volume needed to reach the next tier, and the requested pair's six-row fee schedule.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:J})=>{let Y=await(await x$()).fees.getMyFeeTier({tradingPairId:J});return A$(Y)})}function $r($){$.registerTool("simulate_fees",{description:"Simulate the fees for an order before placing it. Returns Monaco protocol fees, application fees, and total amounts.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),side:A.enum(["BUY","SELL"]).describe("Order side"),price:A.string().describe("Price per unit as a decimal string"),quantity:A.string().describe("Quantity to trade as a decimal string")})},async({tradingPairId:J,side:Q,price:Y,quantity:X})=>{let W=await(await x$()).fees.simulateFees({tradingPairId:J,side:Q,price:Y,quantity:X});return A$(W)})}function Jr($){$r($),eo($)}function Qr($){$.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),interval:A.enum(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:A.number().optional().describe("Start time as Unix timestamp (seconds)"),endTime:A.number().optional().describe("End time as Unix timestamp (seconds)"),limit:A.number().optional().describe("Max number of candlesticks to return")})},async({tradingPairId:J,interval:Q,startTime:Y,endTime:X,limit:G})=>{let D=await a1().market.getCandlesticks(J,Q,{startTime:Y,endTime:X,limit:G});return A$(D)})}function Xr($){$.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID")})},async({tradingPairId:J})=>{let Y=await a1().market.getMarketMetadata(J);return A$(Y)})}function Yr($){$.registerTool("get_trading_pair_by_symbol",{description:"Look up a specific trading pair by its symbol (e.g. 'BTC/USDC'). Returns the pair's full details including its UUID.",inputSchema:A.object({symbol:A.string().describe("Trading pair symbol (e.g. 'BTC/USDC')")})},async({symbol:J})=>{let Y=await a1().market.getTradingPairBySymbol(J);if(!Y)return JJ(`Trading pair '${J}' not found.`);return A$(Y)})}function Gr($){$.registerTool("get_trading_pairs",{description:"Get a paginated list of trading pairs available on Monaco. Returns pair IDs, symbols, base/quote tokens, and status.",inputSchema:A.object({page:A.number().optional().describe("Page number (starts from 1)"),limit:A.number().optional().describe("Number of items per page (max 100)"),marketType:A.string().optional().describe("Filter by market type"),baseToken:A.string().optional().describe("Filter by base token"),quoteToken:A.string().optional().describe("Filter by quote token"),isActive:A.boolean().optional().describe("Filter by active status")})},async(J)=>{let Y=await a1().market.getPaginatedTradingPairs(J);return A$(Y)})}function Wr($){Gr($),Yr($),Qr($),Xr($)}function Dr($){$.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),depth:A.number().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:A.enum(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:A.number().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:A.enum(["BASE","QUOTE"]).optional().describe("Quantity denomination: BASE or QUOTE")})},async({tradingPairId:J,depth:Q,tradingMode:Y,magnitude:X,denomination:G})=>{let D=await a1().orderbook.getOrderbook(J,{depth:Q,tradingMode:Y,magnitude:X,denomination:G});return A$(D)})}function Vr($){Dr($)}function Kr($){$.registerTool("get_my_trader_code",{description:"Return the authenticated caller's PitPass TraderCode — their normalized wallet address. Clients render it as `Monaco - <address>`. Never 404s; ensures the backing row so referrals attributed to this wallet link correctly.",inputSchema:A.object({})},async()=>{let Q=await(await x$()).pitpass.getMyTraderCode();return A$(Q)})}function Ur($){$.registerTool("get_rewards_balance",{description:"Return the authenticated caller's current PitPass rewards-bucket balances across all reward tokens. Returns an empty list when no rewards have been earned yet. Use transfer_rewards to move earned rewards into a tradeable balance.",inputSchema:A.object({})},async()=>{let Q=await(await x$()).pitpass.getRewardsBalance();return A$(Q)})}function Or($){$.registerTool("get_trader_code_info",{description:"Public lookup of a PitPass TraderCode (wallet address or 'Monaco - <address>' form). Returns the resolved normalized code when it belongs to a known wallet, or a 404 error if not found. Use this to validate a referral code before sign-up.",inputSchema:A.object({code:A.string().describe("The TraderCode to look up — a wallet address (0x-prefixed) or the 'Monaco - <address>' display form.")})},async({code:J})=>{let Y=await a1().pitpass.getTraderCodeInfo(J);return A$(Y)})}function Nr($){$.registerTool("transfer_rewards",{description:"Transfer earned PitPass rewards from your rewards bucket into your trading balance, making them immediately tradeable. Ledger-only — no on-chain transaction. Fails if the rewards balance is insufficient.",inputSchema:A.object({token:A.string().describe("Reward token contract address (0x-prefixed EVM address) to transfer."),amount:A.string().describe("Amount to transfer in RAW atomic units of the token (positive integer string).")})},async({token:J,amount:Q})=>{let X=await(await x$()).pitpass.transferRewards({token:J,amount:Q});return A$(X)})}function wr($){Or($)}function Mr($){Kr($),Ur($),Nr($)}function Hr($){$.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:A.object({assetId:A.string().describe("The asset UUID")})},async({assetId:J})=>{let Y=await(await x$()).profile.getUserBalanceByAssetId(J);return A$(Y)})}function Ar($){$.registerTool("get_balances",{description:"Get the authenticated user's token balances with pagination.",inputSchema:A.object({limit:A.number().optional().describe("Number of items to return (default: 20)"),offset:A.number().optional().describe("Number of items to skip (default: 0)")})},async({limit:J,offset:Q})=>{let X=await(await x$()).profile.getUserBalances({limit:J,offset:Q});return A$(X)})}function zr($){$.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history) with pagination.",inputSchema:A.object({page:A.number().int().min(1).optional().describe("Page number (starts from 1, default: 1)"),limit:A.number().int().min(1).max(100).optional().describe("Items per page (default: 20, max: 100)"),entryType:A.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:A.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"]).optional().describe("Filter by transaction type (e.g. DEPOSIT, WITHDRAWAL, TRADE, FEE, FUNDING, LIQUIDATION, INTEREST, REWARD)"),assetId:A.string().uuid().optional().describe("Filter by asset ID (UUID)")})},async({page:J,limit:Q,entryType:Y,transactionType:X,assetId:G})=>{let D=await(await x$()).profile.getPaginatedUserMovements({page:J,limit:Q,entryType:Y,transactionType:X,assetId:G});return A$(D)})}function Ir($){$.registerTool("get_profile",{description:"Get the authenticated user's profile including address, username, account type, and withdrawal status. Use get_balances, get_movements, and get_orders for detailed account data."},async()=>{let Q=await(await x$()).profile.getProfile();return A$(Q)})}function qr($){Ir($),Ar($),Hr($),zr($)}var $O$="https://docs.0xmonaco.com/mcp",JO$="SearchMonacoDocs",uA=null;async function Zr($,J,Q){let Y=await fetch($O$,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...uA?{"Mcp-Session-Id":uA}:{}},body:JSON.stringify({jsonrpc:"2.0",id:Q,method:$,params:J})});if(!Y.ok)throw Error(`Mintlify MCP error: ${Y.status}`);let X=Y.headers.get("mcp-session-id");if(X)uA=X;let W=(await Y.text()).split(`
|
|
169
|
-
`).find((D)=>D.startsWith("data: "));if(!W)throw Error("No data in Mintlify MCP response");return JSON.parse(W.slice(6))}async function QO$(){if(uA)return;await Zr("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:Pw.version}},0)}async function XO$($){return await QO$(),(await Zr("tools/call",{name:JO$,arguments:{query:$}},1))?.result}function Lr($){$.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:A.object({query:A.string().describe("The search query")})},async({query:J})=>{try{let Q=await XO$(J);if(Q?.content&&Array.isArray(Q.content))return{content:Q.content};return A$(Q)}catch(Q){return JJ(`Search failed: ${Q instanceof Error?Q.message:String(Q)}`)}})}function Br($){Lr($)}function Fr($){$.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),page:A.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:A.number().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:J,page:Q,pageSize:Y})=>{let G=await a1().trades.getTrades(J,{page:Q,pageSize:Y});return A$(G)})}function jr($){Fr($)}function Er($){$.registerTool("batch_cancel_all_orders",{description:"Cancel all active orders, optionally filtered to a specific trading pair.",inputSchema:A.object({tradingPairId:A.string().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:J})=>{let Y=await(await x$()).trading.batchCancelAll(J);return A$(Y)})}function Sr($){$.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request.",inputSchema:A.object({orderIds:A.array(A.string()).describe("Array of order IDs to cancel")})},async({orderIds:J})=>{let Y=await(await x$()).trading.batchCancel(J);return A$(Y)})}function _r($){$.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to a specific trading pair. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:A.object({tradingPairId:A.string().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:A.number().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:J,slippageToleranceBps:Q})=>{let X=await(await x$()).positions.batchCloseAllPositions({tradingPairId:J,slippageToleranceBps:Q});return A$(X)})}function Tr($){$.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:A.object({orderId:A.string().describe("The order ID to cancel")})},async({orderId:J})=>{let Y=await(await x$()).trading.cancelOrder(J);return A$(Y)})}function Rr($){$.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:A.object({orderId:A.string().describe("The order ID to look up")})},async({orderId:J})=>{let Y=await(await x$()).trading.getOrder(J);return A$(Y)})}var YO$=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"]})}),GO$=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()}),WO$=A.object({tradingPairId:A.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),Cr=A.object({tierLevel:A.number().int(),minVolumeThreshold:A.string(),makerFeeBps:A.string(),takerFeeBps:A.string()}),DO$=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(Cr)});var Pr=A.object({token:A.string(),available:A.string()}),VO$=A.object({balances:A.array(Pr)}),KO$=A.object({code:A.string(),createdAt:A.string()}),UO$=A.object({code:A.string()}),OO$=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")}),NO$=A.object({rewardsBalance:A.string(),tradingBalance:A.string()});var CK=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var PK=A.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),lA=A.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),WT=A.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),vK=A.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),vr=A.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),DT=A.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),R7=A.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),w4=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"}),_$=A.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),kK=A.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),kr=A.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),xK=A.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),mA=A.object({triggerPrice:w4,orderType:R7,limitPrice:w4.optional(),timeInForce:DT.optional(),slippageToleranceBps:xK.optional(),expiresAt:kK.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"]}),T7=($)=>$?.takeProfit!==void 0||$?.stopLoss!==void 0,yI1=A.object({tradingPairId:_$,side:PK,quantity:w4,price:w4,options:A.object({tradingMode:lA.optional(),useMasterBalance:A.boolean().optional(),expirationDate:kK.optional(),timeInForce:vr.optional(),marginAccountId:_$.optional(),marginMode:WT.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:vK.optional(),leverage:w4.optional(),reduceOnly:A.boolean().optional(),takeProfit:mA.optional(),stopLoss:mA.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(($)=>!T7($.options)||$.options?.tradingMode==="MARGIN",{message:"Parent TP/SL is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>!T7($.options)||$.options?.positionSide!=="NONE",{message:"Parent TP/SL requires positionSide to be LONG or SHORT",path:["options","positionSide"]}).refine(($)=>!T7($.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"]}),hI1=A.object({tradingPairId:_$,side:PK,quantity:w4,options:A.object({tradingMode:lA.optional(),slippageTolerance:kr,marginAccountId:_$.optional(),marginMode:WT.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:vK.optional(),leverage:w4.optional(),reduceOnly:A.boolean().optional(),takeProfit:mA.optional(),stopLoss:mA.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(($)=>!T7($.options)||$.options?.tradingMode==="MARGIN",{message:"Parent TP/SL is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>!T7($.options)||$.options?.positionSide!=="NONE",{message:"Parent TP/SL requires positionSide to be LONG or SHORT",path:["options","positionSide"]}).refine(($)=>!T7($.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"]}),uI1=A.object({orderId:_$}),mI1=A.object({orderId:_$,newOrder:A.object({price:w4.optional(),quantity:w4.optional(),useMasterBalance:A.boolean().optional()})}),lI1=A.object({status:A.enum(CK).optional(),tradingPairId:_$.optional(),tradingMode:lA.optional(),marginAccountId:_$.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()}),dI1=A.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),pI1=A.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),wO$=A.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),nI1=A.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),cI1=A.object({conditionalOrderId:_$}),iI1=A.object({marginAccountId:_$.optional(),tradingPairId:_$.optional(),state:wO$.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()}),MO$=A.object({tradingPairId:_$,orderType:R7,side:PK,price:w4.optional(),quantity:w4,tradingMode:lA.optional(),slippageTolerance:kr,useMasterBalance:A.boolean().optional(),expirationDate:kK.optional(),timeInForce:vr.optional(),marginAccountId:_$.optional(),marginMode:WT.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:vK.optional(),leverage:w4.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"]}),oI1=A.object({orders:A.array(MO$).min(1,"At least one order is required")}),HO$=A.object({orderId:_$,price:w4.optional(),quantity:w4.optional(),useMasterBalance:A.boolean().optional()}).refine(($)=>$.price!==void 0||$.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),rI1=A.object({orders:A.array(HO$).min(1,"At least one order is required")});var VT=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()}),eI1=VT.extend({state:A.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:_$.optional()}),$q1=A.object({marginAccountId:_$,tradingPairId:_$.optional()}),Jq1=A.object({tradingPairId:_$.optional()}).optional(),Qq1=A.object({asset:A.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),AO$=A.object({asset:A.string().trim().min(1,"Asset cannot be empty"),amount:w4,tradingPairId:_$.optional(),strategyKey:A.string().trim().min(1,"Strategy key cannot be empty").optional()}),dA=A.object({asset:A.string().trim().min(1,"Asset cannot be empty"),amount:w4}),zO$=A.object({tradingPairId:_$,strategyKey:A.string().trim().min(1,"Strategy key cannot be empty").optional()}),IO$=A.array(_$).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),xr=zO$.extend({marginMode:A.literal("ISOLATED").optional(),selectedTradingPairIds:A.never().optional()}),fr=A.object({marginMode:A.literal("CROSS"),selectedTradingPairIds:IO$,strategyKey:A.never().optional()}),qO$=fr.extend({tradingPairId:A.never().optional()}),Xq1=A.object({marginAccountId:_$,request:AO$}),Yq1=A.object({request:dA}),Gq1=A.object({request:A.union([dA.merge(xr).strict(),dA.merge(qO$).strict()])}),Wq1=A.object({request:dA}),Dq1=VT.extend({marginAccountId:_$,movementType:A.string().trim().min(1,"Movement type cannot be empty").optional()}),Vq1=VT.extend({movementType:A.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),KT=A.object({tradingPairId:_$,side:PK,positionSide:vK,orderType:R7,price:w4.optional(),quantity:w4,leverage:w4,reduceOnly:A.boolean().optional()}),br=KT.strict(),ZO$=KT.merge(xr).strict(),LO$=KT.merge(fr).strict().refine(($)=>$.selectedTradingPairIds.includes($.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),BO$=A.union([ZO$,LO$]),Kq1=A.object({marginAccountId:_$,request:br}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Uq1=A.object({request:br}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Oq1=A.object({request:BO$}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var gr=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"'}),FO$=31536000000,jO$=946684800000,pA=A.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(jO$,{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()+FO$,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),Hq1=A.object({tradingPairId:_$,interval:gr,startTime:pA,endTime:pA}).refine(($)=>$.startTime<$.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),Aq1=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")'}),EO$=A.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),zq1=A.object({tradingPairId:_$,interval:gr,startTime:pA.optional(),endTime:pA.optional(),limit:EO$}).refine(($)=>{if($.startTime!==void 0&&$.endTime!==void 0)return $.startTime<$.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var Iq1=A.object({tradingPairId:_$}),qq1=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()}),Zq1=A.object({tradingPairId:_$});var hr=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()}),SO$=A.enum(["OPEN","CLOSED","LIQUIDATING"],{message:'Position status must be "OPEN", "CLOSED", or "LIQUIDATING"'}),_O$=A.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),fK=A.object({positionId:_$}),jq1=hr.extend({marginAccountId:_$.optional(),tradingPairId:_$.optional(),status:SO$.optional()});var Eq1=fK.extend({request:A.object({closeType:_O$,limitPrice:w4.optional(),slippageToleranceBps:xK.optional(),quantity:w4.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"]}),Sq1=A.object({tradingPairId:_$.optional(),slippageToleranceBps:xK.optional()});var _q1=fK.extend({request:A.object({amount:w4,asset:A.string().trim().min(1,"Asset cannot be empty")})}),Tq1=fK.extend({request:A.object({amount:w4})}),yr=A.object({triggerPrice:w4,orderType:R7,limitPrice:w4.optional(),quantity:w4.optional(),timeInForce:DT.optional(),slippageToleranceBps:xK.optional(),expiresAt:kK.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"]}),Rq1=fK.extend({request:A.object({takeProfit:yr.optional(),stopLoss:yr.optional()}).refine(($)=>$.takeProfit!==void 0||$.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"})}),Cq1=hr.extend({positionId:_$.optional(),marginAccountId:_$.optional(),tradingPairId:_$.optional()}),TO$=A.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),Pq1=fK.extend({params:A.object({interval:TO$,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 RO$=A.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),CO$=A.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),fq1=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:RO$.optional(),transactionType:CO$.optional(),assetId:_$.optional()}),bq1=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:_$.optional()}),gq1=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:_$.optional(),positionId:_$.optional(),marginAccountId:_$.optional()});var mq1=A.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),UT=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"})]),lq1=A.object({assetId:_$,amount:UT,autoWait:A.boolean().optional()}),dq1=A.object({assetId:_$,amount:UT,autoWait:A.boolean().optional(),target:A.enum(["spot","margin"]).optional()}),pq1=A.object({assetId:_$,amount:UT,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()}),nq1=A.object({assetId:_$});function ur($){$.registerTool("get_orders",{description:"Get a paginated list of orders with optional filters by status and trading pair.",inputSchema:A.object({status:A.enum(CK).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:A.string().optional().describe("Filter by trading pair UUID"),page:A.number().optional().describe("Page number (default: 1)"),pageSize:A.number().optional().describe("Orders per page (default: 10, max: 100)")})},async({status:J,tradingPairId:Q,page:Y,pageSize:X})=>{let W=await(await x$()).trading.getPaginatedOrders({status:J,tradingPairId:Q,page:Y,pageSize:X});return A$(W)})}function mr($){$.registerTool("place_limit_order",{description:"Place a limit order on Monaco. Limit orders execute only when the market reaches the specified price.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),side:A.enum(["BUY","SELL"]).describe("Order side"),quantity:A.string().describe("Order quantity as a decimal string"),price:A.string().describe("Limit price as a decimal string"),tradingMode:A.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:A.enum(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:A.string().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:A.string().optional().describe("Parent margin account UUID for MARGIN orders"),riskBucketId:A.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:A.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:A.string().optional().describe("Optional client strategy key"),positionSide:A.enum(["LONG","SHORT","NONE"]).optional().describe("Position side for MARGIN orders"),leverage:A.string().optional().describe("Leverage as a decimal string for MARGIN orders"),reduceOnly:A.boolean().optional().describe("Whether the order can only reduce existing exposure")})},async({tradingPairId:J,side:Q,quantity:Y,price:X,tradingMode:G,timeInForce:W,expirationDate:D,marginAccountId:V,riskBucketId:K,riskBucketCollateral:O,strategyKey:N,positionSide:w,leverage:M,reduceOnly:z})=>{let F=await(await x$()).trading.placeLimitOrder(J,Q,Y,X,{tradingMode:G,timeInForce:W,expirationDate:D,marginAccountId:V,riskBucketId:K,riskBucketCollateral:O,strategyKey:N,positionSide:w,leverage:M,reduceOnly:z});return A$(F)})}function lr($){$.registerTool("place_market_order",{description:"Place a market order on Monaco. Market orders execute immediately at the current market price.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),side:A.enum(["BUY","SELL"]).describe("Order side"),quantity:A.string().describe("Order quantity as a decimal string"),tradingMode:A.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:A.number().optional().describe("Slippage tolerance as decimal (e.g. 0.01 for 1%)"),marginAccountId:A.string().optional().describe("Parent margin account UUID for MARGIN orders"),riskBucketId:A.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:A.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:A.string().optional().describe("Optional client strategy key"),positionSide:A.enum(["LONG","SHORT","NONE"]).optional().describe("Position side for MARGIN orders"),leverage:A.string().optional().describe("Leverage as a decimal string for MARGIN orders"),reduceOnly:A.boolean().optional().describe("Whether the order can only reduce existing exposure")})},async({tradingPairId:J,side:Q,quantity:Y,tradingMode:X,slippageTolerance:G,marginAccountId:W,riskBucketId:D,riskBucketCollateral:V,strategyKey:K,positionSide:O,leverage:N,reduceOnly:w})=>{let z=await(await x$()).trading.placeMarketOrder(J,Q,Y,{tradingMode:X,slippageTolerance:G,marginAccountId:W,riskBucketId:D,riskBucketCollateral:V,strategyKey:K,positionSide:O,leverage:N,reduceOnly:w});return A$(z)})}function dr($){$.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open.",inputSchema:A.object({orderId:A.string().describe("The order ID to replace"),price:A.string().optional().describe("New price as a decimal string"),quantity:A.string().optional().describe("New quantity as a decimal string")})},async({orderId:J,price:Q,quantity:Y})=>{let G=await(await x$()).trading.replaceOrder(J,{price:Q,quantity:Y});return A$(G)})}function pr($){mr($),lr($),Tr($),Sr($),Er($),_r($),dr($),ur($),Rr($)}function nr($){$.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to check allowance for")})},async({assetId:J})=>{let Y=await(await x$()).vault.getAllowance(J);return A$({assetId:J,allowance:Y.toString()})})}function cr($){$.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to approve"),amount:A.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Max amount to approve as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:J,amount:Q})=>{let X=await(await x$()).vault.approve(J,BigInt(Q));return A$({hash:X.hash,status:X.status})})}function ir($){$.registerTool("vault_deposit",{description:"Deposit tokens into the Monaco vault. Requires prior approval for ERC20 tokens (use vault_approve first). Set target to 'margin' to route the deposit straight into margin collateral instead of the spot wallet.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to deposit"),amount:A.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to deposit as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)"),target:A.enum(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:J,amount:Q,target:Y})=>{let G=await(await x$()).vault.deposit(J,BigInt(Q),void 0,Y);return A$({hash:G.hash,status:G.status})})}function or($){$.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to check"),amount:A.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:J,amount:Q})=>{let X=await(await x$()).vault.needsApproval(J,BigInt(Q));return A$({assetId:J,amount:Q,needs_approval:X})})}function rr($){$.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to withdraw"),amount:A.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to withdraw as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:J,amount:Q})=>{let X=await(await x$()).vault.withdraw(J,BigInt(Q));return A$({withdrawalIndex:X.withdrawalIndex,status:X.status,hash:X.hash})})}function tr($){cr($),ir($),rr($),nr($),or($)}function ar($,J){if(Br($),Wr($),Vr($),jr($),wr($),J.authenticated)pr($),qr($),Jr($),tr($),so($,{network:J.network}),Mr($)}if(!globalThis.fetch)globalThis.fetch=IU,globalThis.Headers=$6,globalThis.Request=cJ,globalThis.Response=E1;if(!globalThis.WebSocket)globalThis.WebSocket=cz.default;async function PO$(){let $=P8(),J=$.privateKey!==null,Q=new tB({name:"monaco-mcp-server",version:Pw.version});ar(Q,{authenticated:J,network:$.network});let Y=new sB;await Q.connect(Y),console.error(J?"Monaco MCP server running on stdio":"Monaco MCP server running on stdio (public-only mode — set MONACO_PRIVATE_KEY and MONACO_CLIENT_ID for full access)")}PO$().catch(($)=>{console.error("Fatal error:",$),process.exit(1)});
|
|
169
|
+
`).find((D)=>D.startsWith("data: "));if(!W)throw Error("No data in Mintlify MCP response");return JSON.parse(W.slice(6))}async function QO$(){if(uA)return;await Zr("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:Pw.version}},0)}async function XO$($){return await QO$(),(await Zr("tools/call",{name:JO$,arguments:{query:$}},1))?.result}function Lr($){$.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:A.object({query:A.string().describe("The search query")})},async({query:J})=>{try{let Q=await XO$(J);if(Q?.content&&Array.isArray(Q.content))return{content:Q.content};return A$(Q)}catch(Q){return JJ(`Search failed: ${Q instanceof Error?Q.message:String(Q)}`)}})}function Br($){Lr($)}function Fr($){$.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),page:A.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:A.number().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:J,page:Q,pageSize:Y})=>{let G=await a1().trades.getTrades(J,{page:Q,pageSize:Y});return A$(G)})}function jr($){Fr($)}function Er($){$.registerTool("batch_cancel_all_orders",{description:"Cancel all active orders, optionally filtered to a specific trading pair.",inputSchema:A.object({tradingPairId:A.string().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:J})=>{let Y=await(await x$()).trading.batchCancelAll(J);return A$(Y)})}function Sr($){$.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request.",inputSchema:A.object({orderIds:A.array(A.string()).describe("Array of order IDs to cancel")})},async({orderIds:J})=>{let Y=await(await x$()).trading.batchCancel(J);return A$(Y)})}function _r($){$.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to a specific trading pair. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:A.object({tradingPairId:A.string().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:A.number().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:J,slippageToleranceBps:Q})=>{let X=await(await x$()).positions.batchCloseAllPositions({tradingPairId:J,slippageToleranceBps:Q});return A$(X)})}function Tr($){$.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:A.object({orderId:A.string().describe("The order ID to cancel")})},async({orderId:J})=>{let Y=await(await x$()).trading.cancelOrder(J);return A$(Y)})}function Rr($){$.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:A.object({orderId:A.string().describe("The order ID to look up")})},async({orderId:J})=>{let Y=await(await x$()).trading.getOrder(J);return A$(Y)})}var YO$=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"]})}),GO$=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()}),WO$=A.object({tradingPairId:A.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),Cr=A.object({tierLevel:A.number().int(),minVolumeThreshold:A.string(),makerFeeBps:A.string(),takerFeeBps:A.string()}),DO$=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(Cr)});var Pr=A.object({token:A.string(),available:A.string()}),VO$=A.object({balances:A.array(Pr)}),KO$=A.object({code:A.string(),createdAt:A.string()}),UO$=A.object({code:A.string()}),OO$=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")}),NO$=A.object({rewardsBalance:A.string(),tradingBalance:A.string()});var CK=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var PK=A.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),lA=A.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),WT=A.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),vK=A.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),vr=A.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),DT=A.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),R7=A.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),w4=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"}),_$=A.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),kK=A.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),kr=A.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),xK=A.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),mA=A.object({triggerPrice:w4,orderType:R7,limitPrice:w4.optional(),timeInForce:DT.optional(),slippageToleranceBps:xK.optional(),expiresAt:kK.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"]}),T7=($)=>$?.takeProfit!==void 0||$?.stopLoss!==void 0,yI1=A.object({tradingPairId:_$,side:PK,quantity:w4,price:w4,options:A.object({tradingMode:lA.optional(),useMasterBalance:A.boolean().optional(),expirationDate:kK.optional(),timeInForce:vr.optional(),marginAccountId:_$.optional(),marginMode:WT.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:vK.optional(),leverage:w4.optional(),reduceOnly:A.boolean().optional(),takeProfit:mA.optional(),stopLoss:mA.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(($)=>!T7($.options)||$.options?.tradingMode==="MARGIN",{message:"Parent TP/SL is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>!T7($.options)||$.options?.positionSide!=="NONE",{message:"Parent TP/SL requires positionSide to be LONG or SHORT",path:["options","positionSide"]}).refine(($)=>!T7($.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"]}),hI1=A.object({tradingPairId:_$,side:PK,quantity:w4,options:A.object({tradingMode:lA.optional(),slippageTolerance:kr,marginAccountId:_$.optional(),marginMode:WT.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:vK.optional(),leverage:w4.optional(),reduceOnly:A.boolean().optional(),takeProfit:mA.optional(),stopLoss:mA.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(($)=>!T7($.options)||$.options?.tradingMode==="MARGIN",{message:"Parent TP/SL is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>!T7($.options)||$.options?.positionSide!=="NONE",{message:"Parent TP/SL requires positionSide to be LONG or SHORT",path:["options","positionSide"]}).refine(($)=>!T7($.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"]}),uI1=A.object({orderId:_$}),mI1=A.object({orderId:_$,newOrder:A.object({price:w4.optional(),quantity:w4.optional(),useMasterBalance:A.boolean().optional()})}),lI1=A.object({status:A.enum(CK).optional(),tradingPairId:_$.optional(),tradingMode:lA.optional(),marginAccountId:_$.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()}),dI1=A.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),pI1=A.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),wO$=A.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),nI1=A.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),cI1=A.object({conditionalOrderId:_$}),iI1=A.object({marginAccountId:_$.optional(),tradingPairId:_$.optional(),state:wO$.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()}),MO$=A.object({tradingPairId:_$,orderType:R7,side:PK,price:w4.optional(),quantity:w4,tradingMode:lA.optional(),slippageTolerance:kr,useMasterBalance:A.boolean().optional(),expirationDate:kK.optional(),timeInForce:vr.optional(),marginAccountId:_$.optional(),marginMode:WT.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:vK.optional(),leverage:w4.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"]}),oI1=A.object({orders:A.array(MO$).min(1,"At least one order is required")}),HO$=A.object({orderId:_$,price:w4.optional(),quantity:w4.optional(),useMasterBalance:A.boolean().optional()}).refine(($)=>$.price!==void 0||$.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),rI1=A.object({orders:A.array(HO$).min(1,"At least one order is required")});var VT=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()}),eI1=VT.extend({state:A.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:_$.optional()}),$q1=A.object({marginAccountId:_$,tradingPairId:_$.optional()}),Jq1=A.object({tradingPairId:_$.optional()}).optional(),Qq1=A.object({asset:A.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),AO$=A.object({asset:A.string().trim().min(1,"Asset cannot be empty"),amount:w4,tradingPairId:_$.optional(),strategyKey:A.string().trim().min(1,"Strategy key cannot be empty").optional()}),dA=A.object({asset:A.string().trim().min(1,"Asset cannot be empty"),amount:w4}),zO$=A.object({tradingPairId:_$,strategyKey:A.string().trim().min(1,"Strategy key cannot be empty").optional()}),IO$=A.array(_$).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),xr=zO$.extend({marginMode:A.literal("ISOLATED").optional(),selectedTradingPairIds:A.never().optional()}),fr=A.object({marginMode:A.literal("CROSS"),selectedTradingPairIds:IO$,strategyKey:A.never().optional()}),qO$=fr.extend({tradingPairId:A.never().optional()}),Xq1=A.object({marginAccountId:_$,request:AO$}),Yq1=A.object({request:dA}),Gq1=A.object({request:A.union([dA.merge(xr).strict(),dA.merge(qO$).strict()])}),Wq1=A.object({request:dA}),Dq1=VT.extend({marginAccountId:_$,movementType:A.string().trim().min(1,"Movement type cannot be empty").optional()}),Vq1=VT.extend({movementType:A.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),KT=A.object({tradingPairId:_$,side:PK,positionSide:vK,orderType:R7,price:w4.optional(),quantity:w4,leverage:w4,reduceOnly:A.boolean().optional()}),br=KT.strict(),ZO$=KT.merge(xr).strict(),LO$=KT.merge(fr).strict().refine(($)=>$.selectedTradingPairIds.includes($.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),BO$=A.union([ZO$,LO$]),Kq1=A.object({marginAccountId:_$,request:br}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Uq1=A.object({request:br}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Oq1=A.object({request:BO$}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var gr=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"'}),FO$=31536000000,jO$=946684800000,pA=A.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(jO$,{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()+FO$,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),Hq1=A.object({tradingPairId:_$,interval:gr,startTime:pA,endTime:pA}).refine(($)=>$.startTime<$.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),Aq1=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")'}),EO$=A.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),zq1=A.object({tradingPairId:_$,interval:gr,startTime:pA.optional(),endTime:pA.optional(),limit:EO$}).refine(($)=>{if($.startTime!==void 0&&$.endTime!==void 0)return $.startTime<$.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var Iq1=A.object({tradingPairId:_$}),qq1=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()}),Zq1=A.object({tradingPairId:_$});var hr=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()}),SO$=A.enum(["OPEN","CLOSED","LIQUIDATING"],{message:'Position status must be "OPEN", "CLOSED", or "LIQUIDATING"'}),_O$=A.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),fK=A.object({positionId:_$}),jq1=hr.extend({marginAccountId:_$.optional(),tradingPairId:_$.optional(),status:SO$.optional()});var Eq1=fK.extend({request:A.object({closeType:_O$,limitPrice:w4.optional(),slippageToleranceBps:xK.optional(),quantity:w4.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"]}),Sq1=A.object({tradingPairId:_$.optional(),slippageToleranceBps:xK.optional()});var _q1=fK.extend({request:A.object({amount:w4,asset:A.string().trim().min(1,"Asset cannot be empty")})}),Tq1=fK.extend({request:A.object({amount:w4})}),yr=A.object({triggerPrice:w4,orderType:R7,limitPrice:w4.optional(),quantity:w4.optional(),timeInForce:DT.optional(),slippageToleranceBps:xK.optional(),expiresAt:kK.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"]}),Rq1=fK.extend({request:A.object({takeProfit:yr.optional(),stopLoss:yr.optional()}).refine(($)=>$.takeProfit!==void 0||$.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"})}),Cq1=hr.extend({positionId:_$.optional(),marginAccountId:_$.optional(),tradingPairId:_$.optional(),reductionOnly:A.boolean().optional()}),TO$=A.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),Pq1=fK.extend({params:A.object({interval:TO$,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 RO$=A.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),CO$=A.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),fq1=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:RO$.optional(),transactionType:CO$.optional(),assetId:_$.optional()}),bq1=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:_$.optional()}),gq1=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:_$.optional(),positionId:_$.optional(),marginAccountId:_$.optional()});var mq1=A.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),UT=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"})]),lq1=A.object({assetId:_$,amount:UT,autoWait:A.boolean().optional()}),dq1=A.object({assetId:_$,amount:UT,autoWait:A.boolean().optional(),target:A.enum(["spot","margin"]).optional()}),pq1=A.object({assetId:_$,amount:UT,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()}),nq1=A.object({assetId:_$});function ur($){$.registerTool("get_orders",{description:"Get a paginated list of orders with optional filters by status and trading pair.",inputSchema:A.object({status:A.enum(CK).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:A.string().optional().describe("Filter by trading pair UUID"),page:A.number().optional().describe("Page number (default: 1)"),pageSize:A.number().optional().describe("Orders per page (default: 10, max: 100)")})},async({status:J,tradingPairId:Q,page:Y,pageSize:X})=>{let W=await(await x$()).trading.getPaginatedOrders({status:J,tradingPairId:Q,page:Y,pageSize:X});return A$(W)})}function mr($){$.registerTool("place_limit_order",{description:"Place a limit order on Monaco. Limit orders execute only when the market reaches the specified price.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),side:A.enum(["BUY","SELL"]).describe("Order side"),quantity:A.string().describe("Order quantity as a decimal string"),price:A.string().describe("Limit price as a decimal string"),tradingMode:A.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:A.enum(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:A.string().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:A.string().optional().describe("Parent margin account UUID for MARGIN orders"),riskBucketId:A.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:A.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:A.string().optional().describe("Optional client strategy key"),positionSide:A.enum(["LONG","SHORT","NONE"]).optional().describe("Position side for MARGIN orders"),leverage:A.string().optional().describe("Leverage as a decimal string for MARGIN orders"),reduceOnly:A.boolean().optional().describe("Whether the order can only reduce existing exposure")})},async({tradingPairId:J,side:Q,quantity:Y,price:X,tradingMode:G,timeInForce:W,expirationDate:D,marginAccountId:V,riskBucketId:K,riskBucketCollateral:O,strategyKey:N,positionSide:w,leverage:M,reduceOnly:z})=>{let F=await(await x$()).trading.placeLimitOrder(J,Q,Y,X,{tradingMode:G,timeInForce:W,expirationDate:D,marginAccountId:V,riskBucketId:K,riskBucketCollateral:O,strategyKey:N,positionSide:w,leverage:M,reduceOnly:z});return A$(F)})}function lr($){$.registerTool("place_market_order",{description:"Place a market order on Monaco. Market orders execute immediately at the current market price.",inputSchema:A.object({tradingPairId:A.string().describe("Trading pair UUID"),side:A.enum(["BUY","SELL"]).describe("Order side"),quantity:A.string().describe("Order quantity as a decimal string"),tradingMode:A.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:A.number().optional().describe("Slippage tolerance as decimal (e.g. 0.01 for 1%)"),marginAccountId:A.string().optional().describe("Parent margin account UUID for MARGIN orders"),riskBucketId:A.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:A.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:A.string().optional().describe("Optional client strategy key"),positionSide:A.enum(["LONG","SHORT","NONE"]).optional().describe("Position side for MARGIN orders"),leverage:A.string().optional().describe("Leverage as a decimal string for MARGIN orders"),reduceOnly:A.boolean().optional().describe("Whether the order can only reduce existing exposure")})},async({tradingPairId:J,side:Q,quantity:Y,tradingMode:X,slippageTolerance:G,marginAccountId:W,riskBucketId:D,riskBucketCollateral:V,strategyKey:K,positionSide:O,leverage:N,reduceOnly:w})=>{let z=await(await x$()).trading.placeMarketOrder(J,Q,Y,{tradingMode:X,slippageTolerance:G,marginAccountId:W,riskBucketId:D,riskBucketCollateral:V,strategyKey:K,positionSide:O,leverage:N,reduceOnly:w});return A$(z)})}function dr($){$.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open.",inputSchema:A.object({orderId:A.string().describe("The order ID to replace"),price:A.string().optional().describe("New price as a decimal string"),quantity:A.string().optional().describe("New quantity as a decimal string")})},async({orderId:J,price:Q,quantity:Y})=>{let G=await(await x$()).trading.replaceOrder(J,{price:Q,quantity:Y});return A$(G)})}function pr($){mr($),lr($),Tr($),Sr($),Er($),_r($),dr($),ur($),Rr($)}function nr($){$.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to check allowance for")})},async({assetId:J})=>{let Y=await(await x$()).vault.getAllowance(J);return A$({assetId:J,allowance:Y.toString()})})}function cr($){$.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to approve"),amount:A.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Max amount to approve as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:J,amount:Q})=>{let X=await(await x$()).vault.approve(J,BigInt(Q));return A$({hash:X.hash,status:X.status})})}function ir($){$.registerTool("vault_deposit",{description:"Deposit tokens into the Monaco vault. Requires prior approval for ERC20 tokens (use vault_approve first). Set target to 'margin' to route the deposit straight into margin collateral instead of the spot wallet.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to deposit"),amount:A.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to deposit as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)"),target:A.enum(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:J,amount:Q,target:Y})=>{let G=await(await x$()).vault.deposit(J,BigInt(Q),void 0,Y);return A$({hash:G.hash,status:G.status})})}function or($){$.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to check"),amount:A.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:J,amount:Q})=>{let X=await(await x$()).vault.needsApproval(J,BigInt(Q));return A$({assetId:J,amount:Q,needs_approval:X})})}function rr($){$.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:A.object({assetId:A.string().describe("The asset UUID to withdraw"),amount:A.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to withdraw as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:J,amount:Q})=>{let X=await(await x$()).vault.withdraw(J,BigInt(Q));return A$({withdrawalIndex:X.withdrawalIndex,status:X.status,hash:X.hash})})}function tr($){cr($),ir($),rr($),nr($),or($)}function ar($,J){if(Br($),Wr($),Vr($),jr($),wr($),J.authenticated)pr($),qr($),Jr($),tr($),so($,{network:J.network}),Mr($)}if(!globalThis.fetch)globalThis.fetch=IU,globalThis.Headers=$6,globalThis.Request=cJ,globalThis.Response=E1;if(!globalThis.WebSocket)globalThis.WebSocket=cz.default;async function PO$(){let $=P8(),J=$.privateKey!==null,Q=new tB({name:"monaco-mcp-server",version:Pw.version});ar(Q,{authenticated:J,network:$.network});let Y=new sB;await Q.connect(Y),console.error(J?"Monaco MCP server running on stdio":"Monaco MCP server running on stdio (public-only mode — set MONACO_PRIVATE_KEY and MONACO_CLIENT_ID for full access)")}PO$().catch(($)=>{console.error("Fatal error:",$),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0xmonaco/mcp-server",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
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.
|
|
29
|
-
"@0xmonaco/types": "1.0.
|
|
28
|
+
"@0xmonaco/core": "1.0.3",
|
|
29
|
+
"@0xmonaco/types": "1.0.3",
|
|
30
30
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
31
31
|
"node-fetch": "^3.3.2",
|
|
32
32
|
"viem": "^2.53.1",
|