@0xmonaco/mcp-server 1.0.26 → 1.0.28
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 iN($,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]:v$($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",X]})??h4(J)}),{}),additionalProperties:J.rejectedAdditionalProperties};let Q={type:"object",additionalProperties:v$($.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}=cN($.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}=nN($.keyType._def,J);return{...Q,propertyNames:X}}return Q}function Yx($,J){if(J.mapStrategy==="record")return iN($,J);let Q=v$($.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||h4(J),Y=v$($.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 Gx($){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 Wx($){return $.target==="openAi"?void 0:{not:h4({...$,currentPath:[...$.currentPath,"not"]})}}function Dx($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ED={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Kx($,J){if(J.target==="openApi3")return Vx($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((Y)=>(Y._def.typeName in ED)&&(!Y._def.checks||!Y._def.checks.length))){let Y=Q.reduce((X,G)=>{let W=ED[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 Vx($,J)}var Vx=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((Y,X)=>v$(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 Ux($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:ED[$.innerType._def.typeName],nullable:!0};return{type:[ED[$.innerType._def.typeName],"null"]}}if(J.target==="openApi3"){let Y=v$($.innerType._def,{...J,currentPath:[...J.currentPath]});if(Y&&"$ref"in Y)return{allOf:[Y],nullable:!0};return Y&&{...Y,nullable:!0}}let Q=v$($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return Q&&{anyOf:[Q,{type:"null"}]}}function Ox($,J){let Q={type:"number"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"int":Q.type="integer",PZ(Q,"type",Y.message,J);break;case"min":if(J.target==="jsonSchema7")if(Y.inclusive)$4(Q,"minimum",Y.value,Y.message,J);else $4(Q,"exclusiveMinimum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;$4(Q,"minimum",Y.value,Y.message,J)}break;case"max":if(J.target==="jsonSchema7")if(Y.inclusive)$4(Q,"maximum",Y.value,Y.message,J);else $4(Q,"exclusiveMaximum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;$4(Q,"maximum",Y.value,Y.message,J)}break;case"multipleOf":$4(Q,"multipleOf",Y.value,Y.message,J);break}return Q}function Nx($,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=g0$(V);if(K&&Q){if(V._def.typeName==="ZodOptional")V=V._def.innerType;if(!V.isNullable())V=V.nullable();K=!1}let O=v$(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=b0$($,J);if(W!==void 0)Y.additionalProperties=W;return Y}function b0$($,J){if($.catchall._def.typeName!=="ZodNever")return v$($.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 g0$($){try{return $.isOptional()}catch{return!0}}var wx=($,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return v$($.innerType._def,J);let Q=v$($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:h4(J)},Q]}:h4(J)};var Mx=($,J)=>{if(J.pipeStrategy==="input")return v$($.in._def,J);else if(J.pipeStrategy==="output")return v$($.out._def,J);let Q=v$($.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),Y=v$($.out._def,{...J,currentPath:[...J.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,Y].filter((X)=>X!==void 0)}};function Hx($,J){return v$($.type._def,J)}function zx($,J){let Y={type:"array",uniqueItems:!0,items:v$($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)$4(Y,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)$4(Y,"maxItems",$.maxSize.value,$.maxSize.message,J);return Y}function Ax($,J){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Q,Y)=>v$(Q._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[]),additionalItems:v$($.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Q,Y)=>v$(Q._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[])}}function Ix($){return{not:h4($)}}function qx($){return h4($)}var Lx=($,J)=>{return v$($.innerType._def,J)};var Zx=($,J,Q)=>{switch(J){case J$.ZodString:return cN($,Q);case J$.ZodNumber:return Ox($,Q);case J$.ZodObject:return Nx($,Q);case J$.ZodBigInt:return rk($,Q);case J$.ZodBoolean:return tk();case J$.ZodDate:return vZ($,Q);case J$.ZodUndefined:return Ix(Q);case J$.ZodNull:return Dx(Q);case J$.ZodArray:return ok($,Q);case J$.ZodUnion:case J$.ZodDiscriminatedUnion:return Kx($,Q);case J$.ZodIntersection:return Jx($,Q);case J$.ZodTuple:return Ax($,Q);case J$.ZodRecord:return iN($,Q);case J$.ZodLiteral:return Qx($,Q);case J$.ZodEnum:return $x($);case J$.ZodNativeEnum:return Gx($);case J$.ZodNullable:return Ux($,Q);case J$.ZodOptional:return wx($,Q);case J$.ZodMap:return Yx($,Q);case J$.ZodSet:return zx($,Q);case J$.ZodLazy:return()=>$.getter()._def;case J$.ZodPromise:return Hx($,Q);case J$.ZodNaN:case J$.ZodNever:return Wx(Q);case J$.ZodEffects:return ek($,Q);case J$.ZodAny:return h4(Q);case J$.ZodUnknown:return qx(Q);case J$.ZodDefault:return sk($,Q);case J$.ZodBranded:return nN($,Q);case J$.ZodReadonly:return Lx($,Q);case J$.ZodCatch:return ak($,Q);case J$.ZodPipeline:return Mx($,Q);case J$.ZodFunction:case J$.ZodVoid:case J$.ZodSymbol:return;default:return((Y)=>{return})(J)}};function v$($,J,Q=!1){let Y=J.seen.get($);if(J.override){let D=J.override?.($,J,Y,Q);if(D!==nk)return D}if(Y&&!Q){let D=y0$(Y,J);if(D!==void 0)return D}let X={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,X);let G=Zx($,$.typeName,J),W=typeof G==="function"?v$(G(),J):G;if(W)h0$($,J,W);if(J.postProcess){let D=J.postProcess(W,$,J);return X.jsonSchema=W,D}return X.jsonSchema=W,W}var y0$=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:pN(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}}},h0$=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var fZ=($,J)=>{let Q=ik(J),Y=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((V,[K,O])=>({...V,[K]:v$(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=v$($._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 u0$($){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 bZ($,J){if($0($))return cX($,{target:u0$(J?.target),io:J?.pipeStrategy??"input"});return fZ($,{strictUnions:J?.strictUnions??!0,pipeStrategy:J?.pipeStrategy??"input"})}function gZ($){let Q=q8($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=i3(Q);if(typeof Y!=="string")throw Error("Schema method literal must be a string");return Y}function yZ($,J){let Q=I8($,J);if(!Q.success)throw Q.error;return Q.data}var m0$=60000;class hZ{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(_N,(J)=>{this._oncancel(J)}),this.setNotificationHandler(RN,(J)=>{this._onprogress(J)}),this.setRequestHandler(TN,(J)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(CN,async(J,Q)=>{let Y=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!Y)throw new F$(S$.InvalidParams,"Failed to retrieve task: Task not found");return{...Y}}),this.setRequestHandler(vN,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 F$(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 F$(S$.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,[Z8]:{taskId:X}}}}return await Y()};return await Y()}),this.setRequestHandler(kN,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 F$(S$.InvalidParams,`Failed to list tasks: ${Y instanceof Error?Y.message:String(Y)}`)}}),this.setRequestHandler(fN,async(J,Q)=>{try{let Y=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!Y)throw new F$(S$.InvalidParams,`Task not found: ${J.params.taskId}`);if(B8(Y.status))throw new F$(S$.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 F$(S$.InvalidParams,`Task not found after cancellation: ${J.params.taskId}`);return{_meta:{},...X}}catch(Y){if(Y instanceof F$)throw Y;throw new F$(S$.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($),F$.fromError(S$.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),zD(X)||vk(X))this._onresponse(X);else if(AZ(X))this._onrequest(X,G);else if(Pk(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=F$.fromError(S$.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?.[Z8]?.taskId;if(Q===void 0){let K={jsonrpc:"2.0",id:$.id,error:{code:S$.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=Tk($.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 F$(S$.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:S$.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),zD($))Q($);else{let G=new F$($.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(zD($)&&$.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(zD($))Y($);else{let G=F$.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 F$?G:new F$(S$.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 F$(S$.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 F$(S$.InternalError,`Task ${X} failed`)};else if(W.status==="cancelled")yield{type:"error",error:new F$(S$.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 F$?G:new F$(S$.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||{},[Z8]: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 F$?Z:new F$(S$.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 A=Q?.timeout??m0$,q=()=>M(F$.fromError(S$.RequestTimeout,"Request timed out",{timeout:A}));this._setupTimeout(N,A,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:$},PN,J)}async getTaskResult($,J,Q){return this.request({method:"tasks/result",params:$},J,Q)}async listTasks($,J){return this.request({method:"tasks/list",params:$},xN,J)}async cancelTask($,J){return this.request({method:"tasks/cancel",params:$},fk,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||{},[Z8]: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||{},[Z8]: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||{},[Z8]:J.relatedTask}}};await this._transport.send(G,J)}setRequestHandler($,J){let Q=gZ($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(Y,X)=>{let G=yZ($,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=gZ($);this._notificationHandlers.set(Q,(Y)=>{let X=yZ($,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"&&AZ(Y.message)){let X=Y.message.id,G=this._requestResolvers.get(X);if(G)G(new F$(S$.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 F$(S$.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Y,Q);J.addEventListener("abort",()=>{clearTimeout(G),X(new F$(S$.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 F$(S$.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=ZD.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 F$(S$.InvalidParams,`Task "${Y}" not found - it may have been cleaned up`);if(B8(W.status))throw new F$(S$.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=ZD.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 Bx($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Fx($,J){let Q={...$};for(let Y in J){let X=Y,G=J[X];if(G===void 0)continue;let W=Q[X];if(Bx(W)&&Bx(G))Q[X]={...W,...G};else Q[X]=G}return Q}var Wh=e1(xB(),1),Dh=e1(Gh(),1);function K7$(){let $=new Wh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Dh.default($),$}class pB{constructor($){this._ajv=$??K7$()}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 nB{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:$},jD,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},Z5,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 Vh($,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 Kh($,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 cB extends hZ{constructor($,J){super(J);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(FD.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 pB,this.setRequestHandler(LZ,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(ZZ,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(TZ,async(Q,Y)=>{let X=Y.sessionId||Y.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=Q.params,W=FD.safeParse(G);if(W.success)this._loggingLevels.set(X,W.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new nB(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Fx(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(L5,D);if(!K.success){let M=K.error instanceof Error?K.error.message:String(K.error);throw new F$(S$.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 A=M.error instanceof Error?M.error.message:String(M.error);throw new F$(S$.InvalidParams,`Invalid task creation result: ${A}`)}return M.data}let w=I8(lN,N);if(!w.success){let M=w.error instanceof Error?w.error.message:String(w.error);throw new F$(S$.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($){Kh(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;Vh(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let J=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:Ek.includes(J)?J:HZ,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"},SN)}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:$},RZ,J);return this.request({method:"sampling/createMessage",params:$},jD,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},Z5,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},Z5,J);if(X.action==="accept"&&X.content&&Y.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(Y.requestedSchema)(X.content);if(!W.valid)throw new F$(S$.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(G){if(G instanceof F$)throw G;throw new F$(S$.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:$},CZ,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 Oh=Symbol.for("mcp.completable");function iB($){return!!$&&typeof $==="object"&&Oh in $}function Nh($){return $[Oh]?.complete}var Uh;(function($){$.Completable="McpCompletable"})(Uh||(Uh={}));var U7$=/^[A-Za-z0-9._-]{1,128}$/;function O7$($){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(!U7$.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 N7$($,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 oB($){let J=O7$($);return N7$($,J.warnings),J.isValid}class rB{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 aB{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 cB($,J)}get experimental(){if(!this._experimental)this._experimental={tasks:new rB(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(mN)),this.server.assertCanSetRequestHandler(C8(L5)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(mN,()=>({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?bZ(Y,{strictUnions:!0,pipeStrategy:"input"}):w7$})(),annotations:J.annotations,execution:J.execution,_meta:J._meta};if(J.outputSchema){let Y=D5(J.outputSchema);if(Y)Q.outputSchema=bZ(Y,{strictUnions:!0,pipeStrategy:"output"})}return Q})})),this.server.setRequestHandler(L5,async($,J)=>{try{let Q=this._registeredTools[$.params.name];if(!Q)throw new F$(S$.InvalidParams,`Tool ${$.params.name} not found`);if(!Q.enabled)throw new F$(S$.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 F$(S$.InternalError,`Tool ${$.params.name} has taskSupport '${X}' but was not registered with registerToolTask`);if(X==="required"&&!Y)throw new F$(S$.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 F$){if(Q.code===S$.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 n3(X,J);if(!G.success){let W="error"in G?G.error:"Unknown error",D=c3(W);throw new F$(S$.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 F$(S$.InvalidParams,`Output validation error: Tool ${Q} has an output schema but no structured content was provided`);let Y=D5($.outputSchema),X=await n3(Y,J.structuredContent);if(!X.success){let G="error"in X?X.error:"Unknown error",W=c3(G);throw new F$(S$.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 F$(S$.InternalError,`Task ${D} not found during polling`);V=O}return await Q.taskStore.getTaskResult(D)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(C8(dN)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(dN,async($)=>{switch($.params.ref.type){case"ref/prompt":return mk($),this.handlePromptCompletion($,$.params.ref);case"ref/resource":return lk($),this.handleResourceCompletion($,$.params.ref);default:throw new F$(S$.InvalidParams,`Invalid completion reference: ${$.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion($,J){let Q=this._registeredPrompts[J.name];if(!Q)throw new F$(S$.InvalidParams,`Prompt ${J.name} not found`);if(!Q.enabled)throw new F$(S$.InvalidParams,`Prompt ${J.name} disabled`);if(!Q.argsSchema)return rD;let X=q8(Q.argsSchema)?.[$.params.argument.name];if(!iB(X))return rD;let G=Nh(X);if(!G)return rD;let W=await G($.params.argument.value,$.params.context);return Mh(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 rD;throw new F$(S$.InvalidParams,`Resource template ${$.params.ref.uri} not found`)}let Y=Q.resourceTemplate.completeCallback($.params.argument.name);if(!Y)return rD;let X=await Y($.params.argument.value,$.params.context);return Mh(X)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(C8(bN)),this.server.assertCanSetRequestHandler(C8(gN)),this.server.assertCanSetRequestHandler(C8(yN)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(bN,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(gN,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([J,Q])=>({name:J,uriTemplate:Q.resourceTemplate.uriTemplate.toString(),...Q.metadata}))}}),this.server.setRequestHandler(yN,async($,J)=>{let Q=new URL($.params.uri),Y=this._registeredResources[Q.toString()];if(Y){if(!Y.enabled)throw new F$(S$.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 F$(S$.InvalidParams,`Resource ${Q} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(C8(hN)),this.server.assertCanSetRequestHandler(C8(uN)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(hN,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,$])=>$.enabled).map(([$,J])=>{return{name:$,title:J.title,description:J.description,arguments:J.argsSchema?M7$(J.argsSchema):void 0}})})),this.server.setRequestHandler(uN,async($,J)=>{let Q=this._registeredPrompts[$.params.name];if(!Q)throw new F$(S$.InvalidParams,`Prompt ${$.params.name} not found`);if(!Q.enabled)throw new F$(S$.InvalidParams,`Prompt ${$.params.name} disabled`);if(Q.argsSchema){let Y=D5(Q.argsSchema),X=await n3(Y,$.params.arguments);if(!X.success){let D="error"in X?X.error:"Unknown error",V=c3(D);throw new F$(S$.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 z5?D._def?.innerType:D;return iB(V)}))this.setCompletionRequestHandler()}return G}_createRegisteredTool($,J,Q,Y,X,G,W,D,V){oB($);let K={title:J,description:Q,inputSchema:wh(Y),outputSchema:wh(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")oB(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(tB(D)){if(Y=J.shift(),J.length>1&&typeof J[0]==="object"&&J[0]!==null&&!tB(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 w7$={type:"object",properties:{}};function Hh($){return $!==null&&typeof $==="object"&&"parse"in $&&typeof $.parse==="function"&&"safeParse"in $&&typeof $.safeParse==="function"}function zh($){return"_def"in $||"_zod"in $||Hh($)}function tB($){if(typeof $!=="object"||$===null)return!1;if(zh($))return!1;if(Object.keys($).length===0)return!0;return Object.values($).some(Hh)}function wh($){if(!$)return;if(tB($))return iX($);if(!zh($))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return $}function M7$($){let J=q8($);if(!J)return[];return Object.entries(J).map(([Q,Y])=>{let X=Uv(Y),G=Ov(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=i3(Q);if(typeof Y==="string")return Y;throw Error("Schema method literal must be a string")}function Mh($){return{completion:{values:$.slice(0,100),total:$.length,hasMore:$.length>100}}}var rD={completion:{values:[],hasMore:!1}};import Ih from"node:process";class sB{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),H7$(J)}clear(){this._buffer=void 0}}function H7$($){return kk.parse(JSON.parse($))}function Ah($){return JSON.stringify($)+`
|
|
136
|
-
`}class eB{constructor($=Ih.stdin,J=Ih.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new sB,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=Ah($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var Cw={name:"@0xmonaco/mcp-server",version:"1.0.26",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.26","@0xmonaco/types":"1.0.26","@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 A7$={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||A7$[G];return{privateKey:J,clientId:Q,network:G,seiRpcUrl:W}}function I7$($){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[I7$(Q)]=typeof Y==="object"&&Y!==null?f5(Y):Y;return J}W0();$V();W0();AF();M9();N9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ZJ=BigInt(0),U6=BigInt(1),Gu=BigInt(2),u7$=BigInt(8),m7$={zip215:!0};function l7$($){let J=XV($);return g0($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function Wu($){let J=l7$($),{Fp:Q,n:Y,prehash:X,hash:G,randomBytes:W,nByteLength:D,h:V}=J,K=Gu<<BigInt(D*8)-U6,O=Q.create,N=HQ(J.n,J.nBitLength);function w(_,k){let b=Q.sqr(_),t=Q.sqr(k),n=Q.add(Q.mul(J.a,b),t),N$=Q.add(Q.ONE,Q.mul(J.d,Q.mul(b,t)));return Q.eql(n,N$)}if(!w(J.Gx,J.Gy))throw Error("bad curve params: generator point");let M=J.uvRatio||((_,k)=>{try{return{isValid:!0,value:Q.sqrt(_*Q.inv(k))}}catch(b){return{isValid:!1,value:ZJ}}}),A=J.adjustScalarBytes||((_)=>_),q=J.domain||((_,k,b)=>{if(qJ("phflag",b),k.length||b)throw Error("Contexts/pre-hash are not supported");return _});function F(_,k,b=!1){let t=b?U6:ZJ;V6("coordinate "+_,k,t,K)}function Z(_){if(!(_ instanceof L))throw Error("ExtendedPoint expected")}let E=u5((_,k)=>{let{ex:b,ey:t,ez:n}=_,N$=_.is0();if(k==null)k=N$?u7$:Q.inv(n);let I$=O(b*k),w$=O(t*k),f$=O(n*k);if(N$)return{x:ZJ,y:U6};if(f$!==U6)throw Error("invZ was invalid");return{x:I$,y:w$}}),B=u5((_)=>{let{a:k,d:b}=J;if(_.is0())throw Error("bad point: ZERO");let{ex:t,ey:n,ez:N$,et:I$}=_,w$=O(t*t),f$=O(n*n),H4=O(N$*N$),i$=O(H4*H4),p4=O(w$*k),a4=O(H4*O(p4+f$)),Y1=O(i$+O(b*O(w$*f$)));if(a4!==Y1)throw Error("bad point: equation left != right (1)");let d1=O(t*n),s4=O(N$*I$);if(d1!==s4)throw Error("bad point: equation left != right (2)");return!0});class L{constructor(_,k,b,t){F("x",_),F("y",k),F("z",b,!0),F("t",t),this.ex=_,this.ey=k,this.ez=b,this.et=t,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:k,y:b}=_||{};return F("x",k),F("y",b),new L(k,b,U6,O(k*b))}static normalizeZ(_){let k=MQ(Q,_.map((b)=>b.ez));return _.map((b,t)=>b.toAffine(k[t])).map(L.fromAffine)}static msm(_,k){return uw(L,N,_,k)}_setWindowSize(_){v.setWindowSize(this,_)}assertValidity(){B(this)}equals(_){Z(_);let{ex:k,ey:b,ez:t}=this,{ex:n,ey:N$,ez:I$}=_,w$=O(k*I$),f$=O(n*t),H4=O(b*I$),i$=O(N$*t);return w$===f$&&H4===i$}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:k,ey:b,ez:t}=this,n=O(k*k),N$=O(b*b),I$=O(Gu*O(t*t)),w$=O(_*n),f$=k+b,H4=O(O(f$*f$)-n-N$),i$=w$+N$,p4=i$-I$,a4=w$-N$,Y1=O(H4*p4),d1=O(i$*a4),s4=O(H4*a4),Z6=O(p4*i$);return new L(Y1,d1,Z6,s4)}add(_){Z(_);let{a:k,d:b}=J,{ex:t,ey:n,ez:N$,et:I$}=this,{ex:w$,ey:f$,ez:H4,et:i$}=_,p4=O(t*w$),a4=O(n*f$),Y1=O(I$*b*i$),d1=O(N$*H4),s4=O((t+n)*(w$+f$)-p4-a4),Z6=d1-Y1,p1=d1+Y1,dQ=O(a4-k*p4),T7=O(s4*Z6),XY=O(p1*dQ),fK=O(s4*dQ),q0=O(Z6*p1);return new L(T7,XY,q0,fK)}subtract(_){return this.add(_.negate())}wNAF(_){return v.wNAFCached(this,_,L.normalizeZ)}multiply(_){let k=_;V6("scalar",k,U6,Y);let{p:b,f:t}=this.wNAF(k);return L.normalizeZ([b,t])[0]}multiplyUnsafe(_,k=L.ZERO){let b=_;if(V6("scalar",b,ZJ,Y),b===ZJ)return T;if(this.is0()||b===U6)return this;return v.wNAFCachedUnsafe(this,b,L.normalizeZ,k)}isSmallOrder(){return this.multiplyUnsafe(V).is0()}isTorsionFree(){return v.unsafeLadder(this,Y).is0()}toAffine(_){return E(this,_)}clearCofactor(){let{h:_}=J;if(_===U6)return this;return this.multiplyUnsafe(_)}static fromHex(_,k=!1){let{d:b,a:t}=J,n=Q.BYTES;_=A4("pointHex",_,n),qJ("zip215",k);let N$=_.slice(),I$=_[n-1];N$[n-1]=I$&-129;let w$=K9(N$),f$=k?K:Q.ORDER;V6("pointHex.y",w$,ZJ,f$);let H4=O(w$*w$),i$=O(H4-U6),p4=O(b*H4-t),{isValid:a4,value:Y1}=M(i$,p4);if(!a4)throw Error("Point.fromHex: invalid y coordinate");let d1=(Y1&U6)===U6,s4=(I$&128)!==0;if(!k&&Y1===ZJ&&s4)throw Error("Point.fromHex: x=0 and x_0=1");if(s4!==d1)Y1=O(-Y1);return L.fromAffine({x:Y1,y:w$})}static fromPrivateKey(_){let{scalar:k}=R(_);return j.multiply(k)}toRawBytes(){let{x:_,y:k}=this.toAffine(),b=h5(k,Q.BYTES);return b[b.length-1]|=_&U6?128:0,b}toHex(){return f8(this.toRawBytes())}}L.BASE=new L(J.Gx,J.Gy,U6,O(J.Gx*J.Gy)),L.ZERO=new L(ZJ,U6,U6,ZJ);let{BASE:j,ZERO:T}=L,v=hw(L,D*8);function x(_){return D4(_,Y)}function y(_){return x(K9(_))}function R(_){let k=Q.BYTES;_=A4("private key",_,k);let b=A4("hashed private key",G(_),2*k),t=A(b.slice(0,k)),n=b.slice(k,2*k),N$=y(t);return{head:t,prefix:n,scalar:N$}}function d(_){let{head:k,prefix:b,scalar:t}=R(_),n=j.multiply(t),N$=n.toRawBytes();return{head:k,prefix:b,scalar:t,point:n,pointBytes:N$}}function p(_){return d(_).pointBytes}function Y$(_=Uint8Array.of(),...k){let b=z1(...k);return y(G(q(b,A4("context",_),!!X)))}function c(_,k,b={}){if(_=A4("message",_),X)_=X(_);let{prefix:t,scalar:n,pointBytes:N$}=d(k),I$=Y$(b.context,t,_),w$=j.multiply(I$).toRawBytes(),f$=Y$(b.context,w$,N$,_),H4=x(I$+f$*n);V6("signature.s",H4,ZJ,Y);let i$=z1(w$,h5(H4,Q.BYTES));return A4("result",i$,Q.BYTES*2)}let l=m7$;function V$(_,k,b,t=l){let{context:n,zip215:N$}=t,I$=Q.BYTES;if(_=A4("signature",_,2*I$),k=A4("message",k),b=A4("publicKey",b,I$),N$!==void 0)qJ("zip215",N$);if(X)k=X(k);let w$=K9(_.slice(I$,2*I$)),f$,H4,i$;try{f$=L.fromHex(b,N$),H4=L.fromHex(_.slice(0,I$),N$),i$=j.multiplyUnsafe(w$)}catch(Y1){return!1}if(!N$&&f$.isSmallOrder())return!1;let p4=Y$(n,H4.toRawBytes(),f$.toRawBytes(),k);return H4.add(f$.multiplyUnsafe(p4)).subtract(i$).clearCofactor().equals(L.ZERO)}return j._setWindowSize(8),{CURVE:J,getPublicKey:p,sign:c,verify:V$,ExtendedPoint:L,utils:{getExtendedPublicKey:d,randomPrivateKey:()=>W(Q.BYTES),precompute(_=8,k=L.BASE){return k._setWindowSize(_),k.multiply(BigInt(3)),k}}}}M9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var IF=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ou=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),cZ$=BigInt(0),i7$=BigInt(1),Nu=BigInt(2),iZ$=BigInt(3),o7$=BigInt(5),r7$=BigInt(8);function t7$($){let J=BigInt(10),Q=BigInt(20),Y=BigInt(40),X=BigInt(80),G=IF,D=$*$%G*$%G,V=u4(D,Nu,G)*D%G,K=u4(V,i7$,G)*$%G,O=u4(K,o7$,G)*K%G,N=u4(O,J,G)*O%G,w=u4(N,Q,G)*N%G,M=u4(w,Y,G)*w%G,A=u4(M,X,G)*M%G,q=u4(A,X,G)*M%G,F=u4(q,J,G)*O%G;return{pow_p_5_8:u4(F,Nu,G)*$%G,b2:D}}function a7$($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function s7$($,J){let Q=IF,Y=D4(J*J*J,Q),X=D4(Y*Y*J,Q),G=t7$($*X).pow_p_5_8,W=D4($*Y*G,Q),D=D4(J*W*W,Q),V=W,K=D4(W*Ou,Q),O=D===$,N=D===D4(-$,Q),w=D===D4(-$*Ou,Q);if(O)W=V;if(N||w)W=K;if(sh(W,Q))W=D4(-W,Q);return{isValid:O||N,value:W}}var wu=(()=>HQ(IF,void 0,!0))(),e7$=(()=>({a:wu.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:wu,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:r7$,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:uh,randomBytes:g5,adjustScalarBytes:a7$,uvRatio:s7$}))(),mw=(()=>Wu(e7$))();$V();W0();function lw(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=mw.utils.randomPrivateKey();return{publicKey:mw.getPublicKey($),privateKey:$}}function dw($){return Y9($.publicKey)}function pw($){return Y9($.privateKey)}function Mu($,J){return{publicKey:tD($),privateKey:tD(J)}}function Hu($){return Y9(OQ($))}function zu($,J,Q,Y){return`${$.toUpperCase()}
|
|
136
|
+
`}class eB{constructor($=Ih.stdin,J=Ih.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new sB,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=Ah($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var Cw={name:"@0xmonaco/mcp-server",version:"1.0.28",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.28","@0xmonaco/types":"1.0.28","@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 A7$={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||A7$[G];return{privateKey:J,clientId:Q,network:G,seiRpcUrl:W}}function I7$($){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[I7$(Q)]=typeof Y==="object"&&Y!==null?f5(Y):Y;return J}W0();$V();W0();AF();M9();N9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ZJ=BigInt(0),U6=BigInt(1),Gu=BigInt(2),u7$=BigInt(8),m7$={zip215:!0};function l7$($){let J=XV($);return g0($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function Wu($){let J=l7$($),{Fp:Q,n:Y,prehash:X,hash:G,randomBytes:W,nByteLength:D,h:V}=J,K=Gu<<BigInt(D*8)-U6,O=Q.create,N=HQ(J.n,J.nBitLength);function w(_,k){let b=Q.sqr(_),t=Q.sqr(k),n=Q.add(Q.mul(J.a,b),t),N$=Q.add(Q.ONE,Q.mul(J.d,Q.mul(b,t)));return Q.eql(n,N$)}if(!w(J.Gx,J.Gy))throw Error("bad curve params: generator point");let M=J.uvRatio||((_,k)=>{try{return{isValid:!0,value:Q.sqrt(_*Q.inv(k))}}catch(b){return{isValid:!1,value:ZJ}}}),A=J.adjustScalarBytes||((_)=>_),q=J.domain||((_,k,b)=>{if(qJ("phflag",b),k.length||b)throw Error("Contexts/pre-hash are not supported");return _});function F(_,k,b=!1){let t=b?U6:ZJ;V6("coordinate "+_,k,t,K)}function Z(_){if(!(_ instanceof L))throw Error("ExtendedPoint expected")}let E=u5((_,k)=>{let{ex:b,ey:t,ez:n}=_,N$=_.is0();if(k==null)k=N$?u7$:Q.inv(n);let I$=O(b*k),w$=O(t*k),f$=O(n*k);if(N$)return{x:ZJ,y:U6};if(f$!==U6)throw Error("invZ was invalid");return{x:I$,y:w$}}),B=u5((_)=>{let{a:k,d:b}=J;if(_.is0())throw Error("bad point: ZERO");let{ex:t,ey:n,ez:N$,et:I$}=_,w$=O(t*t),f$=O(n*n),H4=O(N$*N$),i$=O(H4*H4),p4=O(w$*k),a4=O(H4*O(p4+f$)),Y1=O(i$+O(b*O(w$*f$)));if(a4!==Y1)throw Error("bad point: equation left != right (1)");let d1=O(t*n),s4=O(N$*I$);if(d1!==s4)throw Error("bad point: equation left != right (2)");return!0});class L{constructor(_,k,b,t){F("x",_),F("y",k),F("z",b,!0),F("t",t),this.ex=_,this.ey=k,this.ez=b,this.et=t,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:k,y:b}=_||{};return F("x",k),F("y",b),new L(k,b,U6,O(k*b))}static normalizeZ(_){let k=MQ(Q,_.map((b)=>b.ez));return _.map((b,t)=>b.toAffine(k[t])).map(L.fromAffine)}static msm(_,k){return uw(L,N,_,k)}_setWindowSize(_){v.setWindowSize(this,_)}assertValidity(){B(this)}equals(_){Z(_);let{ex:k,ey:b,ez:t}=this,{ex:n,ey:N$,ez:I$}=_,w$=O(k*I$),f$=O(n*t),H4=O(b*I$),i$=O(N$*t);return w$===f$&&H4===i$}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:k,ey:b,ez:t}=this,n=O(k*k),N$=O(b*b),I$=O(Gu*O(t*t)),w$=O(_*n),f$=k+b,H4=O(O(f$*f$)-n-N$),i$=w$+N$,p4=i$-I$,a4=w$-N$,Y1=O(H4*p4),d1=O(i$*a4),s4=O(H4*a4),Z6=O(p4*i$);return new L(Y1,d1,Z6,s4)}add(_){Z(_);let{a:k,d:b}=J,{ex:t,ey:n,ez:N$,et:I$}=this,{ex:w$,ey:f$,ez:H4,et:i$}=_,p4=O(t*w$),a4=O(n*f$),Y1=O(I$*b*i$),d1=O(N$*H4),s4=O((t+n)*(w$+f$)-p4-a4),Z6=d1-Y1,p1=d1+Y1,dQ=O(a4-k*p4),T7=O(s4*Z6),XY=O(p1*dQ),fK=O(s4*dQ),q0=O(Z6*p1);return new L(T7,XY,q0,fK)}subtract(_){return this.add(_.negate())}wNAF(_){return v.wNAFCached(this,_,L.normalizeZ)}multiply(_){let k=_;V6("scalar",k,U6,Y);let{p:b,f:t}=this.wNAF(k);return L.normalizeZ([b,t])[0]}multiplyUnsafe(_,k=L.ZERO){let b=_;if(V6("scalar",b,ZJ,Y),b===ZJ)return T;if(this.is0()||b===U6)return this;return v.wNAFCachedUnsafe(this,b,L.normalizeZ,k)}isSmallOrder(){return this.multiplyUnsafe(V).is0()}isTorsionFree(){return v.unsafeLadder(this,Y).is0()}toAffine(_){return E(this,_)}clearCofactor(){let{h:_}=J;if(_===U6)return this;return this.multiplyUnsafe(_)}static fromHex(_,k=!1){let{d:b,a:t}=J,n=Q.BYTES;_=A4("pointHex",_,n),qJ("zip215",k);let N$=_.slice(),I$=_[n-1];N$[n-1]=I$&-129;let w$=K9(N$),f$=k?K:Q.ORDER;V6("pointHex.y",w$,ZJ,f$);let H4=O(w$*w$),i$=O(H4-U6),p4=O(b*H4-t),{isValid:a4,value:Y1}=M(i$,p4);if(!a4)throw Error("Point.fromHex: invalid y coordinate");let d1=(Y1&U6)===U6,s4=(I$&128)!==0;if(!k&&Y1===ZJ&&s4)throw Error("Point.fromHex: x=0 and x_0=1");if(s4!==d1)Y1=O(-Y1);return L.fromAffine({x:Y1,y:w$})}static fromPrivateKey(_){let{scalar:k}=R(_);return j.multiply(k)}toRawBytes(){let{x:_,y:k}=this.toAffine(),b=h5(k,Q.BYTES);return b[b.length-1]|=_&U6?128:0,b}toHex(){return f8(this.toRawBytes())}}L.BASE=new L(J.Gx,J.Gy,U6,O(J.Gx*J.Gy)),L.ZERO=new L(ZJ,U6,U6,ZJ);let{BASE:j,ZERO:T}=L,v=hw(L,D*8);function x(_){return D4(_,Y)}function y(_){return x(K9(_))}function R(_){let k=Q.BYTES;_=A4("private key",_,k);let b=A4("hashed private key",G(_),2*k),t=A(b.slice(0,k)),n=b.slice(k,2*k),N$=y(t);return{head:t,prefix:n,scalar:N$}}function d(_){let{head:k,prefix:b,scalar:t}=R(_),n=j.multiply(t),N$=n.toRawBytes();return{head:k,prefix:b,scalar:t,point:n,pointBytes:N$}}function p(_){return d(_).pointBytes}function Y$(_=Uint8Array.of(),...k){let b=z1(...k);return y(G(q(b,A4("context",_),!!X)))}function c(_,k,b={}){if(_=A4("message",_),X)_=X(_);let{prefix:t,scalar:n,pointBytes:N$}=d(k),I$=Y$(b.context,t,_),w$=j.multiply(I$).toRawBytes(),f$=Y$(b.context,w$,N$,_),H4=x(I$+f$*n);V6("signature.s",H4,ZJ,Y);let i$=z1(w$,h5(H4,Q.BYTES));return A4("result",i$,Q.BYTES*2)}let l=m7$;function V$(_,k,b,t=l){let{context:n,zip215:N$}=t,I$=Q.BYTES;if(_=A4("signature",_,2*I$),k=A4("message",k),b=A4("publicKey",b,I$),N$!==void 0)qJ("zip215",N$);if(X)k=X(k);let w$=K9(_.slice(I$,2*I$)),f$,H4,i$;try{f$=L.fromHex(b,N$),H4=L.fromHex(_.slice(0,I$),N$),i$=j.multiplyUnsafe(w$)}catch(Y1){return!1}if(!N$&&f$.isSmallOrder())return!1;let p4=Y$(n,H4.toRawBytes(),f$.toRawBytes(),k);return H4.add(f$.multiplyUnsafe(p4)).subtract(i$).clearCofactor().equals(L.ZERO)}return j._setWindowSize(8),{CURVE:J,getPublicKey:p,sign:c,verify:V$,ExtendedPoint:L,utils:{getExtendedPublicKey:d,randomPrivateKey:()=>W(Q.BYTES),precompute(_=8,k=L.BASE){return k._setWindowSize(_),k.multiply(BigInt(3)),k}}}}M9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var IF=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ou=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),cZ$=BigInt(0),i7$=BigInt(1),Nu=BigInt(2),iZ$=BigInt(3),o7$=BigInt(5),r7$=BigInt(8);function t7$($){let J=BigInt(10),Q=BigInt(20),Y=BigInt(40),X=BigInt(80),G=IF,D=$*$%G*$%G,V=u4(D,Nu,G)*D%G,K=u4(V,i7$,G)*$%G,O=u4(K,o7$,G)*K%G,N=u4(O,J,G)*O%G,w=u4(N,Q,G)*N%G,M=u4(w,Y,G)*w%G,A=u4(M,X,G)*M%G,q=u4(A,X,G)*M%G,F=u4(q,J,G)*O%G;return{pow_p_5_8:u4(F,Nu,G)*$%G,b2:D}}function a7$($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function s7$($,J){let Q=IF,Y=D4(J*J*J,Q),X=D4(Y*Y*J,Q),G=t7$($*X).pow_p_5_8,W=D4($*Y*G,Q),D=D4(J*W*W,Q),V=W,K=D4(W*Ou,Q),O=D===$,N=D===D4(-$,Q),w=D===D4(-$*Ou,Q);if(O)W=V;if(N||w)W=K;if(sh(W,Q))W=D4(-W,Q);return{isValid:O||N,value:W}}var wu=(()=>HQ(IF,void 0,!0))(),e7$=(()=>({a:wu.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:wu,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:r7$,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:uh,randomBytes:g5,adjustScalarBytes:a7$,uvRatio:s7$}))(),mw=(()=>Wu(e7$))();$V();W0();function lw(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=mw.utils.randomPrivateKey();return{publicKey:mw.getPublicKey($),privateKey:$}}function dw($){return Y9($.publicKey)}function pw($){return Y9($.privateKey)}function Mu($,J){return{publicKey:tD($),privateKey:tD(J)}}function Hu($){return Y9(OQ($))}function zu($,J,Q,Y){return`${$.toUpperCase()}
|
|
137
137
|
${J}
|
|
138
138
|
${Q}
|
|
139
139
|
${Y}`}function Au($,J){return`WS-AUTH
|
|
@@ -143,7 +143,7 @@ ${J}`}function nw($,J){return Y9(mw.sign(b5(J),$))}var GV=[0.0001,0.001,0.01,0.1
|
|
|
143
143
|
`;D0();p$();function gn($){let J=(()=>{if(typeof $==="string")return d5($);if(typeof $.raw==="string")return $.raw;return N4($.raw)})(),Q=d5(`${bn}${G4(J)}`);return y1([Q,J])}function jH($,J){return C4(gn($),J)}async function yn($,{address:J,message:Q,factory:Y,factoryData:X,signature:G,...W}){let D=jH(Q);return D$($,GX,"verifyHash")({address:J,factory:Y,factoryData:X,hash:D,signature:G,...W})}BQ();p$();d0();J1();A9();Q4();class MS extends u{constructor({domain:$}){super(`Invalid domain "${V4($)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class HS extends u{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 zS extends u{constructor({type:$}){super(`Struct type "${$}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}ZQ();D0();p$();Qj();function hn($){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(OM);if(w&&(typeof N==="number"||typeof N==="bigint")){let[q,F,Z]=w;O$(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(rm);if(M){let[q,F]=M;if(F&&G4(N)!==Number.parseInt(F,10))throw new lF({expectedSize:Number.parseInt(F,10),givenSize:G4(N)})}let A=X[O];if(A)jK$(O),G(A,N)}};if(X.EIP712Domain&&J){if(typeof J!=="object")throw new MS({domain:J});G(X.EIP712Domain,J)}if(Y!=="EIP712Domain")if(X[Y])G(X[Y],Q);else throw new HS({primaryType:Y,types:X})}function un({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 jK$($){if($==="address"||$==="bool"||$==="string"||$.startsWith("bytes")||$.startsWith("uint")||$.startsWith("int"))throw new zS({type:$})}function mn($){let{domain:J={},message:Q,primaryType:Y}=$,X={EIP712Domain:un({domain:J}),...$.types};hn({domain:J,message:Q,primaryType:Y,types:X});let G=["0x1901"];if(J)G.push(EK$({domain:J,types:X}));if(Y!=="EIP712Domain")G.push(ln({data:Q,primaryType:Y,types:X}));return C4(y1(G))}function EK$({domain:$,types:J}){return ln({data:$,primaryType:"EIP712Domain",types:J})}function ln({data:$,primaryType:J,types:Q}){let Y=dn({data:$,primaryType:J,types:Q});return C4(Y)}function dn({data:$,primaryType:J,types:Q}){let Y=[{type:"bytes32"}],X=[SK$({primaryType:J,types:Q})];for(let G of Q[J]){let[W,D]=nn({types:Q,name:G.name,type:G.type,value:$[G.name]});Y.push(W),X.push(D)}return w6(Y,X)}function SK$({primaryType:$,types:J}){let Q=o1(_K$({primaryType:$,types:J}));return C4(Q)}function _K$({primaryType:$,types:J}){let Q="",Y=pn({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 pn({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])pn({primaryType:G.type,types:J},Q);return Q}function nn({types:$,name:J,type:Q,value:Y}){if($[Q]!==void 0)return[{type:"bytes32"},C4(dn({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)=>nn({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 cn($,J){let{address:Q,factory:Y,factoryData:X,signature:G,message:W,primaryType:D,types:V,domain:K,...O}=J,N=mn({message:W,primaryType:D,types:V,domain:K});return D$($,GX,"verifyHash")({address:Q,factory:Y,factoryData:X,hash:N,signature:G,...O})}TQ();var AS=new Map,on=new Map,TK$=0;function y6($,J,Q){let Y=++TK$,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=on.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")on.set($,K);return W}async function YK($){return new Promise((J)=>setTimeout(J,$))}function GK($,{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 YK(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 YK(V);let K=async()=>{if(!X)return;await $({unpoll:G}),await YK(Y),K()};K()})(),G}function EH($,{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=V4(["watchBlockNumber",$.uid,J,Q,W]);return y6(N,{onBlockNumber:Y,onError:X},(w)=>PJ(async()=>{try{let M=await D$($,CJ,"getBlockNumber")({cacheTime:0});if(V!==void 0){if(M===V)return;if(M-V>1&&Q)for(let A=V+1n;A<M;A++)w.onBlockNumber(A,V),V=A}if(V===void 0||M>V)w.onBlockNumber(M,V),V=M}catch(M){w.onError?.(M)}},{emitOnBegin:J,interval:W}))})():(()=>{let N=V4(["watchBlockNumber",$.uid,J,Q]);return y6(N,{onBlockNumber:Y,onError:X},(w)=>{let M=!0,A=()=>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(A=F,!M)A()}catch(q){X?.(q)}})(),()=>A()})})()}async function rn($,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=V4(["waitForTransactionReceipt",$.uid,X]),O=(()=>{if(J.pollingInterval)return J.pollingInterval;if($.chain?.experimental_preconfirmationTime)return $.chain.experimental_preconfirmationTime;return $.pollingInterval})(),N,w,M,A=!1,q,F,{promise:Z,resolve:E,reject:B}=mM(),L=V?setTimeout(()=>{F?.(),q?.(),B(new yj({hash:X}))},V):void 0;return q=y6(K,{onReplaced:G,resolve:E,reject:B},async(j)=>{if(M=await D$($,dG,"getTransactionReceipt")({hash:X}).catch(()=>{return}),M&&Y<=1){clearTimeout(L),j.resolve(M),q?.();return}F=D$($,EH,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:O,async onBlockNumber(T){let v=(y)=>{clearTimeout(L),F?.(),y(),q?.()},x=T;if(A)return;try{if(M){if(Y>1&&(!M.blockNumber||x-M.blockNumber+1n<Y))return;v(()=>j.resolve(M));return}if(Q&&!N)A=!0,await GK(async()=>{if(N=await D$($,lG,"getTransaction")({hash:X}),N.blockNumber)x=N.blockNumber},{delay:D,retryCount:W}),A=!1;if(M=await D$($,dG,"getTransactionReceipt")({hash:X}),Y>1&&(!M.blockNumber||x-M.blockNumber+1n<Y))return;v(()=>j.resolve(M))}catch(y){if(y instanceof FV||y instanceof jV){if(!N){A=!1;return}try{w=N,A=!0;let R=await GK(()=>D$($,L1,"getBlock")({blockNumber:x,includeTransactions:!0}),{delay:D,retryCount:W,shouldRetry:({error:Y$})=>Y$ instanceof rV});A=!1;let d=R.transactions.find(({from:Y$,nonce:c})=>Y$===w.from&&c===w.nonce);if(!d)return;if(M=await D$($,dG,"getTransactionReceipt")({hash:d.hash}),Y>1&&(!M.blockNumber||x-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";v(()=>{j.onReplaced?.({reason:p,replacedTransaction:w,transaction:d,transactionReceipt:M}),j.resolve(M)})}catch(R){v(()=>j.reject(R))}}else v(()=>j.reject(y))}}})}),Z}function tn($,{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 A=V4(["watchBlocks",$.uid,J,Q,Y,O,V]);return y6(A,{onBlock:X,onError:G},(q)=>PJ(async()=>{try{let F=await D$($,L1,"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 D$($,L1,"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 A=!0,q=!0,F=()=>A=!1;return(async()=>{try{if(Y)D$($,L1,"getBlock")({blockTag:J,includeTransactions:O}).then((B)=>{if(!A)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(!A)return;let L=await D$($,L1,"getBlock")({blockNumber:B.result?.number,includeTransactions:O}).catch(()=>{});if(!A)return;X(L,N),q=!1,N=L},onError(B){G?.(B)}});if(F=E,!A)F()}catch(Z){G?.(Z)}})(),()=>F()})()}J1();RV();function an($,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=V4(["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 D$($,iM,"createContractEventFilter")({abi:Q,address:Y,args:X,eventName:W,strict:F,fromBlock:D})}catch{}j=!0;return}try{let v;if(L)v=await D$($,JX,"getFilterChanges")({filter:L});else{let x=await D$($,CJ,"getBlockNumber")({});if(B&&B<x)v=await D$($,VH,"getContractEvents")({abi:Q,address:Y,args:X,eventName:W,fromBlock:B+1n,toBlock:x,strict:F});else v=[];B=x}if(v.length===0)return;if(G)E.onLogs(v);else for(let x of v)E.onLogs([x])}catch(v){if(L&&v instanceof N0)j=!1;E.onError?.(v)}},{emitOnBegin:!0,interval:N});return async()=>{if(L)await D$($,XX,"uninstallFilter")({filter:L});T()}})})():(()=>{let F=w??!1,Z=V4(["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 x=$.transport.transports.find((y)=>y.config.type==="webSocket"||y.config.type==="ipc");if(!x)return $.transport;return x.value}return $.transport})(),T=W?RJ({abi:Q,eventName:W,args:X}):[],{unsubscribe:v}=await j.subscribe({params:["logs",{address:Y,topics:T}],onData(x){if(!E)return;let y=x.result;try{let{eventName:R,args:d}=h9({abi:Q,data:y.data,topics:y.topics,strict:w}),p=Z1(y,{args:d,eventName:R});L.onLogs([p])}catch(R){let d,p;if(R instanceof h8||R instanceof z9){if(w)return;d=R.abiItem.name,p=R.abiItem.inputs?.some((c)=>!(("name"in c)&&c.name))}let Y$=Z1(y,{args:p?[]:{},eventName:d});L.onLogs([Y$])}},onError(x){L.onError?.(x)}});if(B=v,!E)B()}catch(j){V?.(j)}})(),()=>B()})})()}J1();RV();function sn($,{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=V4(["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 D$($,oM,"createEventFilter")({address:J,args:Q,event:X,events:G,strict:M,fromBlock:W})}catch{}L=!0;return}try{let T;if(B)T=await D$($,JX,"getFilterChanges")({filter:B});else{let v=await D$($,CJ,"getBlockNumber")({});if(E&&E!==v)T=await D$($,mG,"getLogs")({address:J,args:Q,event:X,events:G,fromBlock:E+1n,toBlock:v});else T=[];E=v}if(T.length===0)return;if(Y)Z.onLogs(T);else for(let v of T)Z.onLogs([v])}catch(T){if(B&&T instanceof N0)L=!1;Z.onError?.(T)}},{emitOnBegin:!0,interval:O});return async()=>{if(B)await D$($,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((v)=>v.config.type==="webSocket"||v.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((v)=>RJ({abi:[v],eventName:v.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 v=T.result;try{let{eventName:x,args:y}=h9({abi:B??[],data:v.data,topics:v.topics,strict:M}),R=Z1(v,{args:y,eventName:x});V([R])}catch(x){let y,R;if(x instanceof h8||x instanceof z9){if(N)return;y=x.abiItem.name,R=x.abiItem.inputs?.some((p)=>!(("name"in p)&&p.name))}let d=Z1(v,{args:R?[]:{},eventName:y});V([d])}},onError(T){D?.(T)}});if(Z=j,!F)Z()}catch(E){D?.(E)}})(),()=>Z()})()}function en($,{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=V4(["watchPendingTransactions",$.uid,J,G]);return y6(K,{onTransactions:Y,onError:Q},(O)=>{let N,w=PJ(async()=>{try{if(!N)try{N=await D$($,rM,"createPendingTransactionFilter")({});return}catch(A){throw w(),A}let M=await D$($,JX,"getFilterChanges")({filter:N});if(M.length===0)return;if(J)O.onTransactions(M);else for(let A of M)O.onTransactions([A])}catch(M){O.onError?.(M)}},{emitOnBegin:!0,interval:G});return async()=>{if(N)await D$($,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 $c($){let{scheme:J,statement:Q,...Y}=$.match(RK$)?.groups??{},{chainId:X,expirationTime:G,issuedAt:W,notBefore:D,requestId:V,...K}=$.match(CK$)?.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 RK$=/^(?:(?<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)?/,CK$=/(?: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>.+))?/;ZQ();xG();function Jc($){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 Qc($,J){let{address:Q,domain:Y,message:X,nonce:G,scheme:W,signature:D,time:V=new Date,...K}=J,O=$c(X);if(!O.address)return!1;if(!Jc({address:Q,domain:Y,message:O,nonce:G,scheme:W,time:V}))return!1;let w=jH(X);return GX($,{address:O.address,hash:w,signature:D,...K})}async function Xc($,{serializedTransaction:J}){return $.request({method:"eth_sendRawTransaction",params:[J]},{retryCount:0})}TQ();async function Yc($,{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||KH)(X);if(W.status==="reverted"&&Q)throw new gj({receipt:W});return W}function Gc($){return{call:(J)=>H0($,J),createAccessList:(J)=>cM($,J),createBlockFilter:()=>pd($),createContractEventFilter:(J)=>iM($,J),createEventFilter:(J)=>oM($,J),createPendingTransactionFilter:()=>rM($),estimateContractGas:(J)=>_p($,J),estimateGas:(J)=>hG($,J),getBalance:(J)=>Tp($,J),getBlobBaseFee:()=>Rp($),getBlock:(J)=>L1($,J),getBlockNumber:(J)=>CJ($,J),getBlockTransactionCount:(J)=>vp($,J),getBytecode:(J)=>y9($,J),getChainId:()=>yG($),getCode:(J)=>y9($,J),getContractEvents:(J)=>VH($,J),getDelegation:(J)=>xp($,J),getEip712Domain:(J)=>fp($,J),getEnsAddress:(J)=>fd($,J),getEnsAvatar:(J)=>md($,J),getEnsName:(J)=>ld($,J),getEnsResolver:(J)=>dd($,J),getEnsText:(J)=>nM($,J),getFeeHistory:(J)=>gp($,J),estimateFeesPerGas:(J)=>Hp($,J),getFilterChanges:(J)=>JX($,J),getFilterLogs:(J)=>yp($,J),getGasPrice:()=>gG($),getLogs:(J)=>mG($,J),getProof:(J)=>up($,J),estimateMaxPriorityFeePerGas:(J)=>Mp($,J),fillTransaction:(J)=>WH($,J),getStorageAt:(J)=>mp($,J),getTransaction:(J)=>lG($,J),getTransactionConfirmations:(J)=>lp($,J),getTransactionCount:(J)=>QH($,J),getTransactionReceipt:(J)=>dG($,J),multicall:(J)=>dp($,J),prepareTransactionRequest:(J)=>DH($,J),readContract:(J)=>W1($,J),sendRawTransaction:(J)=>Xc($,J),sendRawTransactionSync:(J)=>Yc($,J),simulate:(J)=>tV($,J),simulateBlocks:(J)=>tV($,J),simulateCalls:(J)=>An($,J),simulateContract:(J)=>In($,J),verifyHash:(J)=>GX($,J),verifyMessage:(J)=>yn($,J),verifySiweMessage:(J)=>Qc($,J),verifyTypedData:(J)=>cn($,J),uninstallFilter:(J)=>XX($,J),waitForTransactionReceipt:(J)=>rn($,J),watchBlocks:(J)=>tn($,J),watchBlockNumber:(J)=>EH($,J),watchContractEvent:(J)=>an($,J),watchEvent:(J)=>sn($,J),watchPendingTransactions:(J)=>en($,J)}}function IS($){let{key:J="public",name:Q="Public Client"}=$;return vm({...$,key:J,name:Q,type:"publicClient"}).extend(Gc)}_9();Q4();class qS extends u{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}UE();_9();function Wc($,{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 PK$(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var LS=PK$();function Dc($,J={}){let{url:Q,headers:Y}=vK$($);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 A=await Wc(async({signal:F})=>{let Z={...O,body:Array.isArray(G)?V4(G.map((j)=>({jsonrpc:"2.0",id:j.id??LS.take(),...j}))):V4({jsonrpc:"2.0",id:G.id??LS.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 PM({body:G,url:Q}),timeout:K,signal:!0});if(V)await V(A);let q;if(A.headers.get("Content-Type")?.startsWith("application/json"))q=await A.json();else{q=await A.text();try{q=JSON.parse(q||"{}")}catch(F){if(A.ok)throw F;q={error:q}}}if(!A.ok){if(typeof q.error?.code==="number"&&typeof q.error?.message==="string")return q;throw new c0({body:G,details:V4(q.error)||A.statusText,headers:A.headers,status:A.status,url:Q})}return q}catch(A){if(A instanceof c0)throw A;if(A instanceof PM)throw A;throw new c0({body:G,cause:A,url:Q})}}}}function vK$($){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:$}}}Q4();_9();RV();zV();var SH=new LQ(8192);function Vc($,{enabled:J=!0,id:Q}){if(!J||!Q)return $();if(SH.get(Q))return SH.get(Q);let Y=$().finally(()=>SH.delete(Q));return SH.set(Q,Y),Y}function Kc($,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?xK$(`${V}.${V4(Q)}`):void 0;return Vc(()=>GK(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 zG.code:throw new zG(w);case AG.code:throw new AG(w);case IG.code:throw new IG(w);case qG.code:throw new qG(w);case LG.code:throw new LG(w);case ZG.code:throw new ZG(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 u)throw N;throw new nj(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})=>kK$(N)}),{enabled:X,id:O})}}function kK$($){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 xK$($,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 Uc({key:$,methods:J,name:Q,request:Y,retryCount:X=3,retryDelay:G=150,timeout:W,type:D},V){let K=tw();return{config:{key:$,methods:J,name:Q,request:Y,retryCount:X,retryDelay:G,timeout:W,type:D},request:Kc(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:A})=>{let{batchSize:q=1000,wait:F=0}=typeof Q==="object"?Q:{},Z=J.retryCount??M,E=A??J.timeout??1e4,B=$||w?.rpcUrls.default.http[0];if(!B)throw new qS;let L=Dc(B,{fetchFn:Y,fetchOptions:X,onRequest:V,onResponse:K,timeout:E});return Uc({key:G,methods:W,name:D,async request({method:j,params:T}){let v={method:j,params:T},{schedule:x}=lM({id:B,wait:F,shouldSplitBatch(p){return p.length>q},fn:(p)=>L.request({body:p}),sort:(p,Y$)=>p.id-Y$.id}),y=async(p)=>Q?x(p):[await L.request({body:p})],[{error:R,result:d}]=await y(v);if(N)return{error:R,result:d};if(R)throw new S9({body:v,error:R,url:B});return d},retryCount:Z,retryDelay:O,timeout:E,type:"http"},{fetchOptions:X,url:B})}}BJ();function _H($){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 BS=_H({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 FS=_H({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 TH=e1(iw(),1);var fK$="@0xmonaco/core";class t${apiUrl;sessionKeypair;serverKey;retryOptions;constructor($,J){this.apiUrl=$,this.retryOptions={maxRetries:J?.maxRetries??3,baseDelayMs:J?.baseDelayMs??1000}}setSessionKeypair($){this.sessionKeypair=$?Mu($.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,G={"User-Agent":fK$,...Q.headers};try{X=await fetch($,{...Q,headers:G})}catch(K){throw new U1(`Network request failed for ${J}`,{endpoint:$,cause:K instanceof Error?K:Error(String(K)),requestBody:Y})}let W,D=X.headers?.get("content-type")||"unknown",V=X.clone?X.clone():X;try{W=await X.json()}catch(K){let O;try{O=await V.text()}catch{O="[Unable to read response body]"}if(!X.ok){let N=`API request failed: ${X.status}. Response is not JSON (Content-Type: ${D})`,{requestId:w,retryAfter:M}=this.extractResponseMetadata(X.headers);throw new U1(N,{endpoint:$,statusCode:X.status,responseBody:{rawResponse:O.substring(0,500),contentType:D,parseError:K instanceof Error?K.message:String(K)},cause:K instanceof Error?K:void 0,requestBody:Y,requestId:w,retryAfter:M})}if(O.trim()==="")return;throw new U1(`Expected JSON response but received ${D}`,{endpoint:$,statusCode:X.status,responseBody:{rawResponse:O.substring(0,500),contentType:D},cause:K instanceof Error?K:void 0,requestBody:Y})}if(!X.ok){let K=W!==null&&typeof W==="object"?W:void 0,O=(typeof K?.message==="string"?K.message:void 0)||(typeof K?.error==="string"?K.error:void 0)||`API request failed: ${X.status}`,{requestId:N,retryAfter:w}=this.extractResponseMetadata(X.headers);throw new U1(O,{endpoint:$,statusCode:X.status,responseBody:W,requestBody:Y,requestId:N,retryAfter:w})}return W}async makeAuthenticatedRequest($,J={}){if(!this.sessionKeypair)throw new U1("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${$}`,statusCode:TH.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:TH.StatusCodes.UNAUTHORIZED});let Q=(J.method??"GET").toUpperCase(),Y=Date.now(),X=typeof J.body==="string"?b5(J.body):new Uint8Array(0),G=Hu(X),W=zu(Q,$,Y,G),D=nw(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:TH.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 e$($){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 W$={orders:{create:()=>"/api/v1/orders",list:($)=>d4("/api/v1/orders",$),get:($)=>`/api/v1/orders/${e$($)}`,replace:($)=>`/api/v1/orders/${e$($)}`,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/${e$($)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:($)=>d4("/api/v1/orders/conditional",$),cancelConditional:($)=>`/api/v1/orders/conditional/${e$($)}`,getConditional:($)=>`/api/v1/orders/conditional/${e$($)}`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:($)=>`/api/v1/delegated-agents/${e$($)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:($)=>`/api/v1/withdrawals/${e$(String($))}`,list:($)=>d4("/api/v1/withdrawals",$)},market:{listTradingPairs:($)=>d4("/api/v1/market/pairs",$),getTradingPair:($)=>`/api/v1/market/pairs/${e$($)}`,getCandles:($,J,Q)=>d4(`/api/v1/market/pairs/charts/candlestick/${e$($)}/${e$(J)}`,Q),getMarketMetadata:($)=>`/api/v1/market/pairs/${e$($)}/metadata`,getPerpMarketConfig:($)=>`/api/v1/market/pairs/${e$($)}/perp/config`,getPerpMarketSummary:($)=>`/api/v1/market/pairs/${e$($)}/perp/summary`,getMarkPrice:($)=>`/api/v1/market/pairs/${e$($)}/mark-price`,getIndexPrice:($)=>`/api/v1/market/pairs/${e$($)}/index-price`,getFundingState:($)=>`/api/v1/market/pairs/${e$($)}/funding`,listFundingHistory:($,J)=>d4(`/api/v1/market/pairs/${e$($)}/funding/history`,J),getOpenInterest:($)=>`/api/v1/market/pairs/${e$($)}/open-interest`,getScreener:($)=>d4("/api/v1/market/screener",$),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:($,J)=>d4(`/api/v1/orderbook/${e$($)}`,J)},trades:{publicByPair:($,J)=>d4(`/api/v1/trades/${e$($)}`,J),byId:($)=>`/api/v1/trades/by-id/${e$($)}`,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/${e$($)}/limits`,limit:($,J)=>`/api/v1/accounts/sub-accounts/${e$($)}/limits/${e$(J)}`},faucet:{mint:()=>"/api/v1/faucet/mint",info:()=>"/api/v1/faucet/info"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:($)=>d4("/api/v1/positions",$),get:($)=>`/api/v1/positions/${e$($)}`,close:($)=>`/api/v1/positions/${e$($)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:($)=>`/api/v1/positions/${e$($)}/risk`,addMargin:($)=>`/api/v1/positions/${e$($)}/margin/add`,reduceMargin:($)=>`/api/v1/positions/${e$($)}/margin/reduce`,attachTpSl:($)=>`/api/v1/positions/${e$($)}/tp-sl`,history:($)=>d4("/api/v1/positions/history",$),pnlHistory:($,J)=>d4(`/api/v1/positions/${e$($)}/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/${e$($)}`,J),availableCollateral:($)=>d4("/api/v1/margin/collateral/available",$),transferIn:($)=>`/api/v1/margin/accounts/${e$($)}/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/${e$($)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:($,J)=>d4(`/api/v1/margin/accounts/${e$($)}/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/${e$($)}/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 RH extends t${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(W$.applications.orders($))}async listApplicationUsers($){return await this.makeBackendRequest(W$.applications.users($))}async listApplicationMovements($){return await this.makeBackendRequest(W$.applications.movements($))}async listApplicationBalances($){return await this.makeBackendRequest(W$.applications.balances($))}async getApplicationStats($){return await this.makeBackendRequest(W$.applications.stats($))}}class jS extends t${async upsertDelegatedAgent($){return this.makeAuthenticatedRequest(W$.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(W$.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(W$.delegatedAgents.owners())}async revokeDelegatedAgent($){return this.makeAuthenticatedRequest(W$.delegatedAgents.byId($),{method:"DELETE"})}async createDelegatedSession($){return this.makeAuthenticatedRequest(W$.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:$.ownerUserId,sessionPublicKey:$.sessionPublicKey})})}}class CH extends t${async mint($){return await this.makeAuthenticatedRequest(W$.faucet.mint(),{method:"POST",body:JSON.stringify({turnstileToken:$.turnstileToken})})}async getInfo(){return await this.makeAuthenticatedRequest(W$.faucet.info(),{method:"GET"})}}var ES=z.object({tradingPairId:z.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:z.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:z.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:z.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:z.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:z.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:z.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),bK$=z.object({applicationName:z.string().nullable().optional(),applicationTakerFee:z.string(),applicationTakerFeeBps:z.number(),buyOrderLockAmount:z.string().nullable().optional(),makerTotalReceipt:z.string(),monacoMakerRebate:z.string(),monacoMakerRebateBps:z.number(),monacoMakerRebateBpsExact:z.string(),monacoTakerFee:z.string(),monacoTakerFeeBps:z.number(),monacoTakerFeeBpsExact:z.string(),notional:z.string(),takerTotalPayment:z.string(),totalTakerFees:z.string(),maxQuantity:z.string().nullable(),maxQuantityRaw:z.string().nullable(),slippageToleranceBps:z.number().nullable()}),SS=z.object({tradingPairId:z.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),Oc=z.object({tierLevel:z.number().int(),minVolumeThreshold:z.string(),makerFeeBps:z.string(),takerFeeBps:z.string()}),gK$=z.object({currentTierLevel:z.number().int(),weightedVolume14d:z.string(),spotVolume14d:z.string(),perpVolume14d:z.string(),volumeToNextTier:z.string().nullable().optional(),nextTierLevel:z.number().int().nullable().optional(),feeSchedule:z.array(Oc)});var Nc=z.object({token:z.string(),available:z.string()}),yK$=z.object({balances:z.array(Nc)}),hK$=z.object({code:z.string(),createdAt:z.string()}),uK$=z.object({code:z.string()}),_S=z.object({token:z.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:z.string().trim().min(1,"amount is required").refine(($)=>/^\d+$/.test($)&&BigInt($)>0n,"amount must be a positive integer string")}),mK$=z.object({rewardsBalance:z.string(),tradingBalance:z.string()});var TS=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];class wc 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 L$($,J){let Q=$.safeParse(J);if(!Q.success)throw new wc(Q.error);return Q.data}var WK=z.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),vH=z.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),RS=z.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),DK=z.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),Mc=z.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),CS=z.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),cG=z.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),w4=z.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"}),_$=z.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),VK=z.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),Hc=z.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),KK=z.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),PH=z.object({triggerPrice:w4,orderType:cG,limitPrice:w4.optional(),timeInForce:CS.optional(),slippageToleranceBps:KK.optional(),expiresAt:VK.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"]}),zc=($)=>$?.takeProfit!==void 0||$?.stopLoss!==void 0,PS=($,J)=>J===void 0||J!=="NONE"&&($==="BUY"&&J==="LONG"||$==="SELL"&&J==="SHORT"),Ac=z.object({tradingPairId:_$,side:WK,quantity:w4,price:w4,options:z.object({tradingMode:vH.optional(),useMasterBalance:z.boolean().optional(),expirationDate:VK.optional(),timeInForce:Mc.optional(),marginAccountId:_$.optional(),marginMode:RS.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:DK.optional(),leverage:w4.optional(),reduceOnly:z.boolean().optional(),takeProfit:PH.optional(),stopLoss:PH.optional()}).optional()}).refine(($)=>PS($.side,$.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.reduceOnly===!0||$.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine(($)=>!zc($.options),{message:"Entry-attached TP/SL are no longer supported; create position TP/SL after the position opens",path:["options"]}).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"]}),Ic=z.object({tradingPairId:_$,side:WK,quantity:w4,options:z.object({tradingMode:vH.optional(),slippageTolerance:Hc,marginAccountId:_$.optional(),marginMode:RS.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:DK.optional(),leverage:w4.optional(),reduceOnly:z.boolean().optional(),takeProfit:PH.optional(),stopLoss:PH.optional()}).optional()}).refine(($)=>PS($.side,$.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.reduceOnly===!0||$.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine(($)=>!zc($.options),{message:"Entry-attached TP/SL are no longer supported; create position TP/SL after the position opens",path:["options"]}).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"]}),qc=z.object({orderId:_$}),Lc=z.object({orderId:_$,newOrder:z.object({price:w4.optional(),quantity:w4.optional(),useMasterBalance:z.boolean().optional()})}),Zc=z.object({status:z.enum(TS).optional(),tradingPairId:_$.optional(),tradingMode:vH.optional(),marginAccountId:_$.optional(),page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),lB4=z.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),dB4=z.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),lK$=z.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),pB4=z.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),vS=z.object({conditionalOrderId:_$}),Bc=z.object({marginAccountId:_$.optional(),tradingPairId:_$.optional(),state:lK$.optional(),page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),dK$=z.object({tradingPairId:_$,orderType:cG,side:WK,price:w4.optional(),quantity:w4,tradingMode:vH.optional(),slippageTolerance:Hc,useMasterBalance:z.boolean().optional(),expirationDate:VK.optional(),timeInForce:Mc.optional(),marginAccountId:_$.optional(),marginMode:RS.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:DK.optional(),leverage:w4.optional(),reduceOnly:z.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(($)=>PS($.side,$.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine(($)=>$.tradingMode!=="MARGIN"||$.reduceOnly===!0||$.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),Fc=z.object({orders:z.array(dK$).min(1,"At least one order is required")}),pK$=z.object({orderId:_$,price:w4.optional(),quantity:w4.optional(),useMasterBalance:z.boolean().optional()}).refine(($)=>$.price!==void 0||$.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),jc=z.object({orders:z.array(pK$).min(1,"At least one order is required")});var kS=z.object({page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Ec=kS.extend({state:z.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:_$.optional()}),Sc=z.object({marginAccountId:_$,tradingPairId:_$.optional()}),_c=z.object({tradingPairId:_$.optional()}).optional(),Tc=z.object({asset:z.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),nK$=z.object({asset:z.string().trim().min(1,"Asset cannot be empty"),amount:w4,tradingPairId:_$.optional(),strategyKey:z.string().trim().min(1,"Strategy key cannot be empty").optional()}),kH=z.object({asset:z.string().trim().min(1,"Asset cannot be empty"),amount:w4}),cK$=z.object({tradingPairId:_$,strategyKey:z.string().trim().min(1,"Strategy key cannot be empty").optional()}),iK$=z.array(_$).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),Rc=cK$.extend({marginMode:z.literal("ISOLATED").optional(),selectedTradingPairIds:z.never().optional()}),Cc=z.object({marginMode:z.literal("CROSS"),selectedTradingPairIds:iK$,strategyKey:z.never().optional()}),oK$=Cc.extend({tradingPairId:z.never().optional()}),xS=z.object({marginAccountId:_$,request:nK$}),Pc=z.object({request:kH}),vc=z.object({request:z.union([kH.merge(Rc).strict(),kH.merge(oK$).strict()])}),kc=z.object({request:kH}),xc=kS.extend({marginAccountId:_$,movementType:z.string().trim().min(1,"Movement type cannot be empty").optional()}),fc=kS.extend({movementType:z.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),fS=z.object({tradingPairId:_$,side:WK,positionSide:DK.optional(),orderType:cG,price:w4.optional(),quantity:w4,leverage:w4.optional(),reduceOnly:z.boolean().optional()}),bS=($,J)=>{if($.positionSide!==void 0){let Q=$.side==="BUY"?"LONG":"SHORT";if($.positionSide!==Q)J.addIssue({code:z.ZodIssueCode.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if($.reduceOnly!==!0&&$.leverage===void 0)J.addIssue({code:z.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},bc=fS.strict().superRefine(bS),rK$=fS.merge(Rc).strict().superRefine(bS),tK$=fS.merge(Cc).strict().superRefine(bS).refine(($)=>$.selectedTradingPairIds.includes($.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),aK$=z.union([rK$,tK$]),gc=z.object({marginAccountId:_$,request:bc}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),yc=z.object({request:bc}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),hc=z.object({request:aK$}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var uc=z.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"'}),sK$=31536000000,eK$=946684800000,xH=z.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(eK$,{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()+sK$,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),aB4=z.object({tradingPairId:_$,interval:uc,startTime:xH,endTime:xH}).refine(($)=>$.startTime<$.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),sB4=z.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")'}),$U$=z.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),mc=z.object({tradingPairId:_$,interval:uc,startTime:xH.optional(),endTime:xH.optional(),limit:$U$}).refine(($)=>{if($.startTime!==void 0&&$.endTime!==void 0)return $.startTime<$.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var eB4=z.object({tradingPairId:_$}),$F4=z.object({query:z.string().min(1,"Search query cannot be empty").optional(),pageSize:z.number().int().min(1).max(100).optional(),page:z.number().int().min(1).optional()}),vJ=z.object({tradingPairId:_$});var dc=z.object({page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),JU$=z.enum(["OPEN","CLOSED","LIQUIDATING"],{message:'Position status must be "OPEN", "CLOSED", or "LIQUIDATING"'}),QU$=z.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),n9=z.object({positionId:_$}),pc=dc.extend({marginAccountId:_$.optional(),tradingPairId:_$.optional(),status:JU$.optional()}),nc=n9,cc=n9.extend({request:z.object({closeType:QU$,limitPrice:w4.optional(),slippageToleranceBps:KK.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"]}),ic=z.object({tradingPairId:_$.optional(),slippageToleranceBps:KK.optional()}),oc=n9,rc=n9.extend({request:z.object({amount:w4,asset:z.string().trim().min(1,"Asset cannot be empty")})}),tc=n9.extend({request:z.object({amount:w4})}),lc=z.object({triggerPrice:w4,orderType:cG,limitPrice:w4.optional(),quantity:w4.optional(),closePosition:z.boolean().optional(),timeInForce:CS.optional(),slippageToleranceBps:KK.optional(),expiresAt:VK.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"]}).refine(($)=>$.closePosition!==!0||$.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine(($)=>$.quantity!==void 0||$.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),ac=n9.extend({request:z.object({takeProfit:lc.optional(),stopLoss:lc.optional(),oco:z.boolean().optional()}).refine(($)=>$.takeProfit!==void 0||$.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine(($)=>$.oco!==!0||$.takeProfit!==void 0&&$.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),sc=dc.extend({positionId:_$.optional(),marginAccountId:_$.optional(),tradingPairId:_$.optional(),reductionOnly:z.boolean().optional()}),XU$=z.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),ec=n9.extend({params:z.object({interval:XU$,startTime:z.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:z.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 YU$=z.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),GU$=z.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),$i=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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:YU$.optional(),transactionType:GU$.optional(),assetId:_$.optional()}),Ji=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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()}),Qi=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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 UF4=z.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),gS=z.union([z.string().regex(/^\d+$/,"Must be a positive integer string").refine(($)=>BigInt($)>0n,{message:"Amount must be greater than 0"}),z.bigint().refine(($)=>$>0n,{message:"Amount must be greater than 0"})]),Xi=z.object({assetId:_$,amount:gS,autoWait:z.boolean().optional()}),Yi=z.object({assetId:_$,amount:gS,autoWait:z.boolean().optional(),target:z.enum(["spot","margin"]).optional()}),Gi=z.object({assetId:_$,amount:gS,destination:z.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:z.boolean().optional(),source:z.enum(["spot","margin"]).optional()}),OF4=z.object({assetId:_$});class fH extends t${async simulateFees($){let J=L$(ES,$),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=L$(SS,$),Q=new URLSearchParams;Q.append("tradingPairId",J.tradingPairId);let Y=`/api/v1/fees/tier?${Q.toString()}`;return await this.makeAuthenticatedRequest(Y,{method:"GET"})}}class bH extends t${async listMarginAccounts($){if($)L$(Ec,$);return await this.makeAuthenticatedRequest(W$.marginAccounts.list($?{page:$.page,pageSize:$.pageSize,state:$.state,tradingPairId:$.tradingPairId}:void 0))}async getMarginAccountSummary($,J){return L$(Sc,{marginAccountId:$,...J}),await this.makeAuthenticatedRequest(W$.marginAccounts.summary($,{tradingPairId:J?.tradingPairId}))}async getParentMarginAccountSummary($){return L$(_c,$),await this.makeAuthenticatedRequest(W$.marginAccounts.parentSummary({tradingPairId:$?.tradingPairId}))}async getAvailableCollateral($){return L$(Tc,$),await this.makeAuthenticatedRequest(W$.marginAccounts.availableCollateral($))}async transferCollateralToMarginAccount($,J){return L$(xS,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferIn($),{method:"POST",body:JSON.stringify({asset:J.asset,amount:J.amount,tradingPairId:J.tradingPairId,strategyKey:J.strategyKey})})}async transferCollateralToParentMarginAccount($){return L$(Pc,{request:$}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount})})}async transferCollateralToRiskBucket($){return L$(vc,{request:$}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount,tradingPairId:$.tradingPairId,strategyKey:$.strategyKey,marginMode:$.marginMode,selectedTradingPairIds:$.selectedTradingPairIds})})}async transferCollateralFromMarginAccount($,J){return L$(xS,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferOut($),{method:"POST",body:JSON.stringify({asset:J.asset,amount:J.amount,tradingPairId:J.tradingPairId,strategyKey:J.strategyKey})})}async transferCollateralFromParentMarginAccount($){return L$(kc,{request:$}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount})})}async getMarginAccountMovements($,J){return L$(xc,{marginAccountId:$,...J}),await this.makeAuthenticatedRequest(W$.marginAccounts.movements($,J))}async getParentMarginAccountMovements($){return L$(fc,$),await this.makeAuthenticatedRequest(W$.marginAccounts.parentMovements($))}async simulateOrderRisk($,J){return L$(gc,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(W$.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 L$(yc,{request:$}),await this.makeAuthenticatedRequest(W$.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 L$(hc,{request:$}),await this.makeAuthenticatedRequest(W$.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 gH extends t${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 L$(vJ,{tradingPairId:$}),(await this.makePublicRequest(W$.market.getTradingPair($))).tradingPair}async getTradingPairBySymbol($,J){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:J})).tradingPairs.find((Y)=>Y.symbol===$)}async getCandlesticks($,J,Q){L$(mc,{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 L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getMarketMetadata($))}async getPerpMarketConfig($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getPerpMarketConfig($))}async getPerpMarketSummary($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getPerpMarketSummary($))}async getMarkPrice($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getMarkPrice($))}async getIndexPrice($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getIndexPrice($))}async getFundingState($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getFundingState($))}async listFundingHistory($,J){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.listFundingHistory($,J))}async getOpenInterest($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getOpenInterest($))}async getScreener($){return await this.makePublicRequest(W$.market.getScreener($))}async getMarketStats(){return await this.makePublicRequest(W$.market.getMarketStats())}}class yH extends t${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 hH extends t${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=L$(_S,$);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:J.token,amount:J.amount})})}}var UK="/api/v1/accounts/me/portfolio";function uH($,J){if(!J?.period)return $;return`${$}?${new URLSearchParams({period:J.period})}`}class mH extends t${async getSummary($){return await this.makeAuthenticatedRequest(uH(`${UK}/summary`,$))}async getPerformance($){return await this.makeAuthenticatedRequest(uH(`${UK}/performance`,$))}async getRealizedPnl($){return await this.makeAuthenticatedRequest(uH(`${UK}/realized-pnl`,$))}async getAssets($){return await this.makeAuthenticatedRequest(uH(`${UK}/assets`,$))}async getMargin(){return await this.makeAuthenticatedRequest(`${UK}/margin`)}}class lH extends t${async listPositions($){if($)L$(pc,$);return await this.makeAuthenticatedRequest(W$.positions.list($))}async getPosition($){return L$(nc,{positionId:$}),await this.makeAuthenticatedRequest(W$.positions.get($))}async closePosition($,J){return L$(cc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(W$.positions.close($),{method:"POST",body:JSON.stringify({closeType:J.closeType,limitPrice:J.limitPrice,slippageToleranceBps:J.slippageToleranceBps,quantity:J.quantity})})}async batchCloseAllPositions($){if($)L$(ic,$);return await this.makeAuthenticatedRequest(W$.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:$?.tradingPairId,slippageToleranceBps:$?.slippageToleranceBps})})}async getPositionRisk($){return L$(oc,{positionId:$}),await this.makeAuthenticatedRequest(W$.positions.risk($))}async addPositionMargin($,J){return L$(rc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(W$.positions.addMargin($),{method:"POST",body:JSON.stringify({amount:J.amount,asset:J.asset})})}async reducePositionMargin($,J){return L$(tc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(W$.positions.reduceMargin($),{method:"POST",body:JSON.stringify({amount:J.amount})})}async attachPositionTpSl($,J){return L$(ac,{positionId:$,request:J}),await this.makeAuthenticatedRequest(W$.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,closePosition:J.takeProfit.closePosition,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,closePosition:J.stopLoss.closePosition,timeInForce:J.stopLoss.timeInForce,slippageToleranceBps:J.stopLoss.slippageToleranceBps,expiresAt:J.stopLoss.expiresAt}:void 0,oco:J.oco})})}async listPositionHistory($){if($)L$(sc,$);return await this.makeAuthenticatedRequest(W$.positions.history($))}async getPositionPnlHistory($,J){return L$(ec,{positionId:$,params:J}),await this.makeAuthenticatedRequest(W$.positions.pnlHistory($,J))}}class yS extends t${async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements($){if($)L$($i,$);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($)L$(Ji,$);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($)L$(Qi,$);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 dH extends t${async list(){return await this.makeAuthenticatedRequest(W$.subAccounts.list())}async createLimit($){return await this.makeAuthenticatedRequest(W$.subAccounts.createLimit(),{method:"POST",body:JSON.stringify($)})}async getLimits($){return await this.makeAuthenticatedRequest(W$.subAccounts.getLimits($))}async updateLimit($,J,Q){return await this.makeAuthenticatedRequest(W$.subAccounts.limit($,J),{method:"PUT",body:JSON.stringify(Q)})}async deleteLimit($,J){await this.makeAuthenticatedRequest(W$.subAccounts.limit($,J),{method:"DELETE"})}}function Wi($){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 hS extends t${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(Wi)}async getTradeById($){let J=await this.makePublicRequest(W$.trades.byId($));return Wi(J)}}function pH($){if(!$)return;return{triggerPrice:$.triggerPrice,orderType:$.orderType,limitPrice:$.limitPrice,timeInForce:$.timeInForce,slippageToleranceBps:$.slippageToleranceBps,expiresAt:$.expiresAt}}class nH extends t${async placeLimitOrder($,J,Q,Y,X){L$(Ac,{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:pH(X?.takeProfit),stopLoss:pH(X?.stopLoss)};return await this.makeAuthenticatedRequest(W$.orders.create(),{method:"POST",body:JSON.stringify(G)})}async placeMarketOrder($,J,Q,Y){L$(Ic,{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:pH(Y?.takeProfit),stopLoss:pH(Y?.stopLoss)};return await this.makeAuthenticatedRequest(W$.orders.create(),{method:"POST",body:JSON.stringify(X)})}async cancelOrder($){L$(qc,{orderId:$});let J={orderId:$};return await this.makeAuthenticatedRequest(W$.orders.cancel(),{method:"POST",body:JSON.stringify(J)})}async cancelConditionalOrder($){return L$(vS,{conditionalOrderId:$}),await this.makeAuthenticatedRequest(W$.orders.cancelConditional($),{method:"DELETE"})}async getConditionalOrder($){return L$(vS,{conditionalOrderId:$}),await this.makeAuthenticatedRequest(W$.orders.getConditional($),{method:"GET"})}async listConditionalOrders($){if($)L$(Bc,$);let{page:J=1,pageSize:Q=20,marginAccountId:Y,tradingPairId:X,state:G}=$||{};return await this.makeAuthenticatedRequest(W$.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(W$.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:$})})}async batchCancelAll($){let J=$?W$.orders.batchCancelAllByPair($):W$.orders.batchCancelAll();return this.makeAuthenticatedRequest(J,{method:"POST"})}async replaceOrder($,J){L$(Lc,{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(W$.orders.replace($),{method:"PUT",body:JSON.stringify(Q)})}async batchCreate($){L$(Fc,{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(W$.orders.batchCreate(),{method:"POST",body:JSON.stringify(J)})}async batchReplace($){L$(jc,{orders:$});let J={orders:$.map((Q)=>({orderId:Q.orderId,price:Q.price,quantity:Q.quantity,useMasterBalance:Q.useMasterBalance}))};return this.makeAuthenticatedRequest(W$.orders.batchReplace(),{method:"POST",body:JSON.stringify(J)})}async getPaginatedOrders($){if($)L$(Zc,$);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(W$.orders.get($),{method:"GET"}),status:"SUCCESS"}}}var uS=[{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 mS={vault:uS};var WU$=5000,DU$=300000,VU$=($)=>new Promise((J)=>setTimeout(J,$));function Di($,J){return J==="margin"?JSON.stringify({clientId:$,depositTarget:"MARGIN"}):$}class cH extends t${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 zQ(`Asset ID '${$}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:Y});throw new zQ(`Failed to resolve asset ID '${$}': ${Y.retryable?"Network error occurred":"API request failed"}`,{revertReason:Y.retryable?"NETWORK_ERROR":"API_ERROR",cause:Y})}throw new zQ(`Failed to resolve asset ID '${$}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:Y instanceof Error?Y:void 0})}return{tokenAddress:J,isNativeToken:J===A6}}async approve($,J,Q=!0){if(!this.walletClient)throw new k4("Wallet client not set. Connect a wallet first.","walletClient");L$(Xi,{assetId:$,amount:J,autoWait:Q});let Y=await this.getVaultAddress(),{tokenAddress:X}=await this.resolveAsset($),G=this.walletClient.account;if(!G)throw new k4("No account available in wallet client","account");let W=G.getNonce?await G.getNonce():0n,D=await this.walletClient.writeContract({address:X,abi:ew,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 k4("Wallet client not set. Connect a wallet first.","walletClient");L$(Yi,{assetId:$,amount:J,autoWait:Q,target:Y});let X=await this.getVaultAddress(),G=await this.getClientId(),W=Di(G,Y),{tokenAddress:D,isNativeToken:V}=await this.resolveAsset($);if(!V){if(await this.needsApproval($,J))throw new zQ(`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 k4("No account available in wallet client","account");let O;if(V)O=await this.walletClient.writeContract({address:X,abi:mS.vault,functionName:"depositNative",args:[K.address,W],account:K,chain:this.chain,value:J});else O=await this.walletClient.writeContract({address:X,abi:mS.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??WU$,Y=J?.timeoutMs??DU$,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 VU$(Q)}}async withdraw($,J,Q=!0,Y,X){if(!this.walletClient)throw new k4("Wallet client not set. Connect a wallet first.","walletClient");let G=this.walletClient.account;if(!G)throw new k4("No account available in wallet client","account");let W=G.address.toLowerCase(),D=typeof Y==="string"?Y:"spot",V=typeof Y==="string"?X:Y;L$(Gi,{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 zQ(`Failed to submit executeWithdrawal for withdrawal ${K}: ${Z instanceof Error?Z.message:"unknown error"}`,{cause:Z instanceof Error?Z:void 0})}let A=G.getNonce?await G.getNonce():0n,q={hash:M,status:"pending",nonce:A};return{...await this.waitForTransaction(q,Q),withdrawalIndex:K}}async retryWithdrawal($,J=!0,Q){if(!this.walletClient)throw new k4("Wallet client not set. Connect a wallet first.","walletClient");let Y=this.walletClient.account;if(!Y)throw new k4("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 zQ(`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 k4("Wallet client not set. Connect a wallet first.","walletClient");let J=await this.getVaultAddress(),Y=(await this.walletClient.getAddresses())[0];if(!Y)throw new k4("No account found in wallet client.","walletClient");let{tokenAddress:X}=await this.resolveAsset($);return await this.publicClient.readContract({address:X,abi:ew,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 iH extends t${async submit($){return await this.makePublicRequest(W$.whitelist.submit(),{method:"POST",body:JSON.stringify($)})}}class lS extends t${async initiateWithdrawal($){return this.makeAuthenticatedRequest(W$.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:$.assetId,amount:$.amount,destination:$.destination,source:$.source??"spot"})})}async getWithdrawal($){return this.makePublicRequest(W$.withdrawals.byIndex($))}async listPendingWithdrawals($){return this.makeAuthenticatedRequest(W$.withdrawals.list({page:$?.page,pageSize:$?.pageSize}))}}class oH extends t${chain;walletClient;constructor($,J,Q){super(Q);this.chain=J,this.walletClient=$}setWalletClient($){this.walletClient=$}async authenticate($,J){if(!this.walletClient)throw new k4("Wallet client not set. Connect a wallet first.","walletClient");let Q=this.walletClient.account;if(!Q)throw new k4("No account available in wallet client","account");let Y=lw(),X={publicKey:dw(Y),privateKey:pw(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 k4("Wallet client not set. Connect a wallet first.","walletClient");let J=this.walletClient.account;if(!J)throw new k4("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"})}}var KU$=750;function Vi($,J){try{new URL($)}catch(Q){throw new k4(`${J} must be a valid URL, got: ${$}`,J)}return $}class pS{auth;delegatedAgents;applications;fees;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;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.portfolio.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.portfolio.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 k4(`network must be one of: ${J.join(", ")}. Got: ${$.network}`,"network");if(this.network=$.network,!$.seiRpcUrl)throw new k4("seiRpcUrl is required","seiRpcUrl");try{new URL($.seiRpcUrl)}catch(W){throw new k4(`seiRpcUrl must be a valid URL, got: ${$.seiRpcUrl}`,"seiRpcUrl")}let Q=$.wsUrl?Vi($.wsUrl,"wsUrl"):SF(this.network),Y=this.network==="mainnet"?BS:FS;if(this.chain=Y,$.pollingInterval!==void 0&&(!Number.isFinite($.pollingInterval)||$.pollingInterval<=0))throw new k4(`pollingInterval must be a positive number of milliseconds, got: ${$.pollingInterval}`,"pollingInterval");let X=ZS($.seiRpcUrl);this.publicClient=IS({chain:Y,transport:X,pollingInterval:$.pollingInterval??KU$});let G=$.apiUrl?Vi($.apiUrl,"apiUrl"):DV(this.network);if($.walletClient){if($.walletClient.chain?.id!==Y.id)throw new k4(`Wallet client chain mismatch. Expected ${Y.id}, got ${$.walletClient.chain?.id}`,"walletClient");this.walletClient=$.walletClient}this.applications=new RH(G),this.market=new gH(G),this.marginAccounts=new bH(G),this.positions=new lH(G),this.portfolio=new mH(G),this.subAccounts=new dH(G),this.faucet=new CH(G),this.whitelist=new iH(G),this.auth=new oH(this.walletClient,this.chain,G),this.delegatedAgents=new jS(G),this.fees=new fH(G),this.pitpass=new hH(G),this.profile=new yS(G),this.vault=new cH(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,G),this.withdrawals=new lS(G),this.trading=new nH(G),this.orderbook=new yH(G),this.trades=new hS(G),this.ws=qF(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:dS.StatusCodes.UNAUTHORIZED});let J=lw(),Q={publicKey:dw(J),privateKey:pw(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:dS.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 k4(`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 WV("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new WV("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 nS($){return new pS($)}function U4($){if(typeof $==="string")return{address:$,type:"json-rpc"};return $}var rH=256,tH;function aH($=11){if(!tH||rH+$>512){tH="",rH=0;for(let J=0;J<256;J++)tH+=(256+Math.random()*256|0).toString(16).substring(1)}return tH.substring(rH,rH+++$)}function Ki($){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?U4($.account):void 0,{config:A,request:q,value:F}=$.transport({account:M,chain:Q,pollingInterval:N}),Z={...A,...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:aH(),...V?{experimental_blockTag:V}:{}};function B(L){return(j)=>{let T=j(L);for(let x in E)delete T[x];let v={...L,...T};return Object.assign(v,{extend:B(v)})}}return Object.assign(E,{extend:B(E)})}var Ui={gwei:9,wei:18},Oi={ether:-9,wei:9};function sH($,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 sH($,Oi[J])}var cS="2.53.1";var iS={getDocsUrl:({docsBaseUrl:$,docsPath:J="",docsSlug:Q})=>J?`${$??"https://viem.sh"}${J}${Q?`#${Q}`:""}`:void 0,version:`viem@${cS}`};class m extends Error{constructor($,J={}){let Q=(()=>{if(J.cause instanceof m)return J.cause.details;if(J.cause?.message)return J.cause.message;return J.details})(),Y=(()=>{if(J.cause instanceof m)return J.cause.docsPath||J.docsPath;return J.docsPath})(),X=iS.getDocsUrl?.({...J,docsPath:Y}),G=[$||"An error occurred.","",...J.metaMessages?[...J.metaMessages,""]:[],...X?[`Docs: ${X}`]:[],...Q?[`Details: ${Q}`]:[],...iS.version?[`Version: ${iS.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 L$($,J){let Q=$.safeParse(J);if(!Q.success)throw new wc(Q.error);return Q.data}var WK=z.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),vH=z.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),RS=z.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),DK=z.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),Mc=z.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),CS=z.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),cG=z.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),w4=z.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"}),_$=z.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),VK=z.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),Hc=z.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),KK=z.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),PH=z.object({triggerPrice:w4,orderType:cG,limitPrice:w4.optional(),timeInForce:CS.optional(),slippageToleranceBps:KK.optional(),expiresAt:VK.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"]}),zc=($)=>$?.takeProfit!==void 0||$?.stopLoss!==void 0,PS=($,J)=>J===void 0||J!=="NONE"&&($==="BUY"&&J==="LONG"||$==="SELL"&&J==="SHORT"),Ac=z.object({tradingPairId:_$,side:WK,quantity:w4,price:w4,options:z.object({tradingMode:vH.optional(),useMasterBalance:z.boolean().optional(),expirationDate:VK.optional(),timeInForce:Mc.optional(),marginAccountId:_$.optional(),marginMode:RS.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:DK.optional(),leverage:w4.optional(),reduceOnly:z.boolean().optional(),takeProfit:PH.optional(),stopLoss:PH.optional()}).optional()}).refine(($)=>PS($.side,$.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.reduceOnly===!0||$.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine(($)=>!zc($.options),{message:"Entry-attached TP/SL are no longer supported; create position TP/SL after the position opens",path:["options"]}).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"]}),Ic=z.object({tradingPairId:_$,side:WK,quantity:w4,options:z.object({tradingMode:vH.optional(),slippageTolerance:Hc,marginAccountId:_$.optional(),marginMode:RS.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:DK.optional(),leverage:w4.optional(),reduceOnly:z.boolean().optional(),takeProfit:PH.optional(),stopLoss:PH.optional()}).optional()}).refine(($)=>PS($.side,$.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.reduceOnly===!0||$.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine(($)=>!zc($.options),{message:"Entry-attached TP/SL are no longer supported; create position TP/SL after the position opens",path:["options"]}).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"]}),qc=z.object({orderId:_$}),Lc=z.object({orderId:_$,newOrder:z.object({price:w4.optional(),quantity:w4.optional(),useMasterBalance:z.boolean().optional()})}),Zc=z.object({status:z.enum(TS).optional(),tradingPairId:_$.optional(),tradingMode:vH.optional(),marginAccountId:_$.optional(),page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),pageToken:z.string().optional()}),lB4=z.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),dB4=z.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),lK$=z.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),pB4=z.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),vS=z.object({conditionalOrderId:_$}),Bc=z.object({marginAccountId:_$.optional(),tradingPairId:_$.optional(),state:lK$.optional(),page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),dK$=z.object({tradingPairId:_$,orderType:cG,side:WK,price:w4.optional(),quantity:w4,tradingMode:vH.optional(),slippageTolerance:Hc,useMasterBalance:z.boolean().optional(),expirationDate:VK.optional(),timeInForce:Mc.optional(),marginAccountId:_$.optional(),marginMode:RS.optional(),riskBucketId:_$.optional(),riskBucketCollateral:w4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:DK.optional(),leverage:w4.optional(),reduceOnly:z.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(($)=>$.orderType!=="MARKET"||$.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).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(($)=>PS($.side,$.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine(($)=>$.tradingMode!=="MARGIN"||$.reduceOnly===!0||$.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),Fc=z.object({orders:z.array(dK$).min(1,"At least one order is required")}),pK$=z.object({orderId:_$,price:w4.optional(),quantity:w4.optional(),useMasterBalance:z.boolean().optional()}).refine(($)=>$.price!==void 0||$.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),jc=z.object({orders:z.array(pK$).min(1,"At least one order is required")});var kS=z.object({page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Ec=kS.extend({state:z.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:_$.optional()}),Sc=z.object({marginAccountId:_$,tradingPairId:_$.optional()}),_c=z.object({tradingPairId:_$.optional()}).optional(),Tc=z.object({asset:z.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),nK$=z.object({asset:z.string().trim().min(1,"Asset cannot be empty"),amount:w4,tradingPairId:_$.optional(),strategyKey:z.string().trim().min(1,"Strategy key cannot be empty").optional()}),kH=z.object({asset:z.string().trim().min(1,"Asset cannot be empty"),amount:w4}),cK$=z.object({tradingPairId:_$,strategyKey:z.string().trim().min(1,"Strategy key cannot be empty").optional()}),iK$=z.array(_$).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),Rc=cK$.extend({marginMode:z.literal("ISOLATED").optional(),selectedTradingPairIds:z.never().optional()}),Cc=z.object({marginMode:z.literal("CROSS"),selectedTradingPairIds:iK$,strategyKey:z.never().optional()}),oK$=Cc.extend({tradingPairId:z.never().optional()}),xS=z.object({marginAccountId:_$,request:nK$}),Pc=z.object({request:kH}),vc=z.object({request:z.union([kH.merge(Rc).strict(),kH.merge(oK$).strict()])}),kc=z.object({request:kH}),xc=kS.extend({marginAccountId:_$,movementType:z.string().trim().min(1,"Movement type cannot be empty").optional()}),fc=kS.extend({movementType:z.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),fS=z.object({tradingPairId:_$,side:WK,positionSide:DK.optional(),orderType:cG,price:w4.optional(),quantity:w4,leverage:w4.optional(),reduceOnly:z.boolean().optional()}),bS=($,J)=>{if($.positionSide!==void 0){let Q=$.side==="BUY"?"LONG":"SHORT";if($.positionSide!==Q)J.addIssue({code:z.ZodIssueCode.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if($.reduceOnly!==!0&&$.leverage===void 0)J.addIssue({code:z.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},bc=fS.strict().superRefine(bS),rK$=fS.merge(Rc).strict().superRefine(bS),tK$=fS.merge(Cc).strict().superRefine(bS).refine(($)=>$.selectedTradingPairIds.includes($.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),aK$=z.union([rK$,tK$]),gc=z.object({marginAccountId:_$,request:bc}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),yc=z.object({request:bc}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),hc=z.object({request:aK$}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var uc=z.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"'}),sK$=31536000000,eK$=946684800000,xH=z.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(eK$,{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()+sK$,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),aB4=z.object({tradingPairId:_$,interval:uc,startTime:xH,endTime:xH}).refine(($)=>$.startTime<$.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),sB4=z.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")'}),$U$=z.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),mc=z.object({tradingPairId:_$,interval:uc,startTime:xH.optional(),endTime:xH.optional(),limit:$U$}).refine(($)=>{if($.startTime!==void 0&&$.endTime!==void 0)return $.startTime<$.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var eB4=z.object({tradingPairId:_$}),$F4=z.object({query:z.string().min(1,"Search query cannot be empty").optional(),pageSize:z.number().int().min(1).max(100).optional(),page:z.number().int().min(1).optional()}),vJ=z.object({tradingPairId:_$});var dc=z.object({page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),JU$=z.enum(["OPEN","CLOSED","LIQUIDATING"],{message:'Position status must be "OPEN", "CLOSED", or "LIQUIDATING"'}),QU$=z.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),n9=z.object({positionId:_$}),pc=dc.extend({marginAccountId:_$.optional(),tradingPairId:_$.optional(),status:JU$.optional()}),nc=n9,cc=n9.extend({request:z.object({closeType:QU$,limitPrice:w4.optional(),slippageToleranceBps:KK.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"]}),ic=z.object({tradingPairId:_$.optional(),slippageToleranceBps:KK.optional()}),oc=n9,rc=n9.extend({request:z.object({amount:w4,asset:z.string().trim().min(1,"Asset cannot be empty")})}),tc=n9.extend({request:z.object({amount:w4})}),lc=z.object({triggerPrice:w4,orderType:cG,limitPrice:w4.optional(),quantity:w4.optional(),closePosition:z.boolean().optional(),timeInForce:CS.optional(),slippageToleranceBps:KK.optional(),expiresAt:VK.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"]}).refine(($)=>$.closePosition!==!0||$.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine(($)=>$.quantity!==void 0||$.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),ac=n9.extend({request:z.object({takeProfit:lc.optional(),stopLoss:lc.optional(),oco:z.boolean().optional()}).refine(($)=>$.takeProfit!==void 0||$.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine(($)=>$.oco!==!0||$.takeProfit!==void 0&&$.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),sc=dc.extend({positionId:_$.optional(),marginAccountId:_$.optional(),tradingPairId:_$.optional(),reductionOnly:z.boolean().optional()}),XU$=z.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),ec=n9.extend({params:z.object({interval:XU$,startTime:z.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:z.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 YU$=z.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),GU$=z.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),$i=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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:YU$.optional(),transactionType:GU$.optional(),assetId:_$.optional()}),Ji=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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(),pageToken:z.string().optional()}),Qi=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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 UF4=z.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),gS=z.union([z.string().regex(/^\d+$/,"Must be a positive integer string").refine(($)=>BigInt($)>0n,{message:"Amount must be greater than 0"}),z.bigint().refine(($)=>$>0n,{message:"Amount must be greater than 0"})]),Xi=z.object({assetId:_$,amount:gS,autoWait:z.boolean().optional()}),Yi=z.object({assetId:_$,amount:gS,autoWait:z.boolean().optional(),target:z.enum(["spot","margin"]).optional()}),Gi=z.object({assetId:_$,amount:gS,destination:z.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:z.boolean().optional(),source:z.enum(["spot","margin"]).optional()}),OF4=z.object({assetId:_$});class fH extends t${async simulateFees($){let J=L$(ES,$),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=L$(SS,$),Q=new URLSearchParams;Q.append("tradingPairId",J.tradingPairId);let Y=`/api/v1/fees/tier?${Q.toString()}`;return await this.makeAuthenticatedRequest(Y,{method:"GET"})}}class bH extends t${async listMarginAccounts($){if($)L$(Ec,$);return await this.makeAuthenticatedRequest(W$.marginAccounts.list($?{page:$.page,pageSize:$.pageSize,state:$.state,tradingPairId:$.tradingPairId}:void 0))}async getMarginAccountSummary($,J){return L$(Sc,{marginAccountId:$,...J}),await this.makeAuthenticatedRequest(W$.marginAccounts.summary($,{tradingPairId:J?.tradingPairId}))}async getParentMarginAccountSummary($){return L$(_c,$),await this.makeAuthenticatedRequest(W$.marginAccounts.parentSummary({tradingPairId:$?.tradingPairId}))}async getAvailableCollateral($){return L$(Tc,$),await this.makeAuthenticatedRequest(W$.marginAccounts.availableCollateral($))}async transferCollateralToMarginAccount($,J){return L$(xS,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferIn($),{method:"POST",body:JSON.stringify({asset:J.asset,amount:J.amount,tradingPairId:J.tradingPairId,strategyKey:J.strategyKey})})}async transferCollateralToParentMarginAccount($){return L$(Pc,{request:$}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount})})}async transferCollateralToRiskBucket($){return L$(vc,{request:$}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount,tradingPairId:$.tradingPairId,strategyKey:$.strategyKey,marginMode:$.marginMode,selectedTradingPairIds:$.selectedTradingPairIds})})}async transferCollateralFromMarginAccount($,J){return L$(xS,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferOut($),{method:"POST",body:JSON.stringify({asset:J.asset,amount:J.amount,tradingPairId:J.tradingPairId,strategyKey:J.strategyKey})})}async transferCollateralFromParentMarginAccount($){return L$(kc,{request:$}),await this.makeAuthenticatedRequest(W$.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount})})}async getMarginAccountMovements($,J){return L$(xc,{marginAccountId:$,...J}),await this.makeAuthenticatedRequest(W$.marginAccounts.movements($,J))}async getParentMarginAccountMovements($){return L$(fc,$),await this.makeAuthenticatedRequest(W$.marginAccounts.parentMovements($))}async simulateOrderRisk($,J){return L$(gc,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(W$.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 L$(yc,{request:$}),await this.makeAuthenticatedRequest(W$.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 L$(hc,{request:$}),await this.makeAuthenticatedRequest(W$.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 gH extends t${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 L$(vJ,{tradingPairId:$}),(await this.makePublicRequest(W$.market.getTradingPair($))).tradingPair}async getTradingPairBySymbol($,J){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:J})).tradingPairs.find((Y)=>Y.symbol===$)}async getCandlesticks($,J,Q){L$(mc,{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 L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getMarketMetadata($))}async getPerpMarketConfig($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getPerpMarketConfig($))}async getPerpMarketSummary($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getPerpMarketSummary($))}async getMarkPrice($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getMarkPrice($))}async getIndexPrice($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getIndexPrice($))}async getFundingState($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getFundingState($))}async listFundingHistory($,J){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.listFundingHistory($,J))}async getOpenInterest($){return L$(vJ,{tradingPairId:$}),await this.makePublicRequest(W$.market.getOpenInterest($))}async getScreener($){return await this.makePublicRequest(W$.market.getScreener($))}async getMarketStats(){return await this.makePublicRequest(W$.market.getMarketStats())}}class yH extends t${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 hH extends t${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=L$(_S,$);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:J.token,amount:J.amount})})}}var UK="/api/v1/accounts/me/portfolio";function uH($,J){if(!J?.period)return $;return`${$}?${new URLSearchParams({period:J.period})}`}class mH extends t${async getSummary($){return await this.makeAuthenticatedRequest(uH(`${UK}/summary`,$))}async getPerformance($){return await this.makeAuthenticatedRequest(uH(`${UK}/performance`,$))}async getRealizedPnl($){return await this.makeAuthenticatedRequest(uH(`${UK}/realized-pnl`,$))}async getAssets($){return await this.makeAuthenticatedRequest(uH(`${UK}/assets`,$))}async getMargin(){return await this.makeAuthenticatedRequest(`${UK}/margin`)}}class lH extends t${async listPositions($){if($)L$(pc,$);return await this.makeAuthenticatedRequest(W$.positions.list($))}async getPosition($){return L$(nc,{positionId:$}),await this.makeAuthenticatedRequest(W$.positions.get($))}async closePosition($,J){return L$(cc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(W$.positions.close($),{method:"POST",body:JSON.stringify({closeType:J.closeType,limitPrice:J.limitPrice,slippageToleranceBps:J.slippageToleranceBps,quantity:J.quantity})})}async batchCloseAllPositions($){if($)L$(ic,$);return await this.makeAuthenticatedRequest(W$.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:$?.tradingPairId,slippageToleranceBps:$?.slippageToleranceBps})})}async getPositionRisk($){return L$(oc,{positionId:$}),await this.makeAuthenticatedRequest(W$.positions.risk($))}async addPositionMargin($,J){return L$(rc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(W$.positions.addMargin($),{method:"POST",body:JSON.stringify({amount:J.amount,asset:J.asset})})}async reducePositionMargin($,J){return L$(tc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(W$.positions.reduceMargin($),{method:"POST",body:JSON.stringify({amount:J.amount})})}async attachPositionTpSl($,J){return L$(ac,{positionId:$,request:J}),await this.makeAuthenticatedRequest(W$.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,closePosition:J.takeProfit.closePosition,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,closePosition:J.stopLoss.closePosition,timeInForce:J.stopLoss.timeInForce,slippageToleranceBps:J.stopLoss.slippageToleranceBps,expiresAt:J.stopLoss.expiresAt}:void 0,oco:J.oco})})}async listPositionHistory($){if($)L$(sc,$);return await this.makeAuthenticatedRequest(W$.positions.history($))}async getPositionPnlHistory($,J){return L$(ec,{positionId:$,params:J}),await this.makeAuthenticatedRequest(W$.positions.pnlHistory($,J))}}class yS extends t${async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements($){if($)L$($i,$);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($)L$(Ji,$);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($?.pageToken!==void 0)J.append("pageToken",$.pageToken);let Q=J.toString(),Y=Q?`/api/v1/accounts/trades?${Q}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(Y)}async listFundingPayments($){if($)L$(Qi,$);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 dH extends t${async list(){return await this.makeAuthenticatedRequest(W$.subAccounts.list())}async createLimit($){return await this.makeAuthenticatedRequest(W$.subAccounts.createLimit(),{method:"POST",body:JSON.stringify($)})}async getLimits($){return await this.makeAuthenticatedRequest(W$.subAccounts.getLimits($))}async updateLimit($,J,Q){return await this.makeAuthenticatedRequest(W$.subAccounts.limit($,J),{method:"PUT",body:JSON.stringify(Q)})}async deleteLimit($,J){await this.makeAuthenticatedRequest(W$.subAccounts.limit($,J),{method:"DELETE"})}}function Wi($){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 hS extends t${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(Wi)}async getTradeById($){let J=await this.makePublicRequest(W$.trades.byId($));return Wi(J)}}function pH($){if(!$)return;return{triggerPrice:$.triggerPrice,orderType:$.orderType,limitPrice:$.limitPrice,timeInForce:$.timeInForce,slippageToleranceBps:$.slippageToleranceBps,expiresAt:$.expiresAt}}class nH extends t${async placeLimitOrder($,J,Q,Y,X){L$(Ac,{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:pH(X?.takeProfit),stopLoss:pH(X?.stopLoss)};return await this.makeAuthenticatedRequest(W$.orders.create(),{method:"POST",body:JSON.stringify(G)})}async placeMarketOrder($,J,Q,Y){L$(Ic,{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:pH(Y?.takeProfit),stopLoss:pH(Y?.stopLoss)};return await this.makeAuthenticatedRequest(W$.orders.create(),{method:"POST",body:JSON.stringify(X)})}async cancelOrder($){L$(qc,{orderId:$});let J={orderId:$};return await this.makeAuthenticatedRequest(W$.orders.cancel(),{method:"POST",body:JSON.stringify(J)})}async cancelConditionalOrder($){return L$(vS,{conditionalOrderId:$}),await this.makeAuthenticatedRequest(W$.orders.cancelConditional($),{method:"DELETE"})}async getConditionalOrder($){return L$(vS,{conditionalOrderId:$}),await this.makeAuthenticatedRequest(W$.orders.getConditional($),{method:"GET"})}async listConditionalOrders($){if($)L$(Bc,$);let{page:J=1,pageSize:Q=20,marginAccountId:Y,tradingPairId:X,state:G}=$||{};return await this.makeAuthenticatedRequest(W$.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(W$.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:$})})}async batchCancelAll($){let J=$?W$.orders.batchCancelAllByPair($):W$.orders.batchCancelAll();return this.makeAuthenticatedRequest(J,{method:"POST"})}async replaceOrder($,J){L$(Lc,{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(W$.orders.replace($),{method:"PUT",body:JSON.stringify(Q)})}async batchCreate($){L$(Fc,{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(W$.orders.batchCreate(),{method:"POST",body:JSON.stringify(J)})}async batchReplace($){L$(jc,{orders:$});let J={orders:$.map((Q)=>({orderId:Q.orderId,price:Q.price,quantity:Q.quantity,useMasterBalance:Q.useMasterBalance}))};return this.makeAuthenticatedRequest(W$.orders.batchReplace(),{method:"POST",body:JSON.stringify(J)})}async getPaginatedOrders($){if($)L$(Zc,$);let{page:J=1,pageSize:Q=10,status:Y,tradingPairId:X,tradingMode:G,marginAccountId:W,pageToken:D}=$||{},V=J>0?J:1,K=Q>0?Q:10,O=Math.min(K,100),N=new URLSearchParams;if(N.append("page",V.toString()),N.append("pageSize",O.toString()),Y)N.append("status",Y);if(X)N.append("tradingPairId",X);if(G)N.append("tradingMode",G);if(W)N.append("marginAccountId",W);if(D!==void 0)N.append("pageToken",D);let w=`/api/v1/orders?${N.toString()}`;return await this.makeAuthenticatedRequest(w,{method:"GET"})}async getOrder($){return{order:await this.makeAuthenticatedRequest(W$.orders.get($),{method:"GET"}),status:"SUCCESS"}}}var uS=[{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 mS={vault:uS};var WU$=5000,DU$=300000,VU$=($)=>new Promise((J)=>setTimeout(J,$));function Di($,J){return J==="margin"?JSON.stringify({clientId:$,depositTarget:"MARGIN"}):$}class cH extends t${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 zQ(`Asset ID '${$}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:Y});throw new zQ(`Failed to resolve asset ID '${$}': ${Y.retryable?"Network error occurred":"API request failed"}`,{revertReason:Y.retryable?"NETWORK_ERROR":"API_ERROR",cause:Y})}throw new zQ(`Failed to resolve asset ID '${$}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:Y instanceof Error?Y:void 0})}return{tokenAddress:J,isNativeToken:J===A6}}async approve($,J,Q=!0){if(!this.walletClient)throw new k4("Wallet client not set. Connect a wallet first.","walletClient");L$(Xi,{assetId:$,amount:J,autoWait:Q});let Y=await this.getVaultAddress(),{tokenAddress:X}=await this.resolveAsset($),G=this.walletClient.account;if(!G)throw new k4("No account available in wallet client","account");let W=G.getNonce?await G.getNonce():0n,D=await this.walletClient.writeContract({address:X,abi:ew,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 k4("Wallet client not set. Connect a wallet first.","walletClient");L$(Yi,{assetId:$,amount:J,autoWait:Q,target:Y});let X=await this.getVaultAddress(),G=await this.getClientId(),W=Di(G,Y),{tokenAddress:D,isNativeToken:V}=await this.resolveAsset($);if(!V){if(await this.needsApproval($,J))throw new zQ(`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 k4("No account available in wallet client","account");let O;if(V)O=await this.walletClient.writeContract({address:X,abi:mS.vault,functionName:"depositNative",args:[K.address,W],account:K,chain:this.chain,value:J});else O=await this.walletClient.writeContract({address:X,abi:mS.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??WU$,Y=J?.timeoutMs??DU$,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 VU$(Q)}}async withdraw($,J,Q=!0,Y,X){if(!this.walletClient)throw new k4("Wallet client not set. Connect a wallet first.","walletClient");let G=this.walletClient.account;if(!G)throw new k4("No account available in wallet client","account");let W=G.address.toLowerCase(),D=typeof Y==="string"?Y:"spot",V=typeof Y==="string"?X:Y;L$(Gi,{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 zQ(`Failed to submit executeWithdrawal for withdrawal ${K}: ${Z instanceof Error?Z.message:"unknown error"}`,{cause:Z instanceof Error?Z:void 0})}let A=G.getNonce?await G.getNonce():0n,q={hash:M,status:"pending",nonce:A};return{...await this.waitForTransaction(q,Q),withdrawalIndex:K}}async retryWithdrawal($,J=!0,Q){if(!this.walletClient)throw new k4("Wallet client not set. Connect a wallet first.","walletClient");let Y=this.walletClient.account;if(!Y)throw new k4("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 zQ(`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 k4("Wallet client not set. Connect a wallet first.","walletClient");let J=await this.getVaultAddress(),Y=(await this.walletClient.getAddresses())[0];if(!Y)throw new k4("No account found in wallet client.","walletClient");let{tokenAddress:X}=await this.resolveAsset($);return await this.publicClient.readContract({address:X,abi:ew,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 iH extends t${async submit($){return await this.makePublicRequest(W$.whitelist.submit(),{method:"POST",body:JSON.stringify($)})}}class lS extends t${async initiateWithdrawal($){return this.makeAuthenticatedRequest(W$.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:$.assetId,amount:$.amount,destination:$.destination,source:$.source??"spot"})})}async getWithdrawal($){return this.makePublicRequest(W$.withdrawals.byIndex($))}async listPendingWithdrawals($){return this.makeAuthenticatedRequest(W$.withdrawals.list({page:$?.page,pageSize:$?.pageSize}))}}class oH extends t${chain;walletClient;constructor($,J,Q){super(Q);this.chain=J,this.walletClient=$}setWalletClient($){this.walletClient=$}async authenticate($,J){if(!this.walletClient)throw new k4("Wallet client not set. Connect a wallet first.","walletClient");let Q=this.walletClient.account;if(!Q)throw new k4("No account available in wallet client","account");let Y=lw(),X={publicKey:dw(Y),privateKey:pw(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 k4("Wallet client not set. Connect a wallet first.","walletClient");let J=this.walletClient.account;if(!J)throw new k4("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"})}}var KU$=750;function Vi($,J){try{new URL($)}catch(Q){throw new k4(`${J} must be a valid URL, got: ${$}`,J)}return $}class pS{auth;delegatedAgents;applications;fees;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;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.portfolio.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.portfolio.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 k4(`network must be one of: ${J.join(", ")}. Got: ${$.network}`,"network");if(this.network=$.network,!$.seiRpcUrl)throw new k4("seiRpcUrl is required","seiRpcUrl");try{new URL($.seiRpcUrl)}catch(W){throw new k4(`seiRpcUrl must be a valid URL, got: ${$.seiRpcUrl}`,"seiRpcUrl")}let Q=$.wsUrl?Vi($.wsUrl,"wsUrl"):SF(this.network),Y=this.network==="mainnet"?BS:FS;if(this.chain=Y,$.pollingInterval!==void 0&&(!Number.isFinite($.pollingInterval)||$.pollingInterval<=0))throw new k4(`pollingInterval must be a positive number of milliseconds, got: ${$.pollingInterval}`,"pollingInterval");let X=ZS($.seiRpcUrl);this.publicClient=IS({chain:Y,transport:X,pollingInterval:$.pollingInterval??KU$});let G=$.apiUrl?Vi($.apiUrl,"apiUrl"):DV(this.network);if($.walletClient){if($.walletClient.chain?.id!==Y.id)throw new k4(`Wallet client chain mismatch. Expected ${Y.id}, got ${$.walletClient.chain?.id}`,"walletClient");this.walletClient=$.walletClient}this.applications=new RH(G),this.market=new gH(G),this.marginAccounts=new bH(G),this.positions=new lH(G),this.portfolio=new mH(G),this.subAccounts=new dH(G),this.faucet=new CH(G),this.whitelist=new iH(G),this.auth=new oH(this.walletClient,this.chain,G),this.delegatedAgents=new jS(G),this.fees=new fH(G),this.pitpass=new hH(G),this.profile=new yS(G),this.vault=new cH(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,G),this.withdrawals=new lS(G),this.trading=new nH(G),this.orderbook=new yH(G),this.trades=new hS(G),this.ws=qF(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:dS.StatusCodes.UNAUTHORIZED});let J=lw(),Q={publicKey:dw(J),privateKey:pw(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:dS.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 k4(`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 WV("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new WV("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 nS($){return new pS($)}function U4($){if(typeof $==="string")return{address:$,type:"json-rpc"};return $}var rH=256,tH;function aH($=11){if(!tH||rH+$>512){tH="",rH=0;for(let J=0;J<256;J++)tH+=(256+Math.random()*256|0).toString(16).substring(1)}return tH.substring(rH,rH+++$)}function Ki($){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?U4($.account):void 0,{config:A,request:q,value:F}=$.transport({account:M,chain:Q,pollingInterval:N}),Z={...A,...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:aH(),...V?{experimental_blockTag:V}:{}};function B(L){return(j)=>{let T=j(L);for(let x in E)delete T[x];let v={...L,...T};return Object.assign(v,{extend:B(v)})}}return Object.assign(E,{extend:B(E)})}var Ui={gwei:9,wei:18},Oi={ether:-9,wei:9};function sH($,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 sH($,Oi[J])}var cS="2.53.1";var iS={getDocsUrl:({docsBaseUrl:$,docsPath:J="",docsSlug:Q})=>J?`${$??"https://viem.sh"}${J}${Q?`#${Q}`:""}`:void 0,version:`viem@${cS}`};class m extends Error{constructor($,J={}){let Q=(()=>{if(J.cause instanceof m)return J.cause.details;if(J.cause?.message)return J.cause.message;return J.details})(),Y=(()=>{if(J.cause instanceof m)return J.cause.docsPath||J.docsPath;return J.docsPath})(),X=iS.getDocsUrl?.({...J,docsPath:Y}),G=[$||"An error occurred.","",...J.metaMessages?[...J.metaMessages,""]:[],...X?[`Docs: ${X}`]:[],...Q?[`Details: ${Q}`]:[],...iS.version?[`Version: ${iS.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=cS}walk($){return Ni(this,$)}}function Ni($,J){if(J?.($))return $;if($&&typeof $==="object"&&"cause"in $&&$.cause!==void 0)return Ni($.cause,J);return J?null:$}class OK extends m{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class c9 extends m{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class oS extends m{constructor({maxPriorityFeePerGas:$}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${I6($)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class WX extends m{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 m{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 NK extends m{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(NK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class wK extends m{constructor({cause:$,nonce:J}={}){super(`Nonce provided for the transaction ${J?`(${J}) `:""}is higher than the next one expected.`,{cause:$,name:"NonceTooHighError"})}}Object.defineProperty(wK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class MK extends m{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(MK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class HK extends m{constructor({cause:$,nonce:J}={}){super(`Nonce provided for the transaction ${J?`(${J}) `:""}exceeds the maximum allowed nonce.`,{cause:$,name:"NonceMaxValueError"})}}Object.defineProperty(HK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class zK extends m{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 AK extends m{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(AK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class IK extends m{constructor({cause:$,gas:J}={}){super(`The amount of gas ${J?`(${J}) `:""}provided for the transaction is too low.`,{cause:$,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(IK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class qK extends m{constructor({cause:$}){super("The transaction type is not supported for this chain.",{cause:$,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(qK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class fQ extends m{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 nw($,J){return Y9(mw.sign(b5(J),$))}var GV=[0.0001,0.001,0.01,0.1
|
|
|
166
166
|
`),{name:"ChainNotFoundError"})}}class q7 extends m{constructor({chainId:$}){super(typeof $==="number"?`Chain ID "${$}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}function L7({chain:$,currentChainId:J}){if(!$)throw new S_;if(J!==$.id)throw new E_({chain:$,currentChainId:J})}async function zz($){let J=await $.request({method:"eth_gasPrice"});return BigInt(J)}async function _i($,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 x$($,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):x$($,e0,"getBlock")({}),x$($,zz,"getGasPrice")({})]);if(typeof G.baseFeePerGas!=="bigint")throw new c9;let D=W-G.baseFeePerGas;if(D<0n)return 0n;return D}}async function __($,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 OK;let V=10**(W.toString().split(".")[1]?.length??0),K=(w)=>w*BigInt(Math.ceil(W*V))/BigInt(V),O=Q?Q:await x$($,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 _i($,{block:O,chain:Y,request:X}),M=K(O.baseFeePerGas);return{maxFeePerGas:X?.maxFeePerGas??M+w,maxPriorityFeePerGas:w}}return{gasPrice:X?.gasPrice??K(await x$($,zz,"getGasPrice")({}))}}class T_ extends m{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=iG({from:J?.address,to:O,value:typeof N<"u"&&`${eH(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 Ti($,{docsPath:J,...Q}){let Y=(()=>{let X=Qz($,Q);if(X instanceof i9)return $;return X})();return new T_(Y,{docsPath:J,...Q})}class R_ extends m{constructor({address:$}){super(`State for account "${$}" is set multiple times.`,{name:"AccountStateConflictError"})}}class C_ extends m{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Ri($){if(!$||$.length===0)return;return $.reduce((J,{slot:Q,value:Y})=>{if(Q.length!==66)throw new Gz({size:Q.length,targetSize:66,type:"hex"});if(Y.length!==66)throw new Gz({size:Y.length,targetSize:66,type:"hex"});return J[Q]=Y,J},{})}function xU$($){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=Ri(Y);if(X!==void 0){if(W.state)throw new C_;W.stateDiff=Ri(X)}return W}function Ci($){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 R_({address:Q});J[Q]=xU$(Y)}return J}async function Pi($,J){let{account:Q=$.account,prepare:Y=!0}=J,X=Q?U4(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 I7({authorization:J.authorizationList[0]}).catch(()=>{throw new m("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:D,authorizationList:V,blobs:K,blobVersionedHashes:O,blockNumber:N,blockTag:w,data:M,gas:A,gasPrice:q,maxFeePerBlobGas:F,maxFeePerGas:Z,maxPriorityFeePerGas:E,nonce:B,value:L,stateOverride:j,...T}=Y?await zX($,{...J,parameters:G,to:W}):J;if(A&&J.gas!==A)return A;let x=(typeof N==="bigint"?X$(N):void 0)||w,y=Ci(j);A0(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:y?[p,x??$.experimental_blockTag??"latest",y]:x?[p,x]:[p]}))}catch(W){throw Ti(W,{...J,account:X,chain:$.chain})}}function vi($){let{blockHash:J,blockNumber:Q,blockTag:Y,requireCanonical:X}=$;if(X!==void 0&&!J)throw new m("`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 Az($,{address:J,blockHash:Q,blockNumber:Y,blockTag:X="latest",requireCanonical:G}){let W=vi({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 Z7($){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)=>x4(G))}function B7($){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)=>x4(W))}function ki($,J){let Q=J||"hex",Y=GH(u1($,{strict:!1})?M7($):$);if(Q==="bytes")return Y;return m1(Y)}function xi($){let{commitment:J,version:Q=1}=$,Y=$.to??(typeof J==="string"?"hex":"bytes"),X=ki(J,"bytes");return X.set([Q],0),Y==="bytes"?X:x4(X)}function Iz($){let{commitments:J,version:Q}=$,Y=$.to??(typeof J[0]==="string"?"hex":"bytes"),X=[];for(let G of J)X.push(xi({commitment:G,to:Y,version:Q}));return X}var fi=32,bi=4096,gi=131072,P_=761855;var qz=1;class v_ extends m{constructor({maxSize:$,size:J}){super("Blob size is too large.",{metaMessages:[`Max: ${$} bytes`,`Given: ${J} bytes`],name:"BlobSizeTooLargeError"})}}class jK extends m{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class k_ extends m{constructor({hash:$,size:J}){super(`Versioned hash "${$}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${J}`],name:"InvalidVersionedHashSizeError"})}}class x_ extends m{constructor({hash:$,version:J}){super(`Versioned hash "${$}" version is invalid.`,{metaMessages:[`Expected: ${qz}`,`Received: ${J}`],name:"InvalidVersionedHashVersionError"})}}function yi($){let J=$.to??(typeof $.data==="string"?"hex":"bytes"),Q=typeof $.data==="string"?w1($.data):$.data,Y=O4(Q);if(!Y)throw new jK;if(Y>P_)throw new v_({maxSize:P_,size:Y});let X=[],G=!0,W=0;while(G){let D=A7(new Uint8Array(gi)),V=0;while(V<bi){let K=Q.slice(W,W+(fi-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)=>x4(D.bytes))}function Lz($){let{data:J,kzg:Q,to:Y}=$,X=$.blobs??yi({data:J,to:Y}),G=$.commitments??Z7({blobs:X,kzg:Q,to:Y}),W=$.proofs??B7({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 Zz($){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 tS({transaction:$})}var EK=["blobVersionedHashes","chainId","fees","gas","nonce","type"],hi=new Map,f_=new o6(128);async function zX($,J){let Q=J;Q.account??=$.account,Q.parameters??=EK;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 x$($,t1,"getChainId")({}),V}let O=Y?U4(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(f_.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 x$($,Wz,"fillTransaction")({...Q,nonce:N}).then((L)=>{let{chainId:j,from:T,gas:v,gasPrice:x,nonce:y,maxFeePerBlobGas:R,maxFeePerGas:d,maxPriorityFeePerGas:p,type:Y$,...c}=L.transaction;return f_.set($.uid,!0),{...Q,...T?{from:T}:{},...Y$&&!Q.type?{type:Y$}:{},...typeof j<"u"?{chainId:j}:{},...typeof v<"u"?{gas:v}:{},...typeof x<"u"?{gasPrice:x}:{},...typeof y<"u"?{nonce:y}:{},...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?.((x)=>{return x.name==="ExecutionRevertedError"}))throw L;if(j.walk?.((x)=>{let y=x;return y.name==="MethodNotFoundRpcError"||y.name==="MethodNotSupportedRpcError"||y.message?.includes("eth_fillTransaction is not available")}))f_.set($.uid,!1);return Q}):Q;N??=M.nonce,Q={...M,...O?{from:O?.address}:{},...typeof N<"u"?{nonce:N}:{}};let{blobs:A,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 x$($,e0,"getBlock")({blockTag:"latest"}),E}if(W.includes("nonce")&&typeof N>"u"&&O&&!G)Q.nonce=await x$($,Az,"getTransactionCount")({address:O.address,blockTag:"pending"});if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&A&&F){let L=Z7({blobs:A,kzg:F});if(W.includes("blobVersionedHashes")){let j=Iz({commitments:L,to:"hex"});Q.blobVersionedHashes=j}if(W.includes("sidecars")){let j=B7({blobs:A,commitments:L,kzg:F}),T=Lz({blobs:A,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=Zz(Q)}catch{let L=hi.get($.uid);if(typeof L>"u")L=typeof(await B())?.baseFeePerGas==="bigint",hi.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 __($,{block:L,chain:X,request:Q});if(typeof Q.maxPriorityFeePerGas>"u"&&Q.maxFeePerGas&&Q.maxFeePerGas<T)throw new oS({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 __($,{block:L,chain:X,request:Q,type:"legacy"});Q.gasPrice=j}}if(W.includes("gas")&&typeof q>"u")Q.gas=await x$($,Pi,"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 A0(Q),delete Q.parameters,Q}async function Bz($,{serializedTransaction:J}){return $.request({method:"eth_sendRawTransaction",params:[J]},{retryCount:0})}var b_=new o6(128);async function AX($,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:A,nonce:q,type:F,value:Z,...E}=J;if(typeof Q>"u")throw new l1({docsPath:"/docs/actions/wallet/sendTransaction"});let B=Q?U4(Q):null,L;try{A0(J);let j=await(async()=>{if(J.to)return J.to;if(J.to===null)return;if(W&&W.length>0)return await I7({authorization:W[0]}).catch(()=>{throw new m("`to` is required. Could not infer from `authorizationList`.")});return})();if(B?.type==="json-rpc"||B===null){let T;if(X!==null){if(T=await x$($,t1,"getChainId")({}),Y)L7({currentChainId:T,chain:X})}let v=$.chain?.formatters?.transactionRequest?.format,y=(v||kJ)({...wX(E,{format:v}),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:A,nonce:q,to:j,type:F,value:Z},"sendTransaction"),R=b_.get($.uid),d=R?"wallet_sendTransaction":"eth_sendTransaction";try{return await $.request({method:d,params:[y]},{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:[y]},{retryCount:0}).then((c)=>{return b_.set($.uid,!0),c}).catch((c)=>{let l=c;if(l.name==="MethodNotFoundRpcError"||l.name==="MethodNotSupportedRpcError")throw b_.set($.uid,!1),Y$;throw l});throw Y$}}if(B?.type==="local"){if(B.nonceManager&&typeof q>"u"){let y=E.chainId,R=await(async()=>{if(typeof y==="number")return y;if(X)return X.id;return x$($,t1,"getChainId")({})})();L={address:B.address,chainId:R}}let T=await x$($,zX,"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:A,nonce:q,nonceManager:B.nonceManager,parameters:[...EK,"sidecars"],type:F,value:Z,...E,to:j}),v=X?.serializers?.transaction,x=await B.signTransaction(T,{serializer:v});return await x$($,Bz,"sendRawTransaction")({serializedTransaction:x})}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 ui($,J){let{abi:Q,args:Y,bytecode:X,...G}=J,W=Zi({abi:Q,args:Y,bytecode:X});return AX($,{...G,...G.authorizationList?{to:null}:{},data:W})}async function mi($){if($.account?.type==="local")return[$.account.address];return(await $.request({method:"eth_accounts"},{dedupe:!0})).map((Q)=>uQ(Q))}function li($,{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 g_={"0x0":"reverted","0x1":"success"};function Fz($,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)=>li(Y)):null,to:$.to?$.to:null,transactionIndex:$.transactionIndex?F1($.transactionIndex):null,status:$.status?g_[$.status]:null,type:$.type?G_[$.type]||$.type:null};if($.blobGasPrice)Q.blobGasPrice=BigInt($.blobGasPrice);if($.blobGasUsed)Q.blobGasUsed=BigInt($.blobGasUsed);return Q}var fU$=($)=>D1(M7($));function di($){return fU$($)}a5();function pi($){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 m("Unable to normalize signature.");return X}var ni=($)=>{let J=(()=>{if(typeof $==="string")return $;return EQ($)})();return pi(J)};function jz($){return di(ni($))}var F7=($)=>mQ(jz($),0,4);var ci=jz;function Ez($){let{abi:J,args:Q=[],name:Y}=$,X=u1(Y,{strict:!1}),G=J.filter((D)=>{if(X){if(D.type==="function")return F7(D)===Y;if(D.type==="event")return ci(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 y_(K,N)})){if(W&&"inputs"in W&&W.inputs){let K=ii(D.inputs,W.inputs,Q);if(K)throw new M_({abiItem:D,type:K[0]},{abiItem:W,type:K[1]})}W=D}}if(W)return W;return G[0]}function y_($,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"&&y_(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)=>y_(X,{...J,type:Y.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function ii($,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 ii(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 oi="/docs/contract/encodeFunctionData";function ri($){let{abi:J,args:Q,functionName:Y}=$,X=J[0];if(Y){let G=Ez({abi:J,args:Q,name:Y});if(!G)throw new Kz(Y,{docsPath:oi});X=G}if(X.type!=="function")throw new Kz(void 0,{docsPath:oi});return{abi:[X],functionName:F7(xJ(X))}}function Sz($){let{args:J}=$,{abi:Q,functionName:Y}=(()=>{if($.abi.length===1&&$.functionName?.startsWith("0x"))return $;return ri($)})(),X=Q[0],G=Y,W="inputs"in X&&X.inputs?e9(X.inputs,J??[]):void 0;return I0([G,W??"0x"])}var h_="0x5792579257925792579257925792579257925792579257925792579257925792",u_=X$(0,{size:32});async function _z($,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?U4(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,A=M.abi?Sz({abi:M.abi,functionName:M.functionName,args:M.args}):M.data;return{data:M.dataSuffix&&A?V1([A,M.dataSuffix]):A,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 m("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 m("`forceAtomic` is not supported on fallback to `eth_sendTransaction`.",{details:"`forceAtomic` is not supported on fallback to `eth_sendTransaction`."}));let A=[];for(let F of N){try{let Z=await AX($,{account:K,chain:Y,data:F.data,to:F.to,value:F.value?B1(F.value):void 0});A.push({status:"fulfilled",value:Z})}catch(Z){A.push({reason:Z,status:"rejected"})}if(G>0)await new Promise((Z)=>setTimeout(Z,G))}if(A.every((F)=>F.status==="rejected"))throw A[0].reason;let q=A.map((F)=>{if(F.status==="fulfilled")return F.value;return u_});return{id:V1([...q,X$(Y.id,{size:32}),h_])}}throw NX(w,{...J,account:K,chain:J.chain})}}async function Tz($,J){async function Q(O){if(O.endsWith(h_.slice(2))){let w=z0(Uz(O,-64,-32)),M=Uz(O,0,-64).slice(2).match(/.{1,64}/g),A=await Promise.all(M.map((F)=>u_.slice(2)!==F?$.request({method:"eth_getTransactionReceipt",params:[`0x${F}`]},{dedupe:!0}):void 0)),q=(()=>{if(A.some((F)=>F===null))return 100;if(A.every((F)=>F?.status==="0x1"))return 200;if(A.every((F)=>F?.status==="0x0"))return 500;return 600})();return{atomic:!1,chainId:F1(w),receipts:A.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:g_[O.status]}))??[],statusCode:K,status:V,version:W}}async function ti($,J={}){let{account:Q=$.account,chainId:Y}=J,X=Q?U4(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 ai($){return await $.request({method:"wallet_getPermissions"},{dedupe:!0})}function si($,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 Rz($,J){let{account:Q=$.account,chainId:Y,nonce:X}=J;if(!Q)throw new l1({docsPath:"/docs/eip7702/prepareAuthorization"});let G=U4(Q),W=(()=>{if(!J.executor)return;if(J.executor==="self")return J.executor;return U4(J.executor)})(),D={address:J.contractAddress??J.address,chainId:Y,nonce:X};if(typeof D.chainId>"u")D.chainId=$.chain?.id??await x$($,t1,"getChainId")({});if(typeof D.nonce>"u"){if(D.nonce=await x$($,Az,"getTransactionCount")({address:G.address,blockTag:"pending"}),W==="self"||W?.address&&si(W.address,G.address))D.nonce+=1}return D}async function ei($){return(await $.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map((Q)=>Hi(Q))}async function $o($,J){return $.request({method:"wallet_requestPermissions",params:[J]},{retryCount:0})}class m_ extends m{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 Cz=new Map,l_=new Map,bU$=0;function $Y($,J,Q){let Y=++bU$,X=()=>Cz.get($)||[],G=()=>{let N=X().filter((w)=>w.id!==Y);if(N.length===0){Cz.delete($),l_.delete($);return}Cz.set($,N)},W=()=>{let O=X();if(!O.some((w)=>w.id===Y))return;let N=l_.get($);if(O.length===1&&N){let w=N();if(w instanceof Promise)w.catch(()=>{})}G()},D=X();if(Cz.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")l_.set($,K);return W}async function SK($,{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 Pz($,{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 SK(V);let K=async()=>{if(!X)return;await $({unpoll:G}),await SK(Y),K()};K()})(),G}function j7(){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 SK(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 vz($,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}=j7(),M,A=$Y(K,{resolve:N,reject:w},(q)=>{let F=Pz(async()=>{let Z=(E)=>{clearTimeout(M),F(),E(),A()};try{let E=await JY(async()=>{let B=await x$($,Tz,"getCallsStatus")({id:Q});if(V&&B.status==="failure")throw new m_(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(()=>{A(),clearTimeout(M),w(new Jo({id:Q}))},D):void 0,await O}class Jo extends m{constructor({id:$}){super(`Timed out while waiting for call bundle with id "${$}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}async function Qo($,J){let{chain:Q=$.chain}=J,Y=J.timeout??Math.max((Q?.blockTime??0)*3,5000),X=await x$($,_z,"sendCalls")(J);return await x$($,vz,"waitForCallsStatus")({...J,id:X.id,timeout:Y})}async function kz($,{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||Fz)(X);if(W.status==="reverted"&&Q)throw new oG({receipt:W});return W}async function Xo($,{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||H7)(O,"getTransaction")}async function xz($,{hash:J}){let Q=await $.request({method:"eth_getTransactionReceipt",params:[J]},{dedupe:!0});if(!Q)throw new ZK({hash:J});return($.chain?.formatters?.transactionReceipt?.format||Fz)(Q,"getTransactionReceipt")}var gU$=new Map,yU$=new Map;function Yo($){let J=(X,G)=>({clear:()=>G.delete(X),get:()=>G.get(X),set:(W)=>G.set(X,W)}),Q=J($,gU$),Y=J($,yU$);return{clear:()=>{Q.clear(),Y.clear()},promise:Q,response:Y}}async function Go($,{cacheKey:J,cacheTime:Q=Number.POSITIVE_INFINITY}){let Y=Yo(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 hU$=($)=>`blockNumber.${$}`;async function Wo($,{cacheTime:J=$.cacheTime}={}){let Q=await Go(()=>$.request({method:"eth_blockNumber"}),{cacheKey:hU$($.uid),cacheTime:J});return BigInt(Q)}function Do($,{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)=>Pz(async()=>{try{let M=await x$($,Wo,"getBlockNumber")({cacheTime:0});if(V!==void 0){if(M===V)return;if(M-V>1&&Q)for(let A=V+1n;A<M;A++)w.onBlockNumber(A,V),V=A}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,A=()=>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(A=F,!M)A()}catch(q){X?.(q)}})(),()=>A()})})()}async function Vo($,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,A=!1,q,F,{promise:Z,resolve:E,reject:B}=j7(),L=V?setTimeout(()=>{F?.(),q?.(),B(new eS({hash:X}))},V):void 0;return q=$Y(K,{onReplaced:G,resolve:E,reject:B},async(j)=>{if(M=await x$($,xz,"getTransactionReceipt")({hash:X}).catch(()=>{return}),M&&Y<=1){clearTimeout(L),j.resolve(M),q?.();return}F=x$($,Do,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:O,async onBlockNumber(T){let v=(y)=>{clearTimeout(L),F?.(),y(),q?.()},x=T;if(A)return;try{if(M){if(Y>1&&(!M.blockNumber||x-M.blockNumber+1n<Y))return;v(()=>j.resolve(M));return}if(Q&&!N)A=!0,await JY(async()=>{if(N=await x$($,Xo,"getTransaction")({hash:X}),N.blockNumber)x=N.blockNumber},{delay:D,retryCount:W}),A=!1;if(M=await x$($,xz,"getTransactionReceipt")({hash:X}),Y>1&&(!M.blockNumber||x-M.blockNumber+1n<Y))return;v(()=>j.resolve(M))}catch(y){if(y instanceof LK||y instanceof ZK){if(!N){A=!1;return}try{w=N,A=!0;let R=await JY(()=>x$($,e0,"getBlock")({blockNumber:x,includeTransactions:!0}),{delay:D,retryCount:W,shouldRetry:({error:Y$})=>Y$ instanceof BK});A=!1;let d=R.transactions.find(({from:Y$,nonce:c})=>Y$===w.from&&c===w.nonce);if(!d)return;if(M=await x$($,xz,"getTransactionReceipt")({hash:d.hash}),Y>1&&(!M.blockNumber||x-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";v(()=>{j.onReplaced?.({reason:p,replacedTransaction:w,transaction:d,transactionReceipt:M}),j.resolve(M)})}catch(R){v(()=>j.reject(R))}}else v(()=>j.reject(y))}}})}),Z}var d_=new o6(128);async function fz($,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:A,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?U4(Q):null,v;try{A0(J);let x=await(async()=>{if(J.to)return J.to;if(J.to===null)return;if(W&&W.length>0)return await I7({authorization:W[0]}).catch(()=>{throw new m("`to` is required. Could not infer from `authorizationList`.")});return})();if(T?.type==="json-rpc"||T===null){let y;if(X!==null){if(y=await x$($,t1,"getChainId")({}),Y)L7({currentChainId:y,chain:X})}let R=$.chain?.formatters?.transactionRequest?.format,p=(R||kJ)({...wX(L,{format:R}),accessList:G,account:T,authorizationList:W,blobs:D,chainId:y,data:K?V1([V??"0x",K]):V,gas:O,gasPrice:N,maxFeePerBlobGas:w,maxFeePerGas:M,maxPriorityFeePerGas:A,nonce:q,to:x,type:E,value:B},"sendTransaction"),Y$=d_.get($.uid),c=Y$?"wallet_sendTransaction":"eth_sendTransaction",l=await(async()=>{try{return await $.request({method:c,params:[p]},{retryCount:0})}catch(Z$){if(Y$===!1)throw Z$;let _=Z$;if(_.name==="InvalidInputRpcError"||_.name==="InvalidParamsRpcError"||_.name==="MethodNotFoundRpcError"||_.name==="MethodNotSupportedRpcError")return await $.request({method:"wallet_sendTransaction",params:[p]},{retryCount:0}).then((k)=>{return d_.set($.uid,!0),k}).catch((k)=>{let b=k;if(b.name==="MethodNotFoundRpcError"||b.name==="MethodNotSupportedRpcError")throw d_.set($.uid,!1),_;throw b});throw _}})(),V$=await x$($,Vo,"waitForTransactionReceipt")({checkReplacement:!1,hash:l,pollingInterval:F,timeout:j});if(Z&&V$.status==="reverted")throw new oG({receipt:V$});return V$}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 x$($,t1,"getChainId")({})})();v={address:T.address,chainId:Y$}}let y=await x$($,zX,"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:A,nonce:q,nonceManager:T.nonceManager,parameters:[...EK,"sidecars"],type:E,value:B,...L,to:x}),R=X?.serializers?.transaction,d=await T.signTransaction(y,{serializer:R});return await x$($,kz,"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(x){if(x instanceof $J)throw x;if(v&&!(x instanceof oG))T?.nonceManager?.reset(v);throw NX(x,{...J,account:T,chain:J.chain||void 0})}}async function Ko($,J){let{id:Q}=J;await $.request({method:"wallet_showCallsStatus",params:[Q]});return}async function Uo($,J){let{account:Q=$.account}=J;if(!Q)throw new l1({docsPath:"/docs/eip7702/signAuthorization"});let Y=U4(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 Rz($,J);return Y.signAuthorization(X)}async function Oo($,{account:J=$.account,message:Q}){if(!J)throw new l1({docsPath:"/docs/actions/wallet/signMessage"});let Y=U4(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 No($,J){let{account:Q=$.account,chain:Y=$.chain,...X}=J;if(!Q)throw new l1({docsPath:"/docs/actions/wallet/signTransaction"});let G=U4(Q);A0({account:G,...J});let W=await x$($,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 p_ extends m{constructor({domain:$}){super(`Invalid domain "${i4($)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class n_ extends m{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 c_ extends m{constructor({type:$}){super(`Struct type "${$}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function wo($){let{domain:J={},message:Q,primaryType:Y}=$,X={EIP712Domain:gz({domain:J}),...$.types};bz({domain:J,message:Q,primaryType:Y,types:X});let G=["0x1901"];if(J)G.push(uU$({domain:J,types:X}));if(Y!=="EIP712Domain")G.push(Mo({data:Q,primaryType:Y,types:X}));return D1(V1(G))}function uU$({domain:$,types:J}){return Mo({data:$,primaryType:"EIP712Domain",types:J})}function Mo({data:$,primaryType:J,types:Q}){let Y=Ho({data:$,primaryType:J,types:Q});return D1(Y)}function Ho({data:$,primaryType:J,types:Q}){let Y=[{type:"bytes32"}],X=[mU$({primaryType:J,types:Q})];for(let G of Q[J]){let[W,D]=Ao({types:Q,name:G.name,type:G.type,value:$[G.name]});Y.push(W),X.push(D)}return e9(Y,X)}function mU$({primaryType:$,types:J}){let Q=m1(lU$({primaryType:$,types:J}));return D1(Q)}function lU$({primaryType:$,types:J}){let Q="",Y=zo({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 zo({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])zo({primaryType:G.type,types:J},Q);return Q}function Ao({types:$,name:J,type:Q,value:Y}){if($[Q]!==void 0)return[{type:"bytes32"},D1(Ho({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)=>Ao({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 Io($){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 bz($){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(Oz);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(Li);if(M){let[q,F]=M;if(F&&O4(N)!==Number.parseInt(F,10))throw new H_({expectedSize:Number.parseInt(F,10),givenSize:O4(N)})}let A=X[O];if(A)dU$(O),G(A,N)}};if(X.EIP712Domain&&J){if(typeof J!=="object")throw new p_({domain:J});G(X.EIP712Domain,J)}if(Y!=="EIP712Domain")if(X[Y])G(X[Y],Q);else throw new n_({primaryType:Y,types:X})}function gz({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 dU$($){if($==="address"||$==="bool"||$==="string"||$.startsWith("bytes")||$.startsWith("uint")||$.startsWith("int"))throw new c_({type:$})}async function qo($,J){let{account:Q=$.account,domain:Y,message:X,primaryType:G}=J;if(!Q)throw new l1({docsPath:"/docs/actions/wallet/signTypedData"});let W=U4(Q),D={EIP712Domain:gz({domain:Y}),...J.types};if(bz({domain:Y,message:X,primaryType:G,types:D}),W.signTypedData)return W.signTypedData({domain:Y,message:X,primaryType:G,types:D});let V=Io({domain:Y,message:X,primaryType:G,types:D});return $.request({method:"eth_signTypedData_v4",params:[W.address,V]},{retryCount:0})}async function Lo($,{id:J}){await $.request({method:"wallet_switchEthereumChain",params:[{chainId:X$(J)}]},{retryCount:0})}async function Zo($,J){return await $.request({method:"wallet_watchAsset",params:J},{retryCount:0})}var Bo={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."},Fo={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},jo={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};function Eo($,J={}){if(typeof J.size<"u")i6($,{size:J.size});let Q=x4($,J);return B1(Q,J)}function So($,J={}){let Q=$;if(typeof J.size<"u")i6(Q,{size:J.size}),Q=z0(Q);if(Q.length>1||Q[0]>1)throw new J_(Q);return Boolean(Q[0])}function fJ($,J={}){if(typeof J.size<"u")i6($,{size:J.size});let Q=x4($,J);return F1(Q,J)}function _o($,J={}){let Q=$;if(typeof J.size<"u")i6(Q,{size:J.size}),Q=z0(Q,{dir:"right"});return new TextDecoder().decode(Q)}function Ro($,J){let Q=typeof J==="string"?w1(J):J,Y=A7(Q);if(O4(Q)===0&&$.length>0)throw new s9;if(O4(J)&&O4(J)<32)throw new U_({data:typeof J==="string"?J:x4(J),params:$,size:O4(J)});let X=0,G=[];for(let W=0;W<$.length;++W){let D=$[W];Y.setPosition(X);let[V,K]=E7(Y,D,{staticPosition:0});X+=K,G.push(V)}return G}function E7($,J,{staticPosition:Q}){let Y=Nz(J.type);if(Y){let[X,G]=Y;return nU$($,{...J,type:G},{length:X,staticPosition:Q})}if(J.type==="tuple")return rU$($,J,{staticPosition:Q});if(J.type==="address")return pU$($);if(J.type==="bool")return cU$($);if(J.type.startsWith("bytes"))return iU$($,J,{staticPosition:Q});if(J.type.startsWith("uint")||J.type.startsWith("int"))return oU$($,J);if(J.type==="string")return tU$($,{staticPosition:Q});throw new A_(J.type,{docsPath:"/docs/contract/decodeAbiParameters"})}var To=32,i_=32;function pU$($){let J=$.readBytes(32);return[uQ(x4(q_(J,-20))),32]}function nU$($,J,{length:Q,staticPosition:Y}){if(!Q){let W=fJ($.readBytes(i_)),D=Y+W,V=D+To;$.setPosition(D);let K=fJ($.readBytes(To)),O=_K(J),N=0,w=[];for(let M=0;M<K;++M){$.setPosition(V+(O?M*32:N));let[A,q]=E7($,J,{staticPosition:V});N+=q,w.push(A)}return $.setPosition(Y+32),[w,32]}if(_K(J)){let W=fJ($.readBytes(i_)),D=Y+W,V=[];for(let K=0;K<Q;++K){$.setPosition(D+K*32);let[O]=E7($,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]=E7($,J,{staticPosition:Y+X});X+=V,G.push(D)}return[G,X]}function cU$($){return[So($.readBytes(32),{size:32}),32]}function iU$($,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),[x4(V),32]}return[x4($.readBytes(Number.parseInt(X,10),32)),32]}function oU$($,J){let Q=J.type.startsWith("int"),Y=Number.parseInt(J.type.split("int")[1]||"256",10),X=$.readBytes(32);return[Y>48?Eo(X,{signed:Q}):fJ(X,{signed:Q}),32]}function rU$($,J,{staticPosition:Q}){let Y=J.components.length===0||J.components.some(({name:W})=>!W),X=Y?[]:{},G=0;if(_K(J)){let W=fJ($.readBytes(i_)),D=Q+W;for(let V=0;V<J.components.length;++V){let K=J.components[V];$.setPosition(D+G);let[O,N]=E7($,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]=E7($,D,{staticPosition:Q});X[Y?W:D?.name]=V,G+=K}return[X,G]}function tU$($,{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=_o(z0(G));return $.setPosition(J+32),[W,32]}function _K($){let{type:J}=$;if(J==="string")return!0;if(J==="bytes")return!0;if(J.endsWith("[]"))return!0;if(J==="tuple")return $.components?.some(_K);let Q=Nz($.type);if(Q&&_K({...$,type:Q[1]}))return!0;return!1}function Co($){let{abi:J,data:Q,cause:Y}=$,X=mQ(Q,0,4);if(X==="0x")throw new s9({cause:Y});let W=[...J||[],Fo,jo].find((D)=>D.type==="error"&&X===F7(xJ(D)));if(!W)throw new FK(X,{docsPath:"/docs/contract/decodeErrorResult",cause:Y});return{abiItem:W,args:"inputs"in W&&W.inputs&&W.inputs.length>0?Ro(W.inputs,mQ(Q,4)):void 0,errorName:W.name}}function o_({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 r_ extends m{constructor($,{abi:J,args:Q,contractAddress:Y,docsPath:X,functionName:G,sender:W}){let D=Ez({abi:J,args:Q,name:G}),V=D?o_({abiItem:D,args:Q,includeFunctionName:!1,includeName:!1}):void 0,K=D?xJ(D,{includeName:!0}):void 0,O=iG({address:Y&&wi(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 t_ extends m{constructor({abi:$,data:J,functionName:Q,message:Y,cause:X}){let G,W,D,V;if(J&&J!=="0x")try{W=Co({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=Bo[M]}else{let M=O?xJ(O,{includeName:!0}):void 0,A=O&&w?o_({abiItem:O,args:w,includeFunctionName:!1,includeName:!1}):void 0;D=[M?`Error: ${M}`:"",A&&A!=="()"?` ${[...Array(N?.length??0).keys()].map(()=>" ").join("")}${A}`:""]}}catch(O){G=O}else if(Y)V=Y;let K;if(G instanceof FK)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 a_ extends m{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 s_ extends m{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 aU$=3;function Po($,{abi:J,address:Q,args:Y,docsPath:X,functionName:G,sender:W}){let D=$ instanceof s_?$:$ instanceof m?$.walk((A)=>("data"in A))||$.walk():{},{code:V,data:K,details:O,message:N,shortMessage:w}=D,M=(()=>{if($ instanceof s9)return new a_({functionName:G,cause:$});if([aU$,gQ.code].includes(V)&&(K||O||N||w)||V===VX.code&&O==="execution reverted"&&K)return new t_({abi:J,data:typeof K==="object"?K.data:K,functionName:G,message:D instanceof o9?O:w??N,cause:$});return $})();return new r_(M,{abi:J,args:Y,contractAddress:Q,docsPath:X,functionName:G,sender:W})}async function QY($,J){return QY.internal($,AX,"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?U4(D):null,M=Sz({abi:W,args:K,functionName:O});try{return await x$(Q,Y,X)({data:M,to:V,account:w,...N})}catch(A){throw Po(A,{abi:W,address:V,args:K,docsPath:"/docs/contract/writeContract",functionName:O,sender:w?.address})}}$.internal=J})(QY||(QY={}));async function vo($,J){return QY.internal($,fz,"sendTransactionSync",J)}function ko($){return{addChain:(J)=>Ai($,J),deployContract:(J)=>ui($,J),fillTransaction:(J)=>Wz($,J),getAddresses:()=>mi($),getCallsStatus:(J)=>Tz($,J),getCapabilities:(J)=>ti($,J),getChainId:()=>t1($),getPermissions:()=>ai($),prepareAuthorization:(J)=>Rz($,J),prepareTransactionRequest:(J)=>zX($,J),requestAddresses:()=>ei($),requestPermissions:(J)=>$o($,J),sendCalls:(J)=>_z($,J),sendCallsSync:(J)=>Qo($,J),sendRawTransaction:(J)=>Bz($,J),sendRawTransactionSync:(J)=>kz($,J),sendTransaction:(J)=>AX($,J),sendTransactionSync:(J)=>fz($,J),showCallsStatus:(J)=>Ko($,J),signAuthorization:(J)=>Uo($,J),signMessage:(J)=>Oo($,J),signTransaction:(J)=>No($,J),signTypedData:(J)=>qo($,J),switchChain:(J)=>Lo($,J),waitForCallsStatus:(J)=>vz($,J),watchAsset:(J)=>Zo($,J),writeContract:(J)=>QY($,J),writeContractSync:(J)=>vo($,J)}}function e_($){let{key:J="wallet",name:Q="Wallet Client",transport:Y}=$;return Ki({...$,key:J,name:Q,transport:Y,type:"walletClient"}).extend(ko)}class $T extends m{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 JT=new Map;function xo({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:A}=O[M];A?.([w[M],w])}}).catch((w)=>{for(let M=0;M<O.length;M++){let{reject:A}=O[M];A?.(w)}})},W=()=>JT.delete(J),D=()=>V().map(({args:O})=>O),V=()=>JT.get(J)||[],K=(O)=>JT.set(J,[...V(),O]);return{flush:W,async schedule(O){let{promise:N,resolve:w,reject:M}=j7();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 fo($,{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 sU$(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var QT=sU$();function bo($,J={}){let{url:Q,headers:Y}=eU$($);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 A=await fo(async({signal:F})=>{let Z={...O,body:Array.isArray(G)?i4(G.map((j)=>({jsonrpc:"2.0",id:j.id??QT.take(),...j}))):i4({jsonrpc:"2.0",id:G.id??QT.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 Jz({body:G,url:Q}),timeout:K,signal:!0});if(V)await V(A);let q;if(A.headers.get("Content-Type")?.startsWith("application/json"))q=await A.json();else{q=await A.text();try{q=JSON.parse(q||"{}")}catch(F){if(A.ok)throw F;q={error:q}}}if(!A.ok){if(typeof q.error?.code==="number"&&typeof q.error?.message==="string")return q;throw new DX({body:G,details:i4(q.error)||A.statusText,headers:A.headers,status:A.status,url:Q})}return q}catch(A){if(M?.aborted)throw s0(M);if(bQ(A))throw A;if(A instanceof DX)throw A;if(A instanceof Jz)throw A;throw new DX({body:G,cause:A,url:Q})}}}}function eU$($){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 yz=new o6(8192);function go($,{enabled:J=!0,id:Q}){if(!J||!Q)return $();if(yz.get(Q))return yz.get(Q);let Y=$().finally(()=>yz.delete(Q));return yz.set(Q,Y),Y}function yo($,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?JO$(`${K}.${i4(Q)}`):void 0;return go(()=>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 rG.code:throw new rG(M);case tG.code:throw new tG(M);case aG.code:throw new aG(M,{method:Q.method});case sG.code:throw new sG(M);case gQ.code:throw new gQ(M);case VX.code:throw new VX(M);case eG.code:throw new eG(M);case $7.code:throw new $7(M);case J7.code:throw new J7(M);case KX.code:throw new KX(M,{method:Q.method});case r9.code:throw new r9(M);case Q7.code:throw new Q7(M);case t9.code:throw new t9(M);case X7.code:throw new X7(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 UX.code:throw new UX(M);case V7.code:throw new V7(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 OX.code:throw new OX(M);case 5000:throw new t9(M);case w7.code:throw new w7(M);default:if(w instanceof m)throw w;throw new $_(M)}}},{delay:({count:w,error:M})=>{if(M&&M instanceof DX){let A=M?.headers?.get("Retry-After");if(A?.match(/\d/))return Number.parseInt(A,10)*1000}return~~(1<<w)*W},retryCount:D,signal:V,shouldRetry:({error:w})=>$O$(w)}),{enabled:X,id:N})}}function $O$($){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 JO$($,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 ho({key:$,methods:J,name:Q,request:Y,retryCount:X=3,retryDelay:G=150,timeout:W,type:D},V){let K=aH();return{config:{key:$,methods:J,name:Q,request:Y,retryCount:X,retryDelay:G,timeout:W,type:D},request:yo(Y,{methods:J,retryCount:X,retryDelay:G,uid:K}),value:V}}var QO$=0,uo=new WeakMap;function XO$($){if(!$)return"default";let J=uo.get($);if(J!==void 0)return J;let Q=QO$++;return uo.set($,Q),Q}function XT($,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:A})=>{let{batchSize:q=1000,wait:F=0}=typeof Q==="object"?Q:{},Z=J.retryCount??M,E=A??J.timeout??1e4,B=$||w?.rpcUrls.default.http[0];if(!B)throw new $T;let L=bo(B,{fetchFn:Y,fetchOptions:X,onRequest:V,onResponse:K,timeout:E});return ho({key:G,methods:W,name:D,async request({method:j,params:T},v){let x={method:j,params:T},y=v?.signal?{signal:v.signal}:void 0,{schedule:R}=xo({id:`${B}.${XO$(v?.signal)}`,wait:F,shouldSplitBatch(c){return c.length>q},fn:(c)=>L.request({body:c,fetchOptions:y}),sort:(c,l)=>c.id-l.id}),d=async(c)=>Q?R(c):[await L.request({body:c,fetchOptions:y})],[{error:p,result:Y$}]=await d(x);if(N)return{error:p,result:Y$};if(p)throw new o9({body:x,error:p,url:B});return Y$},retryCount:Z,retryDelay:O,timeout:E,type:"http"},{fetchOptions:X,url:B})}}$X();function mo($){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 lo({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 z6.Signature(B1($),B1(J)).toCompactHex()}${G===0?"1b":"1c"}`;if(Q==="hex")return W;return w1(W)}var YT=!1;async function bJ({hash:$,privateKey:J,to:Q="object"}){let{r:Y,s:X,recovery:G}=z6.sign($.slice(2),J.slice(2),{lowS:!0,extraEntropy:u1(YT,{strict:!1})?w1(YT):YT}),W={r:X$(Y,{size:32}),s:X$(X,{size:32}),v:G?28n:27n,yParity:G};return(()=>{if(Q==="bytes"||Q==="hex")return lo({...W,to:Q});return W})()}async function po($){let{chainId:J,nonce:Q,privateKey:Y,to:X="object"}=$,G=$.contractAddress??$.address,W=await bJ({hash:Hz({address:G,chainId:J,nonce:Q}),privateKey:Y,to:X});if(X==="object")return{address:G,chainId:J,nonce:Q,...W};return W}var no=`\x19Ethereum Signed Message:
|
|
168
168
|
`;function co($){let J=(()=>{if(typeof $==="string")return HX($);if(typeof $.raw==="string")return $.raw;return x4($.raw)})(),Q=HX(`${no}${O4(J)}`);return V1([Q,J])}function io($,J){return D1(co($),J)}async function oo({message:$,privateKey:J}){return await bJ({hash:io($),privateKey:J,to:"hex"})}function ro($){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",...S7({},G)])}return J}function to($){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 q7({chainId:Y})}hz($)}function ao($){let{blobVersionedHashes:J}=$;if(J){if(J.length===0)throw new jK;for(let Q of J){let Y=O4(Q),X=F1(mQ(Q,0,1));if(Y!==32)throw new k_({hash:Q,size:Y});if(X!==qz)throw new x_({hash:Q,version:X})}}hz($)}function hz($){let{chainId:J,maxPriorityFeePerGas:Q,maxFeePerGas:Y,to:X}=$;if(J<=0)throw new q7({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 so($){let{chainId:J,maxPriorityFeePerGas:Q,gasPrice:Y,maxFeePerGas:X,to:G}=$;if(J<=0)throw new q7({chainId:J});if(G&&!S4(G))throw new y4({address:G});if(Q||X)throw new m("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(Y&&Y>z7)throw new a0({maxFeePerGas:Y})}function eo($){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 q7({chainId:J});if(Q||X)throw new m("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(Y&&Y>z7)throw new a0({maxFeePerGas:Y})}function TK($){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 aS({storageKey:X[G]});if(!S4(Y,{strict:!1}))throw new y4({address:Y});J.push([Y,X])}return J}function $r($,J){let Q=Zz($);if(Q==="eip1559")return WO$($,J);if(Q==="eip2930")return DO$($,J);if(Q==="eip4844")return GO$($,J);if(Q==="eip7702")return YO$($,J);return VO$($,J)}function YO$($,J){let{authorizationList:Q,chainId:Y,gas:X,nonce:G,to:W,value:D,maxFeePerGas:V,maxPriorityFeePerGas:K,accessList:O,data:N}=$;to($);let w=TK(O),M=ro(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,...S7($,J)])])}function GO$($,J){let{chainId:Q,gas:Y,nonce:X,to:G,value:W,maxFeePerBlobGas:D,maxFeePerGas:V,maxPriorityFeePerGas:K,accessList:O,data:N}=$;ao($);let{blobVersionedHashes:w,sidecars:M}=$;if($.blobs&&(typeof w>"u"||typeof M>"u")){let B=typeof $.blobs[0]==="string"?$.blobs:$.blobs.map((T)=>x4(T)),L=$.kzg,j=Z7({blobs:B,kzg:L});if(typeof w>"u")w=Iz({commitments:j});if(typeof M>"u"){let T=B7({blobs:B,commitments:j,kzg:L});M=Lz({blobs:B,commitments:j,proofs:T})}}let A=TK(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",A,D?X$(D):"0x",w??[],...S7($,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 WO$($,J){let{chainId:Q,gas:Y,nonce:X,to:G,value:W,maxFeePerGas:D,maxPriorityFeePerGas:V,accessList:K,data:O}=$;hz($);let N=TK(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,...S7($,J)];return I0(["0x02",lQ(w)])}function DO$($,J){let{chainId:Q,gas:Y,data:X,nonce:G,to:W,value:D,accessList:V,gasPrice:K}=$;so($);let O=TK(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,...S7($,J)];return I0(["0x01",lQ(N)])}function VO$($,J){let{chainId:Q=0,gas:Y,data:X,nonce:G,to:W,value:D,gasPrice:V}=$;eo($);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 rS({v:J.v});return M})(),N=z0(J.r),w=z0(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 S7($,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=z0(Q.r),W=z0(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 Jr($){let{privateKey:J,transaction:Q,serializer:Y=$r}=$,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 Qr($){let{privateKey:J,...Q}=$;return await bJ({hash:wo(Q),privateKey:J,to:"hex"})}function GT($,J={}){let{nonceManager:Q}=J,Y=m1(z6.getPublicKey($.slice(2),!1)),X=wz(Y);return{...mo({address:X,nonceManager:Q,async sign({hash:W}){return bJ({hash:W,privateKey:$,to:"hex"})},async signAuthorization(W){return po({...W,privateKey:$})},async signMessage({message:W}){return oo({message:W,privateKey:$})},async signTransaction(W,{serializer:D}={}){return Jr({privateKey:$,transaction:W,serializer:D})},async signTypedData(W){return Qr({...W,privateKey:$})}}),publicKey:Y,source:"privateKey"}}function uz($){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 WT=uz({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 DT=uz({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 VT=null;var KO$={privateKeyToAccount:GT,createWalletClient:e_,http:XT,createMonacoSDK:nS,sei:WT,seiTestnet:DT};function UO$($,J=KO$){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(!VT){let J=$??P8();VT=UO$(J)}return VT}async function C$($){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 Xr($,J){if(J.network==="mainnet")return;$.registerTool("get_faucet_info",{description:"Get the authenticated wallet's faucet quota: remaining requests in the rolling 24h window, when the next request becomes available, and the 5 most recent faucet requests. Check this before request_faucet to avoid rate-limit errors. Only available on non-mainnet networks (development, staging, local).",inputSchema:{}},async()=>{let Y=await(await C$()).faucet.getInfo();return A$(Y)})}function Yr($,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 C$(),G=Y.getAuthState()?.accessToken;if(!G)return JJ("No access token available. Please authenticate first.");let W=DV(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 Gr($,J){Yr($,J),Xr($,J)}function Wr($){$.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:z.object({tradingPairId:z.string().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:J})=>{let Y=await(await C$()).fees.getMyFeeTier({tradingPairId:J});return A$(Y)})}function Dr($){$.registerTool("simulate_fees",{description:"Simulate the fees for an order before placing it. Returns Monaco protocol fees, application fees, and total amounts.",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),side:z.enum(["BUY","SELL"]).describe("Order side"),price:z.string().describe("Price per unit as a decimal string"),quantity:z.string().describe("Quantity to trade as a decimal string")})},async({tradingPairId:J,side:Q,price:Y,quantity:X})=>{let W=await(await C$()).fees.simulateFees({tradingPairId:J,side:Q,price:Y,quantity:X});return A$(W)})}function Vr($){Dr($),Wr($)}function Kr($){$.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),interval:z.enum(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:z.number().optional().describe("Start time as Unix timestamp (seconds)"),endTime:z.number().optional().describe("End time as Unix timestamp (seconds)"),limit:z.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 Ur($){$.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID")})},async({tradingPairId:J})=>{let Y=await a1().market.getMarketMetadata(J);return A$(Y)})}function Or($){$.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:z.object({symbol:z.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 Nr($){$.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:z.object({page:z.number().optional().describe("Page number (starts from 1)"),limit:z.number().optional().describe("Number of items per page (max 100)"),marketType:z.string().optional().describe("Filter by market type"),baseToken:z.string().optional().describe("Filter by base token"),quoteToken:z.string().optional().describe("Filter by quote token"),isActive:z.boolean().optional().describe("Filter by active status")})},async(J)=>{let Y=await a1().market.getPaginatedTradingPairs(J);return A$(Y)})}function wr($){Nr($),Or($),Kr($),Ur($)}function Mr($){$.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),depth:z.number().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:z.enum(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:z.number().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:z.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 Hr($){Mr($)}function zr($){$.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:z.object({})},async()=>{let Q=await(await C$()).pitpass.getMyTraderCode();return A$(Q)})}function Ar($){$.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:z.object({})},async()=>{let Q=await(await C$()).pitpass.getRewardsBalance();return A$(Q)})}function Ir($){$.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:z.object({code:z.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 qr($){$.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:z.object({token:z.string().describe("Reward token contract address (0x-prefixed EVM address) to transfer."),amount:z.string().describe("Amount to transfer in RAW atomic units of the token (positive integer string).")})},async({token:J,amount:Q})=>{let X=await(await C$()).pitpass.transferRewards({token:J,amount:Q});return A$(X)})}function Lr($){Ir($)}function Zr($){zr($),Ar($),qr($)}function Br($){$.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:z.object({assetId:z.string().describe("The asset UUID")})},async({assetId:J})=>{let Y=await(await C$()).profile.getUserBalanceByAssetId(J);return A$(Y)})}function Fr($){$.registerTool("get_balances",{description:"Get the authenticated user's token balances with pagination.",inputSchema:z.object({limit:z.number().optional().describe("Number of items to return (default: 20)"),offset:z.number().optional().describe("Number of items to skip (default: 0)")})},async({limit:J,offset:Q})=>{let X=await(await C$()).profile.getUserBalances({limit:J,offset:Q});return A$(X)})}function jr($){$.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history) with pagination.",inputSchema:z.object({page:z.number().int().min(1).optional().describe("Page number (starts from 1, default: 1)"),limit:z.number().int().min(1).max(100).optional().describe("Items per page (default: 20, max: 100)"),entryType:z.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:z.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:z.string().uuid().optional().describe("Filter by asset ID (UUID)")})},async({page:J,limit:Q,entryType:Y,transactionType:X,assetId:G})=>{let D=await(await C$()).profile.getPaginatedUserMovements({page:J,limit:Q,entryType:Y,transactionType:X,assetId:G});return A$(D)})}function Er($){$.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 C$()).profile.getProfile();return A$(Q)})}function Sr($){Er($),Fr($),Br($),jr($)}var OO$="https://docs.0xmonaco.com/mcp",NO$="SearchMonacoDocs",mz=null;async function _r($,J,Q){let Y=await fetch(OO$,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...mz?{"Mcp-Session-Id":mz}:{}},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)mz=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 wO$(){if(mz)return;await _r("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:Cw.version}},0)}async function MO$($){return await wO$(),(await _r("tools/call",{name:NO$,arguments:{query:$}},1))?.result}function Tr($){$.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:z.object({query:z.string().describe("The search query")})},async({query:J})=>{try{let Q=await MO$(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 Rr($){Tr($)}function Cr($){$.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),page:z.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:z.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 Pr($){Cr($)}function vr($){$.registerTool("batch_cancel_all_orders",{description:"Cancel all active orders, optionally filtered to a specific trading pair.",inputSchema:z.object({tradingPairId:z.string().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:J})=>{let Y=await(await C$()).trading.batchCancelAll(J);return A$(Y)})}function kr($){$.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request.",inputSchema:z.object({orderIds:z.array(z.string()).describe("Array of order IDs to cancel")})},async({orderIds:J})=>{let Y=await(await C$()).trading.batchCancel(J);return A$(Y)})}function xr($){$.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:z.object({tradingPairId:z.string().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:z.number().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:J,slippageToleranceBps:Q})=>{let X=await(await C$()).positions.batchCloseAllPositions({tradingPairId:J,slippageToleranceBps:Q});return A$(X)})}function fr($){$.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:z.object({orderId:z.string().describe("The order ID to cancel")})},async({orderId:J})=>{let Y=await(await C$()).trading.cancelOrder(J);return A$(Y)})}function br($){$.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:z.object({orderId:z.string().describe("The order ID to look up")})},async({orderId:J})=>{let Y=await(await C$()).trading.getOrder(J);return A$(Y)})}var HO$=z.object({tradingPairId:z.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:z.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:z.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:z.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:z.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:z.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:z.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),zO$=z.object({applicationName:z.string().nullable().optional(),applicationTakerFee:z.string(),applicationTakerFeeBps:z.number(),buyOrderLockAmount:z.string().nullable().optional(),makerTotalReceipt:z.string(),monacoMakerRebate:z.string(),monacoMakerRebateBps:z.number(),monacoMakerRebateBpsExact:z.string(),monacoTakerFee:z.string(),monacoTakerFeeBps:z.number(),monacoTakerFeeBpsExact:z.string(),notional:z.string(),takerTotalPayment:z.string(),totalTakerFees:z.string(),maxQuantity:z.string().nullable(),maxQuantityRaw:z.string().nullable(),slippageToleranceBps:z.number().nullable()}),AO$=z.object({tradingPairId:z.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),gr=z.object({tierLevel:z.number().int(),minVolumeThreshold:z.string(),makerFeeBps:z.string(),takerFeeBps:z.string()}),IO$=z.object({currentTierLevel:z.number().int(),weightedVolume14d:z.string(),spotVolume14d:z.string(),perpVolume14d:z.string(),volumeToNextTier:z.string().nullable().optional(),nextTierLevel:z.number().int().nullable().optional(),feeSchedule:z.array(gr)});var yr=z.object({token:z.string(),available:z.string()}),qO$=z.object({balances:z.array(yr)}),LO$=z.object({code:z.string(),createdAt:z.string()}),ZO$=z.object({code:z.string()}),BO$=z.object({token:z.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:z.string().trim().min(1,"amount is required").refine(($)=>/^\d+$/.test($)&&BigInt($)>0n,"amount must be a positive integer string")}),FO$=z.object({rewardsBalance:z.string(),tradingBalance:z.string()});var RK=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var CK=z.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),dz=z.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),KT=z.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),PK=z.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),hr=z.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),UT=z.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),_7=z.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),M4=z.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"}),T$=z.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),vK=z.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),ur=z.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),kK=z.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),lz=z.object({triggerPrice:M4,orderType:_7,limitPrice:M4.optional(),timeInForce:UT.optional(),slippageToleranceBps:kK.optional(),expiresAt:vK.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"]}),mr=($)=>$?.takeProfit!==void 0||$?.stopLoss!==void 0,OT=($,J)=>J===void 0||J!=="NONE"&&($==="BUY"&&J==="LONG"||$==="SELL"&&J==="SHORT"),Vq1=z.object({tradingPairId:T$,side:CK,quantity:M4,price:M4,options:z.object({tradingMode:dz.optional(),useMasterBalance:z.boolean().optional(),expirationDate:vK.optional(),timeInForce:hr.optional(),marginAccountId:T$.optional(),marginMode:KT.optional(),riskBucketId:T$.optional(),riskBucketCollateral:M4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:PK.optional(),leverage:M4.optional(),reduceOnly:z.boolean().optional(),takeProfit:lz.optional(),stopLoss:lz.optional()}).optional()}).refine(($)=>OT($.side,$.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.reduceOnly===!0||$.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine(($)=>!mr($.options),{message:"Entry-attached TP/SL are no longer supported; create position TP/SL after the position opens",path:["options"]}).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"]}),Kq1=z.object({tradingPairId:T$,side:CK,quantity:M4,options:z.object({tradingMode:dz.optional(),slippageTolerance:ur,marginAccountId:T$.optional(),marginMode:KT.optional(),riskBucketId:T$.optional(),riskBucketCollateral:M4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:PK.optional(),leverage:M4.optional(),reduceOnly:z.boolean().optional(),takeProfit:lz.optional(),stopLoss:lz.optional()}).optional()}).refine(($)=>OT($.side,$.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.reduceOnly===!0||$.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine(($)=>!mr($.options),{message:"Entry-attached TP/SL are no longer supported; create position TP/SL after the position opens",path:["options"]}).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"]}),Uq1=z.object({orderId:T$}),Oq1=z.object({orderId:T$,newOrder:z.object({price:M4.optional(),quantity:M4.optional(),useMasterBalance:z.boolean().optional()})}),Nq1=z.object({status:z.enum(RK).optional(),tradingPairId:T$.optional(),tradingMode:dz.optional(),marginAccountId:T$.optional(),page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),wq1=z.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),Mq1=z.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),jO$=z.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),Hq1=z.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),zq1=z.object({conditionalOrderId:T$}),Aq1=z.object({marginAccountId:T$.optional(),tradingPairId:T$.optional(),state:jO$.optional(),page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),EO$=z.object({tradingPairId:T$,orderType:_7,side:CK,price:M4.optional(),quantity:M4,tradingMode:dz.optional(),slippageTolerance:ur,useMasterBalance:z.boolean().optional(),expirationDate:vK.optional(),timeInForce:hr.optional(),marginAccountId:T$.optional(),marginMode:KT.optional(),riskBucketId:T$.optional(),riskBucketCollateral:M4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:PK.optional(),leverage:M4.optional(),reduceOnly:z.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(($)=>OT($.side,$.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine(($)=>$.tradingMode!=="MARGIN"||$.reduceOnly===!0||$.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),Iq1=z.object({orders:z.array(EO$).min(1,"At least one order is required")}),SO$=z.object({orderId:T$,price:M4.optional(),quantity:M4.optional(),useMasterBalance:z.boolean().optional()}).refine(($)=>$.price!==void 0||$.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),qq1=z.object({orders:z.array(SO$).min(1,"At least one order is required")});var NT=z.object({page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Fq1=NT.extend({state:z.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:T$.optional()}),jq1=z.object({marginAccountId:T$,tradingPairId:T$.optional()}),Eq1=z.object({tradingPairId:T$.optional()}).optional(),Sq1=z.object({asset:z.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),_O$=z.object({asset:z.string().trim().min(1,"Asset cannot be empty"),amount:M4,tradingPairId:T$.optional(),strategyKey:z.string().trim().min(1,"Strategy key cannot be empty").optional()}),pz=z.object({asset:z.string().trim().min(1,"Asset cannot be empty"),amount:M4}),TO$=z.object({tradingPairId:T$,strategyKey:z.string().trim().min(1,"Strategy key cannot be empty").optional()}),RO$=z.array(T$).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),lr=TO$.extend({marginMode:z.literal("ISOLATED").optional(),selectedTradingPairIds:z.never().optional()}),dr=z.object({marginMode:z.literal("CROSS"),selectedTradingPairIds:RO$,strategyKey:z.never().optional()}),CO$=dr.extend({tradingPairId:z.never().optional()}),_q1=z.object({marginAccountId:T$,request:_O$}),Tq1=z.object({request:pz}),Rq1=z.object({request:z.union([pz.merge(lr).strict(),pz.merge(CO$).strict()])}),Cq1=z.object({request:pz}),Pq1=NT.extend({marginAccountId:T$,movementType:z.string().trim().min(1,"Movement type cannot be empty").optional()}),vq1=NT.extend({movementType:z.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),wT=z.object({tradingPairId:T$,side:CK,positionSide:PK.optional(),orderType:_7,price:M4.optional(),quantity:M4,leverage:M4.optional(),reduceOnly:z.boolean().optional()}),MT=($,J)=>{if($.positionSide!==void 0){let Q=$.side==="BUY"?"LONG":"SHORT";if($.positionSide!==Q)J.addIssue({code:z.ZodIssueCode.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if($.reduceOnly!==!0&&$.leverage===void 0)J.addIssue({code:z.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},pr=wT.strict().superRefine(MT),PO$=wT.merge(lr).strict().superRefine(MT),vO$=wT.merge(dr).strict().superRefine(MT).refine(($)=>$.selectedTradingPairIds.includes($.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),kO$=z.union([PO$,vO$]),kq1=z.object({marginAccountId:T$,request:pr}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),xq1=z.object({request:pr}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),fq1=z.object({request:kO$}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var nr=z.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"'}),xO$=31536000000,fO$=946684800000,nz=z.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(fO$,{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()+xO$,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),hq1=z.object({tradingPairId:T$,interval:nr,startTime:nz,endTime:nz}).refine(($)=>$.startTime<$.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),uq1=z.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")'}),bO$=z.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),mq1=z.object({tradingPairId:T$,interval:nr,startTime:nz.optional(),endTime:nz.optional(),limit:bO$}).refine(($)=>{if($.startTime!==void 0&&$.endTime!==void 0)return $.startTime<$.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var lq1=z.object({tradingPairId:T$}),dq1=z.object({query:z.string().min(1,"Search query cannot be empty").optional(),pageSize:z.number().int().min(1).max(100).optional(),page:z.number().int().min(1).optional()}),pq1=z.object({tradingPairId:T$});var ir=z.object({page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),gO$=z.enum(["OPEN","CLOSED","LIQUIDATING"],{message:'Position status must be "OPEN", "CLOSED", or "LIQUIDATING"'}),yO$=z.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),xK=z.object({positionId:T$}),oq1=ir.extend({marginAccountId:T$.optional(),tradingPairId:T$.optional(),status:gO$.optional()});var rq1=xK.extend({request:z.object({closeType:yO$,limitPrice:M4.optional(),slippageToleranceBps:kK.optional(),quantity:M4.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"]}),tq1=z.object({tradingPairId:T$.optional(),slippageToleranceBps:kK.optional()});var aq1=xK.extend({request:z.object({amount:M4,asset:z.string().trim().min(1,"Asset cannot be empty")})}),sq1=xK.extend({request:z.object({amount:M4})}),cr=z.object({triggerPrice:M4,orderType:_7,limitPrice:M4.optional(),quantity:M4.optional(),closePosition:z.boolean().optional(),timeInForce:UT.optional(),slippageToleranceBps:kK.optional(),expiresAt:vK.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"]}).refine(($)=>$.closePosition!==!0||$.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine(($)=>$.quantity!==void 0||$.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),eq1=xK.extend({request:z.object({takeProfit:cr.optional(),stopLoss:cr.optional(),oco:z.boolean().optional()}).refine(($)=>$.takeProfit!==void 0||$.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine(($)=>$.oco!==!0||$.takeProfit!==void 0&&$.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),$21=ir.extend({positionId:T$.optional(),marginAccountId:T$.optional(),tradingPairId:T$.optional(),reductionOnly:z.boolean().optional()}),hO$=z.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),J21=xK.extend({params:z.object({interval:hO$,startTime:z.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:z.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 uO$=z.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),mO$=z.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),G21=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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:uO$.optional(),transactionType:mO$.optional(),assetId:T$.optional()}),W21=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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:T$.optional()}),D21=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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:T$.optional(),positionId:T$.optional(),marginAccountId:T$.optional()});var O21=z.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),HT=z.union([z.string().regex(/^\d+$/,"Must be a positive integer string").refine(($)=>BigInt($)>0n,{message:"Amount must be greater than 0"}),z.bigint().refine(($)=>$>0n,{message:"Amount must be greater than 0"})]),N21=z.object({assetId:T$,amount:HT,autoWait:z.boolean().optional()}),w21=z.object({assetId:T$,amount:HT,autoWait:z.boolean().optional(),target:z.enum(["spot","margin"]).optional()}),M21=z.object({assetId:T$,amount:HT,destination:z.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:z.boolean().optional(),source:z.enum(["spot","margin"]).optional()}),H21=z.object({assetId:T$});function or($){$.registerTool("get_orders",{description:"Get a paginated list of orders with optional filters by status and trading pair.",inputSchema:z.object({status:z.enum(RK).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:z.string().optional().describe("Filter by trading pair UUID"),page:z.number().optional().describe("Page number (default: 1)"),pageSize:z.number().optional().describe("Orders per page (default: 10, max: 100)")})},async({status:J,tradingPairId:Q,page:Y,pageSize:X})=>{let W=await(await C$()).trading.getPaginatedOrders({status:J,tradingPairId:Q,page:Y,pageSize:X});return A$(W)})}function rr($){$.registerTool("place_limit_order",{description:"Place a limit order on Monaco. Limit orders execute only when the market reaches the specified price.",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),side:z.enum(["BUY","SELL"]).describe("Order side"),quantity:z.string().describe("Order quantity as a decimal string"),price:z.string().describe("Limit price as a decimal string"),tradingMode:z.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:z.enum(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:z.string().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:z.string().optional().describe("Parent margin account UUID for MARGIN orders"),riskBucketId:z.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:z.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:z.string().optional().describe("Optional client strategy key"),positionSide:z.enum(["LONG","SHORT","NONE"]).optional().describe("Position side for MARGIN orders"),leverage:z.string().optional().describe("Leverage as a decimal string for MARGIN orders"),reduceOnly:z.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:A})=>{let F=await(await C$()).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:A});return A$(F)})}function tr($){$.registerTool("place_market_order",{description:"Place a market order on Monaco. Market orders execute immediately at the current market price.",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),side:z.enum(["BUY","SELL"]).describe("Order side"),quantity:z.string().describe("Order quantity as a decimal string"),tradingMode:z.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:z.number().optional().describe("Slippage tolerance as decimal (e.g. 0.01 for 1%)"),marginAccountId:z.string().optional().describe("Parent margin account UUID for MARGIN orders"),riskBucketId:z.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:z.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:z.string().optional().describe("Optional client strategy key"),positionSide:z.enum(["LONG","SHORT","NONE"]).optional().describe("Position side for MARGIN orders"),leverage:z.string().optional().describe("Leverage as a decimal string for MARGIN orders"),reduceOnly:z.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 A=await(await C$()).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$(A)})}function ar($){$.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open.",inputSchema:z.object({orderId:z.string().describe("The order ID to replace"),price:z.string().optional().describe("New price as a decimal string"),quantity:z.string().optional().describe("New quantity as a decimal string")})},async({orderId:J,price:Q,quantity:Y})=>{let G=await(await C$()).trading.replaceOrder(J,{price:Q,quantity:Y});return A$(G)})}function sr($){rr($),tr($),fr($),kr($),vr($),xr($),ar($),or($),br($)}function er($){$.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:z.object({assetId:z.string().describe("The asset UUID to check allowance for")})},async({assetId:J})=>{let Y=await(await C$()).vault.getAllowance(J);return A$({assetId:J,allowance:Y.toString()})})}function $t($){$.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:z.object({assetId:z.string().describe("The asset UUID to approve"),amount:z.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 C$()).vault.approve(J,BigInt(Q));return A$({hash:X.hash,status:X.status})})}function Jt($){$.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:z.object({assetId:z.string().describe("The asset UUID to deposit"),amount:z.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:z.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 C$()).vault.deposit(J,BigInt(Q),void 0,Y);return A$({hash:G.hash,status:G.status})})}function Qt($){$.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:z.object({assetId:z.string().describe("The asset UUID to check"),amount:z.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 C$()).vault.needsApproval(J,BigInt(Q));return A$({assetId:J,amount:Q,needs_approval:X})})}function Xt($){$.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:z.object({assetId:z.string().describe("The asset UUID to withdraw"),amount:z.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 C$()).vault.withdraw(J,BigInt(Q));return A$({withdrawalIndex:X.withdrawalIndex,status:X.status,hash:X.hash})})}function Yt($){$t($),Jt($),Xt($),er($),Qt($)}function Gt($,J){if(Rr($),wr($),Hr($),Pr($),Lr($),J.authenticated)sr($),Sr($),Vr($),Yt($),Gr($,{network:J.network}),Zr($)}if(!globalThis.fetch)globalThis.fetch=AU,globalThis.Headers=$6,globalThis.Request=cJ,globalThis.Response=E1;if(!globalThis.WebSocket)globalThis.WebSocket=iA.default;async function lO$(){let $=P8(),J=$.privateKey!==null,Q=new aB({name:"monaco-mcp-server",version:Cw.version});Gt(Q,{authenticated:J,network:$.network});let Y=new eB;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)")}lO$().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 wO$(){if(mz)return;await _r("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:Cw.version}},0)}async function MO$($){return await wO$(),(await _r("tools/call",{name:NO$,arguments:{query:$}},1))?.result}function Tr($){$.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:z.object({query:z.string().describe("The search query")})},async({query:J})=>{try{let Q=await MO$(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 Rr($){Tr($)}function Cr($){$.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),page:z.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:z.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 Pr($){Cr($)}function vr($){$.registerTool("batch_cancel_all_orders",{description:"Cancel all active orders, optionally filtered to a specific trading pair.",inputSchema:z.object({tradingPairId:z.string().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:J})=>{let Y=await(await C$()).trading.batchCancelAll(J);return A$(Y)})}function kr($){$.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request.",inputSchema:z.object({orderIds:z.array(z.string()).describe("Array of order IDs to cancel")})},async({orderIds:J})=>{let Y=await(await C$()).trading.batchCancel(J);return A$(Y)})}function xr($){$.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:z.object({tradingPairId:z.string().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:z.number().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:J,slippageToleranceBps:Q})=>{let X=await(await C$()).positions.batchCloseAllPositions({tradingPairId:J,slippageToleranceBps:Q});return A$(X)})}function fr($){$.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:z.object({orderId:z.string().describe("The order ID to cancel")})},async({orderId:J})=>{let Y=await(await C$()).trading.cancelOrder(J);return A$(Y)})}function br($){$.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:z.object({orderId:z.string().describe("The order ID to look up")})},async({orderId:J})=>{let Y=await(await C$()).trading.getOrder(J);return A$(Y)})}var HO$=z.object({tradingPairId:z.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:z.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:z.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:z.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:z.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:z.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:z.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),zO$=z.object({applicationName:z.string().nullable().optional(),applicationTakerFee:z.string(),applicationTakerFeeBps:z.number(),buyOrderLockAmount:z.string().nullable().optional(),makerTotalReceipt:z.string(),monacoMakerRebate:z.string(),monacoMakerRebateBps:z.number(),monacoMakerRebateBpsExact:z.string(),monacoTakerFee:z.string(),monacoTakerFeeBps:z.number(),monacoTakerFeeBpsExact:z.string(),notional:z.string(),takerTotalPayment:z.string(),totalTakerFees:z.string(),maxQuantity:z.string().nullable(),maxQuantityRaw:z.string().nullable(),slippageToleranceBps:z.number().nullable()}),AO$=z.object({tradingPairId:z.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),gr=z.object({tierLevel:z.number().int(),minVolumeThreshold:z.string(),makerFeeBps:z.string(),takerFeeBps:z.string()}),IO$=z.object({currentTierLevel:z.number().int(),weightedVolume14d:z.string(),spotVolume14d:z.string(),perpVolume14d:z.string(),volumeToNextTier:z.string().nullable().optional(),nextTierLevel:z.number().int().nullable().optional(),feeSchedule:z.array(gr)});var yr=z.object({token:z.string(),available:z.string()}),qO$=z.object({balances:z.array(yr)}),LO$=z.object({code:z.string(),createdAt:z.string()}),ZO$=z.object({code:z.string()}),BO$=z.object({token:z.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:z.string().trim().min(1,"amount is required").refine(($)=>/^\d+$/.test($)&&BigInt($)>0n,"amount must be a positive integer string")}),FO$=z.object({rewardsBalance:z.string(),tradingBalance:z.string()});var RK=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var CK=z.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),dz=z.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),KT=z.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),PK=z.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),hr=z.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),UT=z.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),_7=z.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),M4=z.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"}),T$=z.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),vK=z.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),ur=z.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),kK=z.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),lz=z.object({triggerPrice:M4,orderType:_7,limitPrice:M4.optional(),timeInForce:UT.optional(),slippageToleranceBps:kK.optional(),expiresAt:vK.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"]}),mr=($)=>$?.takeProfit!==void 0||$?.stopLoss!==void 0,OT=($,J)=>J===void 0||J!=="NONE"&&($==="BUY"&&J==="LONG"||$==="SELL"&&J==="SHORT"),Vq1=z.object({tradingPairId:T$,side:CK,quantity:M4,price:M4,options:z.object({tradingMode:dz.optional(),useMasterBalance:z.boolean().optional(),expirationDate:vK.optional(),timeInForce:hr.optional(),marginAccountId:T$.optional(),marginMode:KT.optional(),riskBucketId:T$.optional(),riskBucketCollateral:M4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:PK.optional(),leverage:M4.optional(),reduceOnly:z.boolean().optional(),takeProfit:lz.optional(),stopLoss:lz.optional()}).optional()}).refine(($)=>OT($.side,$.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.reduceOnly===!0||$.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine(($)=>!mr($.options),{message:"Entry-attached TP/SL are no longer supported; create position TP/SL after the position opens",path:["options"]}).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"]}),Kq1=z.object({tradingPairId:T$,side:CK,quantity:M4,options:z.object({tradingMode:dz.optional(),slippageTolerance:ur,marginAccountId:T$.optional(),marginMode:KT.optional(),riskBucketId:T$.optional(),riskBucketCollateral:M4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:PK.optional(),leverage:M4.optional(),reduceOnly:z.boolean().optional(),takeProfit:lz.optional(),stopLoss:lz.optional()}).optional()}).refine(($)=>OT($.side,$.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.reduceOnly===!0||$.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine(($)=>!mr($.options),{message:"Entry-attached TP/SL are no longer supported; create position TP/SL after the position opens",path:["options"]}).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"]}),Uq1=z.object({orderId:T$}),Oq1=z.object({orderId:T$,newOrder:z.object({price:M4.optional(),quantity:M4.optional(),useMasterBalance:z.boolean().optional()})}),Nq1=z.object({status:z.enum(RK).optional(),tradingPairId:T$.optional(),tradingMode:dz.optional(),marginAccountId:T$.optional(),page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),pageToken:z.string().optional()}),wq1=z.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),Mq1=z.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),jO$=z.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),Hq1=z.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),zq1=z.object({conditionalOrderId:T$}),Aq1=z.object({marginAccountId:T$.optional(),tradingPairId:T$.optional(),state:jO$.optional(),page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),EO$=z.object({tradingPairId:T$,orderType:_7,side:CK,price:M4.optional(),quantity:M4,tradingMode:dz.optional(),slippageTolerance:ur,useMasterBalance:z.boolean().optional(),expirationDate:vK.optional(),timeInForce:hr.optional(),marginAccountId:T$.optional(),marginMode:KT.optional(),riskBucketId:T$.optional(),riskBucketCollateral:M4.optional(),strategyKey:z.string().min(1).max(128).optional(),positionSide:PK.optional(),leverage:M4.optional(),reduceOnly:z.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(($)=>$.orderType!=="MARKET"||$.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).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(($)=>OT($.side,$.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine(($)=>$.tradingMode!=="MARGIN"||$.reduceOnly===!0||$.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),Iq1=z.object({orders:z.array(EO$).min(1,"At least one order is required")}),SO$=z.object({orderId:T$,price:M4.optional(),quantity:M4.optional(),useMasterBalance:z.boolean().optional()}).refine(($)=>$.price!==void 0||$.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),qq1=z.object({orders:z.array(SO$).min(1,"At least one order is required")});var NT=z.object({page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Fq1=NT.extend({state:z.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:T$.optional()}),jq1=z.object({marginAccountId:T$,tradingPairId:T$.optional()}),Eq1=z.object({tradingPairId:T$.optional()}).optional(),Sq1=z.object({asset:z.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),_O$=z.object({asset:z.string().trim().min(1,"Asset cannot be empty"),amount:M4,tradingPairId:T$.optional(),strategyKey:z.string().trim().min(1,"Strategy key cannot be empty").optional()}),pz=z.object({asset:z.string().trim().min(1,"Asset cannot be empty"),amount:M4}),TO$=z.object({tradingPairId:T$,strategyKey:z.string().trim().min(1,"Strategy key cannot be empty").optional()}),RO$=z.array(T$).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),lr=TO$.extend({marginMode:z.literal("ISOLATED").optional(),selectedTradingPairIds:z.never().optional()}),dr=z.object({marginMode:z.literal("CROSS"),selectedTradingPairIds:RO$,strategyKey:z.never().optional()}),CO$=dr.extend({tradingPairId:z.never().optional()}),_q1=z.object({marginAccountId:T$,request:_O$}),Tq1=z.object({request:pz}),Rq1=z.object({request:z.union([pz.merge(lr).strict(),pz.merge(CO$).strict()])}),Cq1=z.object({request:pz}),Pq1=NT.extend({marginAccountId:T$,movementType:z.string().trim().min(1,"Movement type cannot be empty").optional()}),vq1=NT.extend({movementType:z.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),wT=z.object({tradingPairId:T$,side:CK,positionSide:PK.optional(),orderType:_7,price:M4.optional(),quantity:M4,leverage:M4.optional(),reduceOnly:z.boolean().optional()}),MT=($,J)=>{if($.positionSide!==void 0){let Q=$.side==="BUY"?"LONG":"SHORT";if($.positionSide!==Q)J.addIssue({code:z.ZodIssueCode.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if($.reduceOnly!==!0&&$.leverage===void 0)J.addIssue({code:z.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},pr=wT.strict().superRefine(MT),PO$=wT.merge(lr).strict().superRefine(MT),vO$=wT.merge(dr).strict().superRefine(MT).refine(($)=>$.selectedTradingPairIds.includes($.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),kO$=z.union([PO$,vO$]),kq1=z.object({marginAccountId:T$,request:pr}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),xq1=z.object({request:pr}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),fq1=z.object({request:kO$}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var nr=z.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"'}),xO$=31536000000,fO$=946684800000,nz=z.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(fO$,{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()+xO$,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),hq1=z.object({tradingPairId:T$,interval:nr,startTime:nz,endTime:nz}).refine(($)=>$.startTime<$.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),uq1=z.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")'}),bO$=z.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),mq1=z.object({tradingPairId:T$,interval:nr,startTime:nz.optional(),endTime:nz.optional(),limit:bO$}).refine(($)=>{if($.startTime!==void 0&&$.endTime!==void 0)return $.startTime<$.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var lq1=z.object({tradingPairId:T$}),dq1=z.object({query:z.string().min(1,"Search query cannot be empty").optional(),pageSize:z.number().int().min(1).max(100).optional(),page:z.number().int().min(1).optional()}),pq1=z.object({tradingPairId:T$});var ir=z.object({page:z.number().int().min(1,"Page must be at least 1").optional(),pageSize:z.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),gO$=z.enum(["OPEN","CLOSED","LIQUIDATING"],{message:'Position status must be "OPEN", "CLOSED", or "LIQUIDATING"'}),yO$=z.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),xK=z.object({positionId:T$}),oq1=ir.extend({marginAccountId:T$.optional(),tradingPairId:T$.optional(),status:gO$.optional()});var rq1=xK.extend({request:z.object({closeType:yO$,limitPrice:M4.optional(),slippageToleranceBps:kK.optional(),quantity:M4.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"]}),tq1=z.object({tradingPairId:T$.optional(),slippageToleranceBps:kK.optional()});var aq1=xK.extend({request:z.object({amount:M4,asset:z.string().trim().min(1,"Asset cannot be empty")})}),sq1=xK.extend({request:z.object({amount:M4})}),cr=z.object({triggerPrice:M4,orderType:_7,limitPrice:M4.optional(),quantity:M4.optional(),closePosition:z.boolean().optional(),timeInForce:UT.optional(),slippageToleranceBps:kK.optional(),expiresAt:vK.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"]}).refine(($)=>$.closePosition!==!0||$.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine(($)=>$.quantity!==void 0||$.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),eq1=xK.extend({request:z.object({takeProfit:cr.optional(),stopLoss:cr.optional(),oco:z.boolean().optional()}).refine(($)=>$.takeProfit!==void 0||$.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine(($)=>$.oco!==!0||$.takeProfit!==void 0&&$.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),$21=ir.extend({positionId:T$.optional(),marginAccountId:T$.optional(),tradingPairId:T$.optional(),reductionOnly:z.boolean().optional()}),hO$=z.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),J21=xK.extend({params:z.object({interval:hO$,startTime:z.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:z.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 uO$=z.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),mO$=z.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),G21=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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:uO$.optional(),transactionType:mO$.optional(),assetId:T$.optional()}),W21=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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:T$.optional(),pageToken:z.string().optional()}),D21=z.object({page:z.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:z.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:T$.optional(),positionId:T$.optional(),marginAccountId:T$.optional()});var O21=z.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),HT=z.union([z.string().regex(/^\d+$/,"Must be a positive integer string").refine(($)=>BigInt($)>0n,{message:"Amount must be greater than 0"}),z.bigint().refine(($)=>$>0n,{message:"Amount must be greater than 0"})]),N21=z.object({assetId:T$,amount:HT,autoWait:z.boolean().optional()}),w21=z.object({assetId:T$,amount:HT,autoWait:z.boolean().optional(),target:z.enum(["spot","margin"]).optional()}),M21=z.object({assetId:T$,amount:HT,destination:z.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:z.boolean().optional(),source:z.enum(["spot","margin"]).optional()}),H21=z.object({assetId:T$});function or($){$.registerTool("get_orders",{description:"Get a paginated list of orders with optional filters by status and trading pair.",inputSchema:z.object({status:z.enum(RK).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:z.string().optional().describe("Filter by trading pair UUID"),page:z.number().optional().describe("Page number (default: 1)"),pageSize:z.number().optional().describe("Orders per page (default: 10, max: 100)")})},async({status:J,tradingPairId:Q,page:Y,pageSize:X})=>{let W=await(await C$()).trading.getPaginatedOrders({status:J,tradingPairId:Q,page:Y,pageSize:X});return A$(W)})}function rr($){$.registerTool("place_limit_order",{description:"Place a limit order on Monaco. Limit orders execute only when the market reaches the specified price.",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),side:z.enum(["BUY","SELL"]).describe("Order side"),quantity:z.string().describe("Order quantity as a decimal string"),price:z.string().describe("Limit price as a decimal string"),tradingMode:z.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:z.enum(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:z.string().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:z.string().optional().describe("Parent margin account UUID for MARGIN orders"),riskBucketId:z.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:z.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:z.string().optional().describe("Optional client strategy key"),positionSide:z.enum(["LONG","SHORT","NONE"]).optional().describe("Position side for MARGIN orders"),leverage:z.string().optional().describe("Leverage as a decimal string for MARGIN orders"),reduceOnly:z.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:A})=>{let F=await(await C$()).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:A});return A$(F)})}function tr($){$.registerTool("place_market_order",{description:"Place a market order on Monaco. Market orders execute immediately at the current market price.",inputSchema:z.object({tradingPairId:z.string().describe("Trading pair UUID"),side:z.enum(["BUY","SELL"]).describe("Order side"),quantity:z.string().describe("Order quantity as a decimal string"),tradingMode:z.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:z.number().optional().describe("Slippage tolerance as decimal (e.g. 0.01 for 1%)"),marginAccountId:z.string().optional().describe("Parent margin account UUID for MARGIN orders"),riskBucketId:z.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:z.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:z.string().optional().describe("Optional client strategy key"),positionSide:z.enum(["LONG","SHORT","NONE"]).optional().describe("Position side for MARGIN orders"),leverage:z.string().optional().describe("Leverage as a decimal string for MARGIN orders"),reduceOnly:z.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 A=await(await C$()).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$(A)})}function ar($){$.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open.",inputSchema:z.object({orderId:z.string().describe("The order ID to replace"),price:z.string().optional().describe("New price as a decimal string"),quantity:z.string().optional().describe("New quantity as a decimal string")})},async({orderId:J,price:Q,quantity:Y})=>{let G=await(await C$()).trading.replaceOrder(J,{price:Q,quantity:Y});return A$(G)})}function sr($){rr($),tr($),fr($),kr($),vr($),xr($),ar($),or($),br($)}function er($){$.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:z.object({assetId:z.string().describe("The asset UUID to check allowance for")})},async({assetId:J})=>{let Y=await(await C$()).vault.getAllowance(J);return A$({assetId:J,allowance:Y.toString()})})}function $t($){$.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:z.object({assetId:z.string().describe("The asset UUID to approve"),amount:z.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 C$()).vault.approve(J,BigInt(Q));return A$({hash:X.hash,status:X.status})})}function Jt($){$.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:z.object({assetId:z.string().describe("The asset UUID to deposit"),amount:z.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:z.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 C$()).vault.deposit(J,BigInt(Q),void 0,Y);return A$({hash:G.hash,status:G.status})})}function Qt($){$.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:z.object({assetId:z.string().describe("The asset UUID to check"),amount:z.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 C$()).vault.needsApproval(J,BigInt(Q));return A$({assetId:J,amount:Q,needs_approval:X})})}function Xt($){$.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:z.object({assetId:z.string().describe("The asset UUID to withdraw"),amount:z.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 C$()).vault.withdraw(J,BigInt(Q));return A$({withdrawalIndex:X.withdrawalIndex,status:X.status,hash:X.hash})})}function Yt($){$t($),Jt($),Xt($),er($),Qt($)}function Gt($,J){if(Rr($),wr($),Hr($),Pr($),Lr($),J.authenticated)sr($),Sr($),Vr($),Yt($),Gr($,{network:J.network}),Zr($)}if(!globalThis.fetch)globalThis.fetch=AU,globalThis.Headers=$6,globalThis.Request=cJ,globalThis.Response=E1;if(!globalThis.WebSocket)globalThis.WebSocket=iA.default;async function lO$(){let $=P8(),J=$.privateKey!==null,Q=new aB({name:"monaco-mcp-server",version:Cw.version});Gt(Q,{authenticated:J,network:$.network});let Y=new eB;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)")}lO$().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.28",
|
|
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.28",
|
|
29
|
+
"@0xmonaco/types": "1.0.28",
|
|
30
30
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
31
31
|
"node-fetch": "^3.3.2",
|
|
32
32
|
"viem": "^2.53.1",
|