@0xmonaco/mcp-server 1.0.44 → 1.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +4 -4
  2. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -133,7 +133,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
133
133
  `:`[${o[c]}\r
134
134
  ]`;continue}if(n+=o[c],o[c]==="\\")i=!0;else if(a&&o[c]==="]")a=!1;else if(!a&&o[c]==="[")a=!0}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return n}function Qv(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===ne.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((o,n)=>({...o,[n]:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Jt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ne.ZodString&&e.keyType._def.checks?.length){let{type:o,...n}=Yv(e.keyType._def,t);return{...r,propertyNames:n}}else if(e.keyType?._def.typeName===ne.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===ne.ZodBranded&&e.keyType._def.type._def.typeName===ne.ZodString&&e.keyType._def.type._def.checks?.length){let{type:o,...n}=Jv(e.keyType._def,t);return{...r,propertyNames:n}}return r}function PD(e,t){if(t.mapStrategy==="record")return Qv(e,t);let r=Be(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Jt(t),o=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Jt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function kD(e){let t=e.values,o=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),n=Array.from(new Set(o.map((i)=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function AD(e){return e.target==="openAi"?void 0:{not:Jt({...e,currentPath:[...e.currentPath,"not"]})}}function RD(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zh={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function OD(e,t){if(t.target==="openApi3")return $D(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((o)=>(o._def.typeName in zh)&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,i)=>{let a=zh[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every((o)=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){let n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every((o)=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter((i)=>!o.includes(i))],[])};return $D(e,t)}var $D=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>Be(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter((o)=>!!o&&(!t.strictUnions||typeof o==="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function CD(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:zh[e.innerType._def.typeName],nullable:!0};return{type:[zh[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let o=Be(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(o&&"$ref"in o)return{allOf:[o],nullable:!0};return o&&{...o,nullable:!0}}let r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function zD(e,t){let r={type:"number"};if(!e.checks)return r;for(let o of e.checks)switch(o.kind){case"int":r.type="integer",VA(r,"type",o.message,t);break;case"min":if(t.target==="jsonSchema7")if(o.inclusive)lt(r,"minimum",o.value,o.message,t);else lt(r,"exclusiveMinimum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMinimum=!0;lt(r,"minimum",o.value,o.message,t)}break;case"max":if(t.target==="jsonSchema7")if(o.inclusive)lt(r,"maximum",o.value,o.message,t);else lt(r,"exclusiveMaximum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMaximum=!0;lt(r,"maximum",o.value,o.message,t)}break;case"multipleOf":lt(r,"multipleOf",o.value,o.message,t);break}return r}function ND(e,t){let r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=aae(c);if(u&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();u=!1}let d=Be(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});if(d===void 0)continue;if(o.properties[s]=d,!u)n.push(s)}if(n.length)o.required=n;let a=iae(e,t);if(a!==void 0)o.additionalProperties=a;return o}function iae(e,t){if(e.catchall._def.typeName!=="ZodNever")return Be(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function aae(e){try{return e.isOptional()}catch{return!0}}var MD=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Be(e.innerType._def,t);let r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Jt(t)},r]}:Jt(t)};var BD=(e,t)=>{if(t.pipeStrategy==="input")return Be(e.in._def,t);else if(t.pipeStrategy==="output")return Be(e.out._def,t);let r=Be(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=Be(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter((n)=>n!==void 0)}};function DD(e,t){return Be(e.type._def,t)}function UD(e,t){let o={type:"array",uniqueItems:!0,items:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)lt(o,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)lt(o,"maxItems",e.maxSize.value,e.maxSize.message,t);return o}function LD(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:Be(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function jD(e){return{not:Jt(e)}}function FD(e){return Jt(e)}var qD=(e,t)=>Be(e.innerType._def,t);var HD=(e,t,r)=>{switch(t){case ne.ZodString:return Yv(e,r);case ne.ZodNumber:return zD(e,r);case ne.ZodObject:return ND(e,r);case ne.ZodBigInt:return bD(e,r);case ne.ZodBoolean:return xD();case ne.ZodDate:return ZA(e,r);case ne.ZodUndefined:return jD(r);case ne.ZodNull:return RD(r);case ne.ZodArray:return yD(e,r);case ne.ZodUnion:case ne.ZodDiscriminatedUnion:return OD(e,r);case ne.ZodIntersection:return TD(e,r);case ne.ZodTuple:return LD(e,r);case ne.ZodRecord:return Qv(e,r);case ne.ZodLiteral:return ED(e,r);case ne.ZodEnum:return SD(e);case ne.ZodNativeEnum:return kD(e);case ne.ZodNullable:return CD(e,r);case ne.ZodOptional:return MD(e,r);case ne.ZodMap:return PD(e,r);case ne.ZodSet:return UD(e,r);case ne.ZodLazy:return()=>e.getter()._def;case ne.ZodPromise:return DD(e,r);case ne.ZodNaN:case ne.ZodNever:return AD(r);case ne.ZodEffects:return wD(e,r);case ne.ZodAny:return Jt(r);case ne.ZodUnknown:return FD(r);case ne.ZodDefault:return _D(e,r);case ne.ZodBranded:return Jv(e,r);case ne.ZodReadonly:return qD(e,r);case ne.ZodCatch:return vD(e,r);case ne.ZodPipeline:return BD(e,r);case ne.ZodFunction:case ne.ZodVoid:case ne.ZodSymbol:return;default:return((o)=>{return})(t)}};function Be(e,t,r=!1){let o=t.seen.get(e);if(t.override){let s=t.override?.(e,t,o,r);if(s!==mD)return s}if(o&&!r){let s=sae(o,t);if(s!==void 0)return s}let n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);let i=HD(e,e.typeName,t),a=typeof i==="function"?Be(i(),t):i;if(a)cae(e,t,a);if(t.postProcess){let s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}var sae=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Kv(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Jt(t);return t.$refStrategy==="seen"?Jt(t):void 0}}},cae=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var JA=(e,t)=>{let r=gD(t),o=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,d])=>({...c,[u]:Be(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Jt(r)}),{}):void 0,n=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Be(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Jt(r),a=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(a!==void 0)i.title=a;if(r.flags.hasReferencedOpenAiAnyType){if(!o)o={};if(!o[r.openAiAnyTypeName])o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let s=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};if(r.target==="jsonSchema7")s.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")s.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in s)||("oneOf"in s)||("allOf"in s)||("type"in s)&&Array.isArray(s.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return s};function uae(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function YA(e,t){if(io(e))return Yc(e,{target:uae(t?.target),io:t?.pipeStrategy??"input"});return JA(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function QA(e){let r=Is(e)?.method;if(!r)throw Error("Schema is missing a method literal");let o=Qx(r);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function XA(e,t){let r=Es(e,t);if(!r.success)throw r.error;return r.data}var lae=60000;class e6{constructor(e){if(this._options=e,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(Ov,(t)=>{this._oncancel(t)}),this.setNotificationHandler(zv,(t)=>{this._onprogress(t)}),this.setRequestHandler(Cv,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(Nv,async(t,r)=>{let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ie(Oe.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Bv,async(t,r)=>{let o=async()=>{let n=t.params.taskId;if(this._taskMessageQueue){let a;while(a=await this._taskMessageQueue.dequeue(n,r.sessionId)){if(a.type==="response"||a.type==="error"){let s=a.message,c=s.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(s);else{let d=s,p=new Ie(d.error.code,d.error.message,d.error.data);u(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(n,r.sessionId);if(!i)throw new Ie(Oe.InvalidParams,`Task not found: ${n}`);if(!As(i.status))return await this._waitForTaskUpdate(n,r.signal),await o();if(As(i.status)){let a=await this._taskStore.getTaskResult(n,r.sessionId);return this._clearTaskQueue(n),{...a,_meta:{...a._meta,[ks]:{taskId:n}}}}return await o()};return await o()}),this.setRequestHandler(Dv,async(t,r)=>{try{let{tasks:o,nextCursor:n}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:o,nextCursor:n,_meta:{}}}catch(o){throw new Ie(Oe.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Lv,async(t,r)=>{try{let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ie(Oe.InvalidParams,`Task not found: ${t.params.taskId}`);if(As(o.status))throw new Ie(Oe.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ie(Oe.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...n}}catch(o){if(o instanceof Ie)throw o;throw new Ie(Oe.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ie.fromError(Oe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){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=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,i)=>{if(o?.(n,i),Eh(n)||tD(n))this._onresponse(n);else if(OA(n))this._onrequest(n,i);else if(eD(n))this._onnotification(n);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=Ie.fromError(Oe.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,n=e.params?._meta?.[ks]?.taskId;if(r===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Oe.MethodNotFound,message:"Method not found"}};if(n&&this._taskMessageQueue)this._enqueueTaskMessage(n,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else o?.send(u).catch((d)=>this._onerror(Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=YB(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,c={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async(u)=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};if(n)d.relatedTask={taskId:n};await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(i.signal.aborted)throw new Ie(Oe.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};if(n&&!m.relatedTask)m.relatedTask={taskId:n};let h=m.relatedTask?.taskId??n;if(h&&s)await s.updateTaskStatus(h,"input_required");return await this.request(u,d,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:n,taskStore:s,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(a)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,c)).then(async(u)=>{if(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};if(n&&this._taskMessageQueue)await this._enqueueTaskMessage(n,{type:"response",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)},async(u)=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Oe.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(n&&this._taskMessageQueue)await this._enqueueTaskMessage(n,{type:"error",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)}).catch((u)=>this._onerror(Error(`Failed to send response: ${u}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(s){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(s);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),Eh(e))r(e);else{let i=new Ie(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(t);if(o===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let n=!1;if(Eh(e)&&e.result&&typeof e.result==="object"){let i=e.result;if(i.task&&typeof i.task==="object"){let a=i.task;if(typeof a.taskId==="string")n=!0,this._taskProgressTokens.set(a.taskId,t)}}if(!n)this._progressHandlers.delete(t);if(Eh(e))o(e);else{let i=Ie.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ie?i:new Ie(Oe.InternalError,String(i))}}return}let n;try{let i=await this.request(e,Td,r);if(i.task)n=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ie(Oe.InternalError,"Task creation did not return a task");while(!0){let a=await this.getTask({taskId:n},r);if(yield{type:"taskStatus",task:a},As(a.status)){if(a.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:n},t,r)};else if(a.status==="failed")yield{type:"error",error:new Ie(Oe.InternalError,`Task ${n} failed`)};else if(a.status==="cancelled")yield{type:"error",error:new Ie(Oe.InternalError,`Task ${n} was cancelled`)};return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:n},t,r)};return}let s=a.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,s)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ie?i:new Ie(Oe.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i,task:a,relatedTask:s}=r??{};return new Promise((c,u)=>{let d=(v)=>{u(v)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),a)this.assertTaskCapability(e.method)}catch(v){d(v);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};if(r?.onprogress)this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(a)m.params={...m.params,task:a};if(s)m.params={...m.params,_meta:{...m.params?._meta||{},[ks]:s}};let h=(v)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i}).catch((w)=>this._onerror(Error(`Failed to send cancellation: ${w}`)));let E=v instanceof Ie?v:new Ie(Oe.RequestTimeout,String(v));u(E)};this._responseHandlers.set(p,(v)=>{if(r?.signal?.aborted)return;if(v instanceof Error)return u(v);try{let E=Es(t,v.result);if(!E.success)u(E.error);else c(E.data)}catch(E){u(E)}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});let y=r?.timeout??lae,x=()=>h(Ie.fromError(Oe.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,r?.maxTotalTimeout,x,r?.resetTimeoutOnProgress??!1);let S=s?.taskId;if(S){let v=(E)=>{let w=this._responseHandlers.get(p);if(w)w(E);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(S,{type:"request",message:m,timestamp:Date.now()}).catch((E)=>{this._cleanupTimeout(p),u(E)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i}).catch((v)=>{this._cleanupTimeout(p),u(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Mv,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Uv,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},oD,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ks]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};if(t?.relatedTask)a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[ks]:t.relatedTask}}};this._transport?.send(a,t).catch((s)=>this._onerror(s))});return}let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ks]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=QA(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,n)=>{let i=XA(e,o);return Promise.resolve(t(i,n))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=QA(e);this._notificationHandlers.set(r,(o)=>{let n=XA(e,o);return Promise.resolve(t(n))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,o)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let o of r)if(o.type==="request"&&OA(o.message)){let n=o.message.id,i=this._requestResolvers.get(n);if(i)i(new Ie(Oe.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n);else this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e);if(o?.pollInterval)r=o.pollInterval}catch{}return new Promise((o,n)=>{if(t.aborted){n(new Ie(Oe.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);t.addEventListener("abort",()=>{clearTimeout(i),n(new Ie(Oe.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(o)=>{if(!e)throw Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},t)},getTask:async(o)=>{let n=await r.getTask(o,t);if(!n)throw new Ie(Oe.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(o,n,i)=>{await r.storeTaskResult(o,n,i,t);let a=await r.getTask(o,t);if(a){let s=Rh.parse({method:"notifications/tasks/status",params:a});if(await this.notification(s),As(a.status))this._cleanupTaskProgressHandler(o)}},getTaskResult:(o)=>r.getTaskResult(o,t),updateTaskStatus:async(o,n,i)=>{let a=await r.getTask(o,t);if(!a)throw new Ie(Oe.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(As(a.status))throw new Ie(Oe.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,n,i,t);let s=await r.getTask(o,t);if(s){let c=Rh.parse({method:"notifications/tasks/status",params:s});if(await this.notification(c),As(s.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>r.listTasks(o,t)}}}function GD(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function VD(e,t){let r={...e};for(let o in t){let n=o,i=t[n];if(i===void 0)continue;let a=r[n];if(GD(a)&&GD(i))r[n]={...a,...i};else r[n]=i}return r}var k3=on(K6(),1),A3=on(P3(),1);function Ome(){let e=new k3.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return A3.default(e),e}class iR{constructor(e){this._ajv=e??Ome()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class aR{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],i=n.some((u)=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some((u)=>u.type==="tool_use");if(i){if(n.some((u)=>u.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter((p)=>p.type==="tool_use").map((p)=>p.id)),d=new Set(n.filter((p)=>p.type==="tool_result").map((p)=>p.toolUseId));if(u.size!==d.size||![...u].every((p)=>d.has(p)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ch,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let n=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:n},Pd,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function R3(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function $3(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class sR extends e6{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Oh.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let n=this._loggingLevels.get(o);return n?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new iR,this.setRequestHandler(NA,(r)=>this._oninitialize(r)),this.setNotificationHandler(MA,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(qA,async(r,o)=>{let n=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Oh.safeParse(i);if(a.success)this._loggingLevels.set(n,a.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new aR(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=VD(this._capabilities,e)}setRequestHandler(e,t){let o=Is(e)?.method;if(!o)throw Error("Schema is missing a method literal");let n;if(io(o)){let a=o;n=a._zod?.def?.value??a.value}else{let a=o;n=a._def?.value??a.value}if(typeof n!=="string")throw Error("Schema method literal must be a string");if(n==="tools/call"){let a=async(s,c)=>{let u=Es(Id,s);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new Ie(Oe.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=u.data,p=await Promise.resolve(t(s,c));if(d.task){let h=Es(Td,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new Ie(Oe.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let m=Es(Zv,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Ie(Oe.InvalidParams,`Invalid tools/call result: ${h}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);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 ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){$3(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;R3(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:WB.includes(t)?t:RA,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"},$v)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],n=o.some((c)=>c.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],s=a.some((c)=>c.type==="tool_use");if(n){if(o.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let c=new Set(a.filter((d)=>d.type==="tool_use").map((d)=>d.id)),u=new Set(o.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(c.size!==u.size||![...c].every((d)=>u.has(d)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},HA,t);return this.request({method:"sampling/createMessage",params:e},Ch,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Pd,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},n=await this.request({method:"elicitation/create",params:o},Pd,t);if(n.action==="accept"&&n.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(n.content);if(!a.valid)throw new Ie(Oe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){if(i instanceof Ie)throw i;throw new Ie(Oe.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return n}}}createElicitationCompletionNotifier(e,t){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:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},GA,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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 C3=Symbol.for("mcp.completable");function cR(e){return!!e&&typeof e==="object"&&C3 in e}function z3(e){return e[C3]?.complete}var O3;(function(e){e.Completable="McpCompletable"})(O3||(O3={}));var Cme=/^[A-Za-z0-9._-]{1,128}$/;function zme(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Cme.test(e)){let r=e.split("").filter((o)=>!/[A-Za-z0-9._-]/.test(o)).filter((o,n,i)=>i.indexOf(o)===n);return t.push(`Tool name contains invalid characters: ${r.map((o)=>`"${o}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Nme(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);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 uR(e){let t=zme(e);return Nme(e,t.warnings),t.isValid}class lR{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let o={taskSupport:"required",...t.execution};if(o.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,o,t._meta,r)}}class pR{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new sR(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new lR(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(Bs(Vv)),this.server.assertCanSetRequestHandler(Bs(Id)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Vv,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let o=fd(t.inputSchema);return o?YA(o,{strictUnions:!0,pipeStrategy:"input"}):Mme})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let o=fd(t.outputSchema);if(o)r.outputSchema=YA(o,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Id,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Ie(Oe.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Ie(Oe.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,n=r.execution?.taskSupport,i="createTask"in r.handler;if((n==="required"||n==="optional")&&!i)throw new Ie(Oe.InternalError,`Tool ${e.params.name} has taskSupport '${n}' but was not registered with registerToolTask`);if(n==="required"&&!o)throw new Ie(Oe.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(n==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,t);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),s=await this.executeToolHandler(r,a,t);if(o)return s;return await this.validateToolOutput(r,s,e.params.name),s}catch(r){if(r instanceof Ie){if(r.code===Oe.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let n=fd(e.inputSchema)??e.inputSchema,i=await Jx(n,t);if(!i.success){let a="error"in i?i.error:"Unknown error",s=Yx(a);throw new Ie(Oe.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${s}`)}return i.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Ie(Oe.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=fd(e.outputSchema),n=await Jx(o,t.structuredContent);if(!n.success){let i="error"in n?n.error:"Unknown error",a=Yx(i);throw new Ie(Oe.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,t,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(o.createTask(t,i));else return await Promise.resolve(o.createTask(i))}if(e.inputSchema)return await Promise.resolve(o(t,r));else return await Promise.resolve(o(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,t.params.arguments,t.params.name),n=e.handler,i={...r,taskStore:r.taskStore},a=o?await Promise.resolve(n.createTask(o,i)):await Promise.resolve(n.createTask(i)),s=a.task.taskId,c=a.task,u=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((p)=>setTimeout(p,u));let d=await r.taskStore.getTask(s);if(!d)throw new Ie(Oe.InternalError,`Task ${s} not found during polling`);c=d}return await r.taskStore.getTaskResult(s)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(Bs(Wv)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Wv,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return lD(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return dD(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ie(Oe.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Ie(Oe.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Ie(Oe.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return og;let n=Is(r.argsSchema)?.[e.params.argument.name];if(!cR(n))return og;let i=z3(n);if(!i)return og;let a=await i(e.params.argument.value,e.params.context);return M3(a)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((i)=>i.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return og;throw new Ie(Oe.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return og;let n=await o(e.params.argument.value,e.params.context);return M3(n)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(Bs(jv)),this.server.assertCanSetRequestHandler(Bs(Fv)),this.server.assertCanSetRequestHandler(Bs(qv)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(jv,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([n,i])=>i.enabled).map(([n,i])=>({uri:n,name:i.name,...i.metadata})),o=[];for(let n of Object.values(this._registeredResourceTemplates)){if(!n.resourceTemplate.listCallback)continue;let i=await n.resourceTemplate.listCallback(t);for(let a of i.resources)o.push({...n.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Fv,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(qv,async(e,t)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new Ie(Oe.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,t)}for(let n of Object.values(this._registeredResourceTemplates)){let i=n.resourceTemplate.uriTemplate.match(r.toString());if(i)return n.readCallback(r,i,t)}throw new Ie(Oe.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(Bs(Hv)),this.server.assertCanSetRequestHandler(Bs(Gv)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Hv,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Bme(t.argsSchema):void 0}))})),this.server.setRequestHandler(Gv,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Ie(Oe.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Ie(Oe.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=fd(r.argsSchema),n=await Jx(o,e.params.arguments);if(!n.success){let s="error"in n?n.error:"Unknown error",c=Yx(s);throw new Ie(Oe.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=n.data,a=r.callback;return await Promise.resolve(a(i,t))}else{let o=r.callback;return await Promise.resolve(o(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let o;if(typeof r[0]==="object")o=r.shift();let n=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,void 0,t,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,t,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,o){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}_createRegisteredResource(e,t,r,o,n){let i={name:e,title:t,metadata:o,readCallback:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:(a)=>{if(typeof a.uri<"u"&&a.uri!==r){if(delete this._registeredResources[r],a.uri)this._registeredResources[a.uri]=i}if(typeof a.name<"u")i.name=a.name;if(typeof a.title<"u")i.title=a.title;if(typeof a.metadata<"u")i.metadata=a.metadata;if(typeof a.callback<"u")i.readCallback=a.callback;if(typeof a.enabled<"u")i.enabled=a.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,o,n){let i={resourceTemplate:r,title:t,metadata:o,readCallback:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=i}if(typeof c.title<"u")i.title=c.title;if(typeof c.template<"u")i.resourceTemplate=c.template;if(typeof c.metadata<"u")i.metadata=c.metadata;if(typeof c.callback<"u")i.readCallback=c.callback;if(typeof c.enabled<"u")i.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;if(Array.isArray(a)&&a.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return i}_createRegisteredPrompt(e,t,r,o,n){let i={title:t,description:r,argsSchema:o===void 0?void 0:Qc(o),callback:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(a)=>{if(typeof a.name<"u"&&a.name!==e){if(delete this._registeredPrompts[e],a.name)this._registeredPrompts[a.name]=i}if(typeof a.title<"u")i.title=a.title;if(typeof a.description<"u")i.description=a.description;if(typeof a.argsSchema<"u")i.argsSchema=Qc(a.argsSchema);if(typeof a.callback<"u")i.callback=a.callback;if(typeof a.enabled<"u")i.enabled=a.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=i,o){if(Object.values(o).some((s)=>{let c=s instanceof wd?s._def?.innerType:s;return cR(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,o,n,i,a,s,c){uR(e);let u={title:t,description:r,inputSchema:N3(o),outputSchema:N3(n),annotations:i,execution:a,_meta:s,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:(d)=>{if(typeof d.name<"u"&&d.name!==e){if(typeof d.name==="string")uR(d.name);if(delete this._registeredTools[e],d.name)this._registeredTools[d.name]=u}if(typeof d.title<"u")u.title=d.title;if(typeof d.description<"u")u.description=d.description;if(typeof d.paramsSchema<"u")u.inputSchema=Qc(d.paramsSchema);if(typeof d.outputSchema<"u")u.outputSchema=Qc(d.outputSchema);if(typeof d.callback<"u")u.handler=d.callback;if(typeof d.annotations<"u")u.annotations=d.annotations;if(typeof d._meta<"u")u._meta=d._meta;if(typeof d.enabled<"u")u.enabled=d.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,o,n,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let s=t[0];if(dR(s)){if(o=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!dR(t[0]))i=t.shift()}else if(typeof s==="object"&&s!==null){if(Object.values(s).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,r,o,n,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:o,description:n,inputSchema:i,outputSchema:a,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,o,n,i,a,s,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let o;if(t.length>1)o=t.shift();let n=t[0],i=this._createRegisteredPrompt(e,void 0,r,o,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:o,description:n,argsSchema:i}=t,a=this._createRegisteredPrompt(e,o,n,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var Mme={type:"object",properties:{}};function B3(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function D3(e){return"_def"in e||"_zod"in e||B3(e)}function dR(e){if(typeof e!=="object"||e===null)return!1;if(D3(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(B3)}function N3(e){if(!e)return;if(dR(e))return Qc(e);if(!D3(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Bme(e){let t=Is(e);if(!t)return[];return Object.entries(t).map(([r,o])=>{let n=C4(o),i=z4(o);return{name:r,description:n,required:!i}})}function Bs(e){let r=Is(e)?.method;if(!r)throw Error("Schema is missing a method literal");let o=Qx(r);if(typeof o==="string")return o;throw Error("Schema method literal must be a string")}function M3(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var og={completion:{values:[],hasMore:!1}};import L3 from"node:process";class fR{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
135
135
  `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Dme(t)}clear(){this._buffer=void 0}}function Dme(e){return rD.parse(JSON.parse(e))}function U3(e){return JSON.stringify(e)+`
136
- `}class mR{constructor(e=L3.stdin,t=L3.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new fR,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}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 e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}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(e){return new Promise((t)=>{let r=U3(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var N_={name:"@0xmonaco/mcp-server",version:"1.0.44",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",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.44","@0xmonaco/types":"1.0.44","@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 M_=["read","market-maker","full"],Ei=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],pRe=Ei.map((e)=>e.name),j3=Ei.filter((e)=>e.authMode==="public").map((e)=>e.name),fRe=Ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),mRe=Ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),hRe=Ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),gRe=Ei.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),F3=Ei.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name),Lme=new Map(Ei.map((e)=>[e.name,e.sideEffect]));function q3(e){let t=Lme.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var H3={read:0,"market-maker":1,full:2},hR=j3,gR=Object.fromEntries(Ei.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),G3=Object.fromEntries(Object.entries(gR).map(([e,t])=>[e,t.capability])),xRe=new Set(F3);function V3(e){let t=gR[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function Z3(e){return V3(e)==="read"}function W3(e,t){if(t.network==="mainnet"&&gR[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(hR.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return H3[t.capability]>=H3[V3(e)]}var jme=new Set([...hR,...Object.keys(G3)]),Fme={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 K3(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function su(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let o=["mainnet","development","staging","local"],n=e.MONACO_NETWORK;if(t&&!n)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${o.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=n||"mainnet";if(!o.includes(i))throw Error(`MONACO_NETWORK must be one of: ${o.join(", ")}.`);let a=i,s=e.MONACO_CAPABILITY;if(s&&!M_.includes(s))throw Error(`MONACO_CAPABILITY must be one of: ${M_.join(", ")}.`);let c=s||"read",u=K3(e.MONACO_TOOL_ALLOWLIST),d=K3(e.MONACO_TOOL_DENYLIST),p=[...u,...d].filter((y)=>!jme.has(y)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||Fme[a],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");h=y}return{privateKey:t,clientId:r,network:a,seiRpcUrl:m,capability:c,allow:u,deny:d,delegatedOwnerUserId:h}}function qme(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function lo(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>lo(r));let t={};for(let[r,o]of Object.entries(e))t[qme(r)]=typeof o==="object"&&o!==null?lo(o):o;return t}fo();ug();fo();zR();vu();bu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ai=BigInt(0),gn=BigInt(1),MF=BigInt(2),dhe=BigInt(8),phe={zip215:!0};function fhe(e){let t=pg(e);return Go(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function BF(e){let t=fhe(e),{Fp:r,n:o,prehash:n,hash:i,randomBytes:a,nByteLength:s,h:c}=t,u=MF<<BigInt(s*8)-gn,d=r.create,p=Sa(t.n,t.nBitLength);function m(C,B){let Z=r.sqr(C),we=r.sqr(B),Pe=r.add(r.mul(t.a,Z),we),je=r.add(r.ONE,r.mul(t.d,r.mul(Z,we)));return r.eql(Pe,je)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((C,B)=>{try{return{isValid:!0,value:r.sqrt(C*r.inv(B))}}catch(Z){return{isValid:!1,value:Ai}}}),y=t.adjustScalarBytes||((C)=>C),x=t.domain||((C,B,Z)=>{if(Pi("phflag",Z),B.length||Z)throw Error("Contexts/pre-hash are not supported");return C});function S(C,B,Z=!1){let we=Z?gn:Ai;mn("coordinate "+C,B,we,u)}function v(C){if(!(C instanceof _))throw Error("ExtendedPoint expected")}let E=Gd((C,B)=>{let{ex:Z,ey:we,ez:Pe}=C,je=C.is0();if(B==null)B=je?dhe:r.inv(Pe);let De=d(Z*B),Ce=d(we*B),V=d(Pe*B);if(je)return{x:Ai,y:gn};if(V!==gn)throw Error("invZ was invalid");return{x:De,y:Ce}}),w=Gd((C)=>{let{a:B,d:Z}=t;if(C.is0())throw Error("bad point: ZERO");let{ex:we,ey:Pe,ez:je,et:De}=C,Ce=d(we*we),V=d(Pe*Pe),se=d(je*je),le=d(se*se),be=d(Ce*B),ie=d(se*d(be+V)),Fe=d(le+d(Z*d(Ce*V)));if(ie!==Fe)throw Error("bad point: equation left != right (1)");let Kt=d(we*Pe),Ve=d(je*De);if(Kt!==Ve)throw Error("bad point: equation left != right (2)");return!0});class _{constructor(C,B,Z,we){S("x",C),S("y",B),S("z",Z,!0),S("t",we),this.ex=C,this.ey=B,this.ez=Z,this.et=we,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof _)throw Error("extended point not allowed");let{x:B,y:Z}=C||{};return S("x",B),S("y",Z),new _(B,Z,gn,d(B*Z))}static normalizeZ(C){let B=wa(r,C.map((Z)=>Z.ez));return C.map((Z,we)=>Z.toAffine(B[we])).map(_.fromAffine)}static msm(C,B){return V_(_,p,C,B)}_setWindowSize(C){O.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){v(C);let{ex:B,ey:Z,ez:we}=this,{ex:Pe,ey:je,ez:De}=C,Ce=d(B*De),V=d(Pe*we),se=d(Z*De),le=d(je*we);return Ce===V&&se===le}is0(){return this.equals(_.ZERO)}negate(){return new _(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:C}=t,{ex:B,ey:Z,ez:we}=this,Pe=d(B*B),je=d(Z*Z),De=d(MF*d(we*we)),Ce=d(C*Pe),V=B+Z,se=d(d(V*V)-Pe-je),le=Ce+je,be=le-De,ie=Ce-je,Fe=d(se*be),Kt=d(le*ie),Ve=d(se*ie),at=d(be*le);return new _(Fe,Kt,at,Ve)}add(C){v(C);let{a:B,d:Z}=t,{ex:we,ey:Pe,ez:je,et:De}=this,{ex:Ce,ey:V,ez:se,et:le}=C,be=d(we*Ce),ie=d(Pe*V),Fe=d(De*Z*le),Kt=d(je*se),Ve=d((we+Pe)*(Ce+V)-be-ie),at=Kt-Fe,pr=Kt+Fe,_r=d(ie-B*be),Bf=d(Ve*at),ul=d(pr*_r),Ly=d(Ve*_r),Po=d(at*pr);return new _(Bf,ul,Po,Ly)}subtract(C){return this.add(C.negate())}wNAF(C){return O.wNAFCached(this,C,_.normalizeZ)}multiply(C){let B=C;mn("scalar",B,gn,o);let{p:Z,f:we}=this.wNAF(B);return _.normalizeZ([Z,we])[0]}multiplyUnsafe(C,B=_.ZERO){let Z=C;if(mn("scalar",Z,Ai,o),Z===Ai)return k;if(this.is0()||Z===gn)return this;return O.wNAFCachedUnsafe(this,Z,_.normalizeZ,B)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,o).is0()}toAffine(C){return E(this,C)}clearCofactor(){let{h:C}=t;if(C===gn)return this;return this.multiplyUnsafe(C)}static fromHex(C,B=!1){let{d:Z,a:we}=t,Pe=r.BYTES;C=It("pointHex",C,Pe),Pi("zip215",B);let je=C.slice(),De=C[Pe-1];je[Pe-1]=De&-129;let Ce=hu(je),V=B?u:r.ORDER;mn("pointHex.y",Ce,Ai,V);let se=d(Ce*Ce),le=d(se-gn),be=d(Z*se-we),{isValid:ie,value:Fe}=h(le,be);if(!ie)throw Error("Point.fromHex: invalid y coordinate");let Kt=(Fe&gn)===gn,Ve=(De&128)!==0;if(!B&&Fe===Ai&&Ve)throw Error("Point.fromHex: x=0 and x_0=1");if(Ve!==Kt)Fe=d(-Fe);return _.fromAffine({x:Fe,y:Ce})}static fromPrivateKey(C){let{scalar:B}=P(C);return T.multiply(B)}toRawBytes(){let{x:C,y:B}=this.toAffine(),Z=Hd(B,r.BYTES);return Z[Z.length-1]|=C&gn?128:0,Z}toHex(){return js(this.toRawBytes())}}_.BASE=new _(t.Gx,t.Gy,gn,d(t.Gx*t.Gy)),_.ZERO=new _(Ai,gn,gn,Ai);let{BASE:T,ZERO:k}=_,O=G_(_,s*8);function z(C){return xt(C,o)}function L(C){return z(hu(C))}function P(C){let B=r.BYTES;C=It("private key",C,B);let Z=It("hashed private key",i(C),2*B),we=y(Z.slice(0,B)),Pe=Z.slice(B,2*B),je=L(we);return{head:we,prefix:Pe,scalar:je}}function F(C){let{head:B,prefix:Z,scalar:we}=P(C),Pe=T.multiply(we),je=Pe.toRawBytes();return{head:B,prefix:Z,scalar:we,point:Pe,pointBytes:je}}function G(C){return F(C).pointBytes}function ue(C=Uint8Array.of(),...B){let Z=Tr(...B);return L(i(x(Z,It("context",C),!!n)))}function W(C,B,Z={}){if(C=It("message",C),n)C=n(C);let{prefix:we,scalar:Pe,pointBytes:je}=F(B),De=ue(Z.context,we,C),Ce=T.multiply(De).toRawBytes(),V=ue(Z.context,Ce,je,C),se=z(De+V*Pe);mn("signature.s",se,Ai,o);let le=Tr(Ce,Hd(se,r.BYTES));return It("result",le,r.BYTES*2)}let H=phe;function fe(C,B,Z,we=H){let{context:Pe,zip215:je}=we,De=r.BYTES;if(C=It("signature",C,2*De),B=It("message",B),Z=It("publicKey",Z,De),je!==void 0)Pi("zip215",je);if(n)B=n(B);let Ce=hu(C.slice(De,2*De)),V,se,le;try{V=_.fromHex(Z,je),se=_.fromHex(C.slice(0,De),je),le=T.multiplyUnsafe(Ce)}catch(Fe){return!1}if(!je&&V.isSmallOrder())return!1;let be=ue(Pe,se.toRawBytes(),V.toRawBytes(),B);return se.add(V.multiplyUnsafe(be)).subtract(le).clearCofactor().equals(_.ZERO)}return T._setWindowSize(8),{CURVE:t,getPublicKey:G,sign:W,verify:fe,ExtendedPoint:_,utils:{getExtendedPublicKey:F,randomPrivateKey:()=>a(r.BYTES),precompute(C=8,B=_.BASE){return B._setWindowSize(C),B.multiply(BigInt(3)),B}}}}vu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var NR=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),FF=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),t$e=BigInt(0),bhe=BigInt(1),qF=BigInt(2),r$e=BigInt(3),xhe=BigInt(5),vhe=BigInt(8);function _he(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=NR,s=e*e%i*e%i,c=Yt(s,qF,i)*s%i,u=Yt(c,bhe,i)*e%i,d=Yt(u,xhe,i)*u%i,p=Yt(d,t,i)*d%i,m=Yt(p,r,i)*p%i,h=Yt(m,o,i)*m%i,y=Yt(h,n,i)*h%i,x=Yt(y,n,i)*h%i,S=Yt(x,t,i)*d%i;return{pow_p_5_8:Yt(S,qF,i)*e%i,b2:s}}function whe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function She(e,t){let r=NR,o=xt(t*t*t,r),n=xt(o*o*t,r),i=_he(e*n).pow_p_5_8,a=xt(e*o*i,r),s=xt(t*a*a,r),c=a,u=xt(a*FF,r),d=s===e,p=s===xt(-e,r),m=s===xt(-e*FF,r);if(d)a=c;if(p||m)a=u;if(AF(a,r))a=xt(-a,r);return{isValid:d||p,value:a}}var HF=(()=>Sa(NR,void 0,!0))(),The=(()=>({a:HF.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:HF,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:vhe,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:yF,randomBytes:Fd,adjustScalarBytes:whe,uvRatio:She}))(),Z_=(()=>BF(The))();ug();fo();function W_(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=Z_.utils.randomPrivateKey();return{publicKey:Z_.getPublicKey(e),privateKey:e}}function K_(e){return lu(e.publicKey)}function J_(e){return lu(e.privateKey)}function GF(e,t){return{publicKey:ig(e),privateKey:ig(t)}}function VF(e){return lu(xa(e))}function ZF(e,t,r,o){return`${e.toUpperCase()}
136
+ `}class mR{constructor(e=L3.stdin,t=L3.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new fR,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}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 e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}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(e){return new Promise((t)=>{let r=U3(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var N_={name:"@0xmonaco/mcp-server",version:"1.0.45",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",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.45","@0xmonaco/types":"1.0.45","@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 M_=["read","market-maker","full"],Ei=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],pRe=Ei.map((e)=>e.name),j3=Ei.filter((e)=>e.authMode==="public").map((e)=>e.name),fRe=Ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),mRe=Ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),hRe=Ei.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),gRe=Ei.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),F3=Ei.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name),Lme=new Map(Ei.map((e)=>[e.name,e.sideEffect]));function q3(e){let t=Lme.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var H3={read:0,"market-maker":1,full:2},hR=j3,gR=Object.fromEntries(Ei.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),G3=Object.fromEntries(Object.entries(gR).map(([e,t])=>[e,t.capability])),xRe=new Set(F3);function V3(e){let t=gR[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function Z3(e){return V3(e)==="read"}function W3(e,t){if(t.network==="mainnet"&&gR[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(hR.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return H3[t.capability]>=H3[V3(e)]}var jme=new Set([...hR,...Object.keys(G3)]),Fme={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 K3(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function su(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let o=["mainnet","development","staging","local"],n=e.MONACO_NETWORK;if(t&&!n)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${o.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=n||"mainnet";if(!o.includes(i))throw Error(`MONACO_NETWORK must be one of: ${o.join(", ")}.`);let a=i,s=e.MONACO_CAPABILITY;if(s&&!M_.includes(s))throw Error(`MONACO_CAPABILITY must be one of: ${M_.join(", ")}.`);let c=s||"read",u=K3(e.MONACO_TOOL_ALLOWLIST),d=K3(e.MONACO_TOOL_DENYLIST),p=[...u,...d].filter((y)=>!jme.has(y)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||Fme[a],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");h=y}return{privateKey:t,clientId:r,network:a,seiRpcUrl:m,capability:c,allow:u,deny:d,delegatedOwnerUserId:h}}function qme(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function lo(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>lo(r));let t={};for(let[r,o]of Object.entries(e))t[qme(r)]=typeof o==="object"&&o!==null?lo(o):o;return t}fo();ug();fo();zR();vu();bu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ai=BigInt(0),gn=BigInt(1),MF=BigInt(2),dhe=BigInt(8),phe={zip215:!0};function fhe(e){let t=pg(e);return Go(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function BF(e){let t=fhe(e),{Fp:r,n:o,prehash:n,hash:i,randomBytes:a,nByteLength:s,h:c}=t,u=MF<<BigInt(s*8)-gn,d=r.create,p=Sa(t.n,t.nBitLength);function m(C,B){let Z=r.sqr(C),we=r.sqr(B),Pe=r.add(r.mul(t.a,Z),we),je=r.add(r.ONE,r.mul(t.d,r.mul(Z,we)));return r.eql(Pe,je)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((C,B)=>{try{return{isValid:!0,value:r.sqrt(C*r.inv(B))}}catch(Z){return{isValid:!1,value:Ai}}}),y=t.adjustScalarBytes||((C)=>C),x=t.domain||((C,B,Z)=>{if(Pi("phflag",Z),B.length||Z)throw Error("Contexts/pre-hash are not supported");return C});function S(C,B,Z=!1){let we=Z?gn:Ai;mn("coordinate "+C,B,we,u)}function v(C){if(!(C instanceof _))throw Error("ExtendedPoint expected")}let E=Gd((C,B)=>{let{ex:Z,ey:we,ez:Pe}=C,je=C.is0();if(B==null)B=je?dhe:r.inv(Pe);let De=d(Z*B),Ce=d(we*B),V=d(Pe*B);if(je)return{x:Ai,y:gn};if(V!==gn)throw Error("invZ was invalid");return{x:De,y:Ce}}),w=Gd((C)=>{let{a:B,d:Z}=t;if(C.is0())throw Error("bad point: ZERO");let{ex:we,ey:Pe,ez:je,et:De}=C,Ce=d(we*we),V=d(Pe*Pe),se=d(je*je),le=d(se*se),be=d(Ce*B),ie=d(se*d(be+V)),Fe=d(le+d(Z*d(Ce*V)));if(ie!==Fe)throw Error("bad point: equation left != right (1)");let Kt=d(we*Pe),Ve=d(je*De);if(Kt!==Ve)throw Error("bad point: equation left != right (2)");return!0});class _{constructor(C,B,Z,we){S("x",C),S("y",B),S("z",Z,!0),S("t",we),this.ex=C,this.ey=B,this.ez=Z,this.et=we,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof _)throw Error("extended point not allowed");let{x:B,y:Z}=C||{};return S("x",B),S("y",Z),new _(B,Z,gn,d(B*Z))}static normalizeZ(C){let B=wa(r,C.map((Z)=>Z.ez));return C.map((Z,we)=>Z.toAffine(B[we])).map(_.fromAffine)}static msm(C,B){return V_(_,p,C,B)}_setWindowSize(C){O.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){v(C);let{ex:B,ey:Z,ez:we}=this,{ex:Pe,ey:je,ez:De}=C,Ce=d(B*De),V=d(Pe*we),se=d(Z*De),le=d(je*we);return Ce===V&&se===le}is0(){return this.equals(_.ZERO)}negate(){return new _(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:C}=t,{ex:B,ey:Z,ez:we}=this,Pe=d(B*B),je=d(Z*Z),De=d(MF*d(we*we)),Ce=d(C*Pe),V=B+Z,se=d(d(V*V)-Pe-je),le=Ce+je,be=le-De,ie=Ce-je,Fe=d(se*be),Kt=d(le*ie),Ve=d(se*ie),at=d(be*le);return new _(Fe,Kt,at,Ve)}add(C){v(C);let{a:B,d:Z}=t,{ex:we,ey:Pe,ez:je,et:De}=this,{ex:Ce,ey:V,ez:se,et:le}=C,be=d(we*Ce),ie=d(Pe*V),Fe=d(De*Z*le),Kt=d(je*se),Ve=d((we+Pe)*(Ce+V)-be-ie),at=Kt-Fe,pr=Kt+Fe,_r=d(ie-B*be),Bf=d(Ve*at),ul=d(pr*_r),Ly=d(Ve*_r),Po=d(at*pr);return new _(Bf,ul,Po,Ly)}subtract(C){return this.add(C.negate())}wNAF(C){return O.wNAFCached(this,C,_.normalizeZ)}multiply(C){let B=C;mn("scalar",B,gn,o);let{p:Z,f:we}=this.wNAF(B);return _.normalizeZ([Z,we])[0]}multiplyUnsafe(C,B=_.ZERO){let Z=C;if(mn("scalar",Z,Ai,o),Z===Ai)return k;if(this.is0()||Z===gn)return this;return O.wNAFCachedUnsafe(this,Z,_.normalizeZ,B)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,o).is0()}toAffine(C){return E(this,C)}clearCofactor(){let{h:C}=t;if(C===gn)return this;return this.multiplyUnsafe(C)}static fromHex(C,B=!1){let{d:Z,a:we}=t,Pe=r.BYTES;C=It("pointHex",C,Pe),Pi("zip215",B);let je=C.slice(),De=C[Pe-1];je[Pe-1]=De&-129;let Ce=hu(je),V=B?u:r.ORDER;mn("pointHex.y",Ce,Ai,V);let se=d(Ce*Ce),le=d(se-gn),be=d(Z*se-we),{isValid:ie,value:Fe}=h(le,be);if(!ie)throw Error("Point.fromHex: invalid y coordinate");let Kt=(Fe&gn)===gn,Ve=(De&128)!==0;if(!B&&Fe===Ai&&Ve)throw Error("Point.fromHex: x=0 and x_0=1");if(Ve!==Kt)Fe=d(-Fe);return _.fromAffine({x:Fe,y:Ce})}static fromPrivateKey(C){let{scalar:B}=P(C);return T.multiply(B)}toRawBytes(){let{x:C,y:B}=this.toAffine(),Z=Hd(B,r.BYTES);return Z[Z.length-1]|=C&gn?128:0,Z}toHex(){return js(this.toRawBytes())}}_.BASE=new _(t.Gx,t.Gy,gn,d(t.Gx*t.Gy)),_.ZERO=new _(Ai,gn,gn,Ai);let{BASE:T,ZERO:k}=_,O=G_(_,s*8);function z(C){return xt(C,o)}function L(C){return z(hu(C))}function P(C){let B=r.BYTES;C=It("private key",C,B);let Z=It("hashed private key",i(C),2*B),we=y(Z.slice(0,B)),Pe=Z.slice(B,2*B),je=L(we);return{head:we,prefix:Pe,scalar:je}}function F(C){let{head:B,prefix:Z,scalar:we}=P(C),Pe=T.multiply(we),je=Pe.toRawBytes();return{head:B,prefix:Z,scalar:we,point:Pe,pointBytes:je}}function G(C){return F(C).pointBytes}function ue(C=Uint8Array.of(),...B){let Z=Tr(...B);return L(i(x(Z,It("context",C),!!n)))}function W(C,B,Z={}){if(C=It("message",C),n)C=n(C);let{prefix:we,scalar:Pe,pointBytes:je}=F(B),De=ue(Z.context,we,C),Ce=T.multiply(De).toRawBytes(),V=ue(Z.context,Ce,je,C),se=z(De+V*Pe);mn("signature.s",se,Ai,o);let le=Tr(Ce,Hd(se,r.BYTES));return It("result",le,r.BYTES*2)}let H=phe;function fe(C,B,Z,we=H){let{context:Pe,zip215:je}=we,De=r.BYTES;if(C=It("signature",C,2*De),B=It("message",B),Z=It("publicKey",Z,De),je!==void 0)Pi("zip215",je);if(n)B=n(B);let Ce=hu(C.slice(De,2*De)),V,se,le;try{V=_.fromHex(Z,je),se=_.fromHex(C.slice(0,De),je),le=T.multiplyUnsafe(Ce)}catch(Fe){return!1}if(!je&&V.isSmallOrder())return!1;let be=ue(Pe,se.toRawBytes(),V.toRawBytes(),B);return se.add(V.multiplyUnsafe(be)).subtract(le).clearCofactor().equals(_.ZERO)}return T._setWindowSize(8),{CURVE:t,getPublicKey:G,sign:W,verify:fe,ExtendedPoint:_,utils:{getExtendedPublicKey:F,randomPrivateKey:()=>a(r.BYTES),precompute(C=8,B=_.BASE){return B._setWindowSize(C),B.multiply(BigInt(3)),B}}}}vu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var NR=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),FF=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),t$e=BigInt(0),bhe=BigInt(1),qF=BigInt(2),r$e=BigInt(3),xhe=BigInt(5),vhe=BigInt(8);function _he(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=NR,s=e*e%i*e%i,c=Yt(s,qF,i)*s%i,u=Yt(c,bhe,i)*e%i,d=Yt(u,xhe,i)*u%i,p=Yt(d,t,i)*d%i,m=Yt(p,r,i)*p%i,h=Yt(m,o,i)*m%i,y=Yt(h,n,i)*h%i,x=Yt(y,n,i)*h%i,S=Yt(x,t,i)*d%i;return{pow_p_5_8:Yt(S,qF,i)*e%i,b2:s}}function whe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function She(e,t){let r=NR,o=xt(t*t*t,r),n=xt(o*o*t,r),i=_he(e*n).pow_p_5_8,a=xt(e*o*i,r),s=xt(t*a*a,r),c=a,u=xt(a*FF,r),d=s===e,p=s===xt(-e,r),m=s===xt(-e*FF,r);if(d)a=c;if(p||m)a=u;if(AF(a,r))a=xt(-a,r);return{isValid:d||p,value:a}}var HF=(()=>Sa(NR,void 0,!0))(),The=(()=>({a:HF.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:HF,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:vhe,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:yF,randomBytes:Fd,adjustScalarBytes:whe,uvRatio:She}))(),Z_=(()=>BF(The))();ug();fo();function W_(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=Z_.utils.randomPrivateKey();return{publicKey:Z_.getPublicKey(e),privateKey:e}}function K_(e){return lu(e.publicKey)}function J_(e){return lu(e.privateKey)}function GF(e,t){return{publicKey:ig(e),privateKey:ig(t)}}function VF(e){return lu(xa(e))}function ZF(e,t,r,o){return`${e.toUpperCase()}
137
137
  ${t}
138
138
  ${r}
139
139
  ${o}`}function WF(e,t){return`WS-AUTH
@@ -143,14 +143,14 @@ ${t}`}function Y_(e,t){return lu(Z_.sign(jd(t),e))}var mg=[0.0001,0.001,0.01,0.1
143
143
  `;mo();et();function hV(e){let t=(()=>{if(typeof e==="string")return Wd(e);if(typeof e.raw==="string")return e.raw;return Tt(e.raw)})(),r=Wd(`${mV}${ht(t)}`);return Vr([r,t])}function R1(e,t){return Ut(hV(e),t)}async function gV(e,{address:t,message:r,factory:o,factoryData:n,signature:i,...a}){let s=R1(r);return pe(e,lc,"verifyHash")({address:t,factory:o,factoryData:n,hash:s,signature:i,...a})}Ra();et();Yo();ur();wu();pt();class OO extends j{constructor({domain:e}){super(`Invalid domain "${vt(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class CO extends j{constructor({primaryType:e,types:t}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(t))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class zO extends j{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}Aa();mo();et();_$();function yV(e){let{domain:t,message:r,primaryType:o,types:n}=e,i=(a,s)=>{for(let c of a){let{name:u,type:d}=c,p=s[u],m=d.match(yw);if(m&&(typeof p==="number"||typeof p==="bigint")){let[x,S,v]=m;ge(p,{signed:S==="int",size:Number.parseInt(v,10)/8})}if(d==="address"&&typeof p==="string"&&!fr(p))throw new bn({address:p});let h=d.match(Iq);if(h){let[x,S]=h;if(S&&ht(p)!==Number.parseInt(S,10))throw new s$({expectedSize:Number.parseInt(S,10),givenSize:ht(p)})}let y=n[d];if(y)r0e(d),i(y,p)}};if(n.EIP712Domain&&t){if(typeof t!=="object")throw new OO({domain:t});i(n.EIP712Domain,t)}if(o!=="EIP712Domain")if(n[o])i(n[o],r);else throw new CO({primaryType:o,types:n})}function bV({domain:e}){return[typeof e?.name==="string"&&{name:"name",type:"string"},e?.version&&{name:"version",type:"string"},(typeof e?.chainId==="number"||typeof e?.chainId==="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function r0e(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new zO({type:e})}function xV(e){let{domain:t={},message:r,primaryType:o}=e,n={EIP712Domain:bV({domain:t}),...e.types};yV({domain:t,message:r,primaryType:o,types:n});let i=["0x1901"];if(t)i.push(n0e({domain:t,types:n}));if(o!=="EIP712Domain")i.push(vV({data:r,primaryType:o,types:n}));return Ut(Vr(i))}function n0e({domain:e,types:t}){return vV({data:e,primaryType:"EIP712Domain",types:t})}function vV({data:e,primaryType:t,types:r}){let o=_V({data:e,primaryType:t,types:r});return Ut(o)}function _V({data:e,primaryType:t,types:r}){let o=[{type:"bytes32"}],n=[o0e({primaryType:t,types:r})];for(let i of r[t]){let[a,s]=SV({types:r,name:i.name,type:i.type,value:e[i.name]});o.push(a),n.push(s)}return vn(o,n)}function o0e({primaryType:e,types:t}){let r=en(i0e({primaryType:e,types:t}));return Ut(r)}function i0e({primaryType:e,types:t}){let r="",o=wV({primaryType:e,types:t});o.delete(e);let n=[e,...Array.from(o).sort()];for(let i of n)r+=`${i}(${t[i].map(({name:a,type:s})=>`${s} ${a}`).join(",")})`;return r}function wV({primaryType:e,types:t},r=new Set){let n=e.match(/^\w*/u)?.[0];if(r.has(n)||t[n]===void 0)return r;r.add(n);for(let i of t[n])wV({primaryType:i.type,types:t},r);return r}function SV({types:e,name:t,type:r,value:o}){if(e[r]!==void 0)return[{type:"bytes32"},Ut(_V({data:o,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},Ut(o)];if(r==="string")return[{type:"bytes32"},Ut(en(o))];if(r.lastIndexOf("]")===r.length-1){let n=r.slice(0,r.lastIndexOf("[")),i=o.map((a)=>SV({name:t,type:n,types:e,value:a}));return[{type:"bytes32"},Ut(vn(i.map(([a])=>a),i.map(([,a])=>a)))]}return[{type:r},o]}async function TV(e,t){let{address:r,factory:o,factoryData:n,signature:i,message:a,primaryType:s,types:c,domain:u,...d}=t,p=xV({message:a,primaryType:s,types:c,domain:u});return pe(e,lc,"verifyHash")({address:r,factory:o,factoryData:n,hash:p,signature:i,...d})}Ma();var NO=new Map,EV=new Map,a0e=0;function qn(e,t,r){let o=++a0e,n=()=>NO.get(e)||[],i=()=>{let d=n();NO.set(e,d.filter((p)=>p.id!==o))},a=()=>{let d=n();if(!d.some((m)=>m.id===o))return;let p=EV.get(e);if(d.length===1&&p){let m=p();if(m instanceof Promise)m.catch(()=>{})}i()},s=n();if(NO.set(e,[...s,{id:o,fns:t}]),s&&s.length>0)return a;let c={};for(let d in t)c[d]=(...p)=>{let m=n();if(m.length===0)return;for(let h of m)h.fns[d]?.(...p)};let u=r(c);if(typeof u==="function")EV.set(e,u);return a}async function py(e){return new Promise((t)=>setTimeout(t,e))}function fy(e,{delay:t=100,retryCount:r=2,shouldRetry:o=()=>!0}={}){return new Promise((n,i)=>{let a=async({count:s=0}={})=>{let c=async({error:u})=>{let d=typeof t==="function"?t({count:s,error:u}):t;if(d)await py(d);a({count:s+1})};try{let u=await e();n(u)}catch(u){if(s<r&&await o({count:s,error:u}))return c({error:u});i(u)}};a()})}xn();function Ui(e,{emitOnBegin:t,initialWaitTime:r,interval:o}){let n=!0,i=()=>n=!1;return(async()=>{let s;if(t)s=await e({unpoll:i});let c=await r?.(s)??o;await py(c);let u=async()=>{if(!n)return;await e({unpoll:i}),await py(o),u()};u()})(),i}function $1(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:o,onError:n,poll:i,pollingInterval:a=e.pollingInterval}){let s=(()=>{if(typeof i<"u")return i;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),c;return s?(()=>{let p=vt(["watchBlockNumber",e.uid,t,r,a]);return qn(p,{onBlockNumber:o,onError:n},(m)=>Ui(async()=>{try{let h=await pe(e,Di,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(h===c)return;if(h-c>1&&r)for(let y=c+1n;y<h;y++)m.onBlockNumber(y,c),c=y}if(c===void 0||h>c)m.onBlockNumber(h,c),c=h}catch(h){m.onError?.(h)}},{emitOnBegin:t,interval:a}))})():(()=>{let p=vt(["watchBlockNumber",e.uid,t,r]);return qn(p,{onBlockNumber:o,onError:n},(m)=>{let h=!0,y=()=>h=!1;return(async()=>{try{let x=(()=>{if(e.transport.type==="fallback"){let v=e.transport.transports.find((E)=>E.config.type==="webSocket"||E.config.type==="ipc");if(!v)return e.transport;return v.value}return e.transport})(),{unsubscribe:S}=await x.subscribe({params:["newHeads"],onData(v){if(!h)return;let E=qr(v.result?.number);m.onBlockNumber(E,c),c=E},onError(v){m.onError?.(v)}});if(y=S,!h)y()}catch(x){n?.(x)}})(),()=>y()})})()}async function IV(e,t){let{checkReplacement:r=!0,confirmations:o=1,hash:n,onReplaced:i,retryCount:a=6,retryDelay:s=({count:T})=>~~(1<<T)*200,timeout:c=180000}=t,u=vt(["waitForTransactionReceipt",e.uid,n]),d=(()=>{if(t.pollingInterval)return t.pollingInterval;if(e.chain?.experimental_preconfirmationTime)return e.chain.experimental_preconfirmationTime;return e.pollingInterval})(),p,m,h,y=!1,x,S,{promise:v,resolve:E,reject:w}=Zw(),_=c?setTimeout(()=>{S?.(),x?.(),w(new n2({hash:n}))},c):void 0;return x=qn(u,{onReplaced:i,resolve:E,reject:w},async(T)=>{if(h=await pe(e,Wp,"getTransactionReceipt")({hash:n}).catch(()=>{return}),h&&o<=1){clearTimeout(_),T.resolve(h),x?.();return}S=pe(e,$1,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:d,async onBlockNumber(k){let O=(L)=>{clearTimeout(_),S?.(),L(),x?.()},z=k;if(y)return;try{if(h){if(o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;O(()=>T.resolve(h));return}if(r&&!p)y=!0,await fy(async()=>{if(p=await pe(e,Zp,"getTransaction")({hash:n}),p.blockNumber)z=p.blockNumber},{delay:s,retryCount:a}),y=!1;if(h=await pe(e,Wp,"getTransactionReceipt")({hash:n}),o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;O(()=>T.resolve(h))}catch(L){if(L instanceof $g||L instanceof Og){if(!p){y=!1;return}try{m=p,y=!0;let P=await fy(()=>pe(e,kr,"getBlock")({blockNumber:z,includeTransactions:!0}),{delay:s,retryCount:a,shouldRetry:({error:ue})=>ue instanceof ny});y=!1;let F=P.transactions.find(({from:ue,nonce:W})=>ue===m.from&&W===m.nonce);if(!F)return;if(h=await pe(e,Wp,"getTransactionReceipt")({hash:F.hash}),o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;let G="replaced";if(F.to===m.to&&F.value===m.value&&F.input===m.input)G="repriced";else if(F.from===F.to&&F.value===0n)G="cancelled";O(()=>{T.onReplaced?.({reason:G,replacedTransaction:m,transaction:F,transactionReceipt:h}),T.resolve(h)})}catch(P){O(()=>T.reject(P))}}else O(()=>T.reject(L))}}})}),v}function PV(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:o=!1,onBlock:n,onError:i,includeTransactions:a,poll:s,pollingInterval:c=e.pollingInterval}){let u=(()=>{if(typeof s<"u")return s;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),d=a??!1,p;return u?(()=>{let y=vt(["watchBlocks",e.uid,t,r,o,d,c]);return qn(y,{onBlock:n,onError:i},(x)=>Ui(async()=>{try{let S=await pe(e,kr,"getBlock")({blockTag:t,includeTransactions:d});if(S.number!==null&&p?.number!=null){if(S.number===p.number)return;if(S.number-p.number>1&&r)for(let v=p?.number+1n;v<S.number;v++){let E=await pe(e,kr,"getBlock")({blockNumber:v,includeTransactions:d});x.onBlock(E,p),p=E}}if(p?.number==null||t==="pending"&&S?.number==null||S.number!==null&&S.number>p.number)x.onBlock(S,p),p=S}catch(S){x.onError?.(S)}},{emitOnBegin:o,interval:c}))})():(()=>{let y=!0,x=!0,S=()=>y=!1;return(async()=>{try{if(o)pe(e,kr,"getBlock")({blockTag:t,includeTransactions:d}).then((w)=>{if(!y)return;if(!x)return;n(w,void 0),x=!1}).catch(i);let v=(()=>{if(e.transport.type==="fallback"){let w=e.transport.transports.find((_)=>_.config.type==="webSocket"||_.config.type==="ipc");if(!w)return e.transport;return w.value}return e.transport})(),{unsubscribe:E}=await v.subscribe({params:["newHeads"],async onData(w){if(!y)return;let _=await pe(e,kr,"getBlock")({blockNumber:w.result?.number,includeTransactions:d}).catch(()=>{});if(!y)return;n(_,p),x=!1,p=_},onError(w){i?.(w)}});if(S=E,!y)S()}catch(v){i?.(v)}})(),()=>S()})()}ur();Bg();function kV(e,t){let{abi:r,address:o,args:n,batch:i=!0,eventName:a,fromBlock:s,onError:c,onLogs:u,poll:d,pollingInterval:p=e.pollingInterval,strict:m}=t;return(()=>{if(typeof d<"u")return d;if(typeof s==="bigint")return!0;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})()?(()=>{let S=m??!1,v=vt(["watchContractEvent",o,n,i,e.uid,a,p,S,s]);return qn(v,{onLogs:u,onError:c},(E)=>{let w;if(s!==void 0)w=s-1n;let _,T=!1,k=Ui(async()=>{if(!T){try{_=await pe(e,Xw,"createContractEventFilter")({abi:r,address:o,args:n,eventName:a,strict:S,fromBlock:s})}catch{}T=!0;return}try{let O;if(_)O=await pe(e,ac,"getFilterChanges")({filter:_});else{let z=await pe(e,Di,"getBlockNumber")({});if(w&&w<z)O=await pe(e,m1,"getContractEvents")({abi:r,address:o,args:n,eventName:a,fromBlock:w+1n,toBlock:z,strict:S});else O=[];w=z}if(O.length===0)return;if(i)E.onLogs(O);else for(let z of O)E.onLogs([z])}catch(O){if(_&&O instanceof xo)T=!1;E.onError?.(O)}},{emitOnBegin:!0,interval:p});return async()=>{if(_)await pe(e,cc,"uninstallFilter")({filter:_});k()}})})():(()=>{let S=m??!1,v=vt(["watchContractEvent",o,n,i,e.uid,a,p,S]),E=!0,w=()=>E=!1;return qn(v,{onLogs:u,onError:c},(_)=>((async()=>{try{let T=(()=>{if(e.transport.type==="fallback"){let z=e.transport.transports.find((L)=>L.config.type==="webSocket"||L.config.type==="ipc");if(!z)return e.transport;return z.value}return e.transport})(),k=a?Bi({abi:r,eventName:a,args:n}):[],{unsubscribe:O}=await T.subscribe({params:["logs",{address:o,topics:k}],onData(z){if(!E)return;let L=z.result;try{let{eventName:P,args:F}=Hu({abi:r,data:L.data,topics:L.topics,strict:m}),G=Ar(L,{args:F,eventName:P});_.onLogs([G])}catch(P){let F,G;if(P instanceof Hs||P instanceof _u){if(m)return;F=P.abiItem.name,G=P.abiItem.inputs?.some((W)=>!(("name"in W)&&W.name))}let ue=Ar(L,{args:G?[]:{},eventName:F});_.onLogs([ue])}},onError(z){_.onError?.(z)}});if(w=O,!E)w()}catch(T){c?.(T)}})(),()=>w()))})()}ur();Bg();function AV(e,{address:t,args:r,batch:o=!0,event:n,events:i,fromBlock:a,onError:s,onLogs:c,poll:u,pollingInterval:d=e.pollingInterval,strict:p}){let m=(()=>{if(typeof u<"u")return u;if(typeof a==="bigint")return!0;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),h=p??!1;return m?(()=>{let S=vt(["watchEvent",t,r,o,e.uid,n,d,a]);return qn(S,{onLogs:c,onError:s},(v)=>{let E;if(a!==void 0)E=a-1n;let w,_=!1,T=Ui(async()=>{if(!_){try{w=await pe(e,e1,"createEventFilter")({address:t,args:r,event:n,events:i,strict:h,fromBlock:a})}catch{}_=!0;return}try{let k;if(w)k=await pe(e,ac,"getFilterChanges")({filter:w});else{let O=await pe(e,Di,"getBlockNumber")({});if(E&&E!==O)k=await pe(e,Vp,"getLogs")({address:t,args:r,event:n,events:i,fromBlock:E+1n,toBlock:O});else k=[];E=O}if(k.length===0)return;if(o)v.onLogs(k);else for(let O of k)v.onLogs([O])}catch(k){if(w&&k instanceof xo)_=!1;v.onError?.(k)}},{emitOnBegin:!0,interval:d});return async()=>{if(w)await pe(e,cc,"uninstallFilter")({filter:w});T()}})})():(()=>{let S=!0,v=()=>S=!1;return(async()=>{try{let E=(()=>{if(e.transport.type==="fallback"){let k=e.transport.transports.find((O)=>O.config.type==="webSocket"||O.config.type==="ipc");if(!k)return e.transport;return k.value}return e.transport})(),w=i??(n?[n]:void 0),_=[];if(w){if(_=[w.flatMap((O)=>Bi({abi:[O],eventName:O.name,args:r}))],n)_=_[0]}let{unsubscribe:T}=await E.subscribe({params:["logs",{address:t,topics:_}],onData(k){if(!S)return;let O=k.result;try{let{eventName:z,args:L}=Hu({abi:w??[],data:O.data,topics:O.topics,strict:h}),P=Ar(O,{args:L,eventName:z});c([P])}catch(z){let L,P;if(z instanceof Hs||z instanceof _u){if(p)return;L=z.abiItem.name,P=z.abiItem.inputs?.some((G)=>!(("name"in G)&&G.name))}let F=Ar(O,{args:P?[]:{},eventName:L});c([F])}},onError(k){s?.(k)}});if(v=T,!S)v()}catch(E){s?.(E)}})(),()=>v()})()}function RV(e,{batch:t=!0,onError:r,onTransactions:o,poll:n,pollingInterval:i=e.pollingInterval}){return(typeof n<"u"?n:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let u=vt(["watchPendingTransactions",e.uid,t,i]);return qn(u,{onTransactions:o,onError:r},(d)=>{let p,m=Ui(async()=>{try{if(!p)try{p=await pe(e,t1,"createPendingTransactionFilter")({});return}catch(y){throw m(),y}let h=await pe(e,ac,"getFilterChanges")({filter:p});if(h.length===0)return;if(t)d.onTransactions(h);else for(let y of h)d.onTransactions([y])}catch(h){d.onError?.(h)}},{emitOnBegin:!0,interval:i});return async()=>{if(p)await pe(e,cc,"uninstallFilter")({filter:p});m()}})})():(()=>{let u=!0,d=()=>u=!1;return(async()=>{try{let{unsubscribe:p}=await e.transport.subscribe({params:["newPendingTransactions"],onData(m){if(!u)return;let h=m.result;o([h])},onError(m){r?.(m)}});if(d=p,!u)d()}catch(p){r?.(p)}})(),()=>d()})()}function $V(e){let{scheme:t,statement:r,...o}=e.match(s0e)?.groups??{},{chainId:n,expirationTime:i,issuedAt:a,notBefore:s,requestId:c,...u}=e.match(c0e)?.groups??{},d=e.split("Resources:")[1]?.split(`
144
144
  - `).slice(1);return{...o,...u,...n?{chainId:Number(n)}:{},...i?{expirationTime:new Date(i)}:{},...a?{issuedAt:new Date(a)}:{},...s?{notBefore:new Date(s)}:{},...c?{requestId:c}:{},...d?{resources:d}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var s0e=/^(?:(?<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)?/,c0e=/(?: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>.+))?/;Aa();Up();function OV(e){let{address:t,domain:r,message:o,nonce:n,scheme:i,time:a=new Date}=e;if(r&&o.domain!==r)return!1;if(n&&o.nonce!==n)return!1;if(i&&o.scheme!==i)return!1;if(o.expirationTime&&a>=o.expirationTime)return!1;if(o.notBefore&&a<o.notBefore)return!1;try{if(!o.address)return!1;if(!fr(o.address,{strict:!1}))return!1;if(t&&!ni(o.address,t))return!1}catch{return!1}return!0}async function CV(e,t){let{address:r,domain:o,message:n,nonce:i,scheme:a,signature:s,time:c=new Date,...u}=t,d=$V(n);if(!d.address)return!1;if(!OV({address:r,domain:o,message:d,nonce:i,scheme:a,time:c}))return!1;let m=R1(n);return lc(e,{address:d.address,hash:m,signature:s,...u})}async function zV(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}Ma();async function NV(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:o}){let n=await e.request({method:"eth_sendRawTransactionSync",params:o?[t,o]:[t]},{retryCount:0}),a=(e.chain?.formatters?.transactionReceipt?.format||h1)(n);if(a.status==="reverted"&&r)throw new r2({receipt:a});return a}function MV(e){return{call:(t)=>wo(e,t),createAccessList:(t)=>Qw(e,t),createBlockFilter:()=>_G(e),createContractEventFilter:(t)=>Xw(e,t),createEventFilter:(t)=>e1(e,t),createPendingTransactionFilter:()=>t1(e),estimateContractGas:(t)=>o7(e,t),estimateGas:(t)=>Hp(e,t),getBalance:(t)=>i7(e,t),getBlobBaseFee:()=>a7(e),getBlock:(t)=>kr(e,t),getBlockNumber:(t)=>Di(e,t),getBlockTransactionCount:(t)=>u7(e,t),getBytecode:(t)=>qu(e,t),getChainId:()=>qp(e),getCode:(t)=>qu(e,t),getContractEvents:(t)=>m1(e,t),getDelegation:(t)=>d7(e,t),getEip712Domain:(t)=>p7(e,t),getEnsAddress:(t)=>pG(e,t),getEnsAvatar:(t)=>bG(e,t),getEnsName:(t)=>xG(e,t),getEnsResolver:(t)=>vG(e,t),getEnsText:(t)=>Yw(e,t),getFeeHistory:(t)=>m7(e,t),estimateFeesPerGas:(t)=>VG(e,t),getFilterChanges:(t)=>ac(e,t),getFilterLogs:(t)=>h7(e,t),getGasPrice:()=>Fp(e),getLogs:(t)=>Vp(e,t),getProof:(t)=>y7(e,t),estimateMaxPriorityFeePerGas:(t)=>GG(e,t),fillTransaction:(t)=>p1(e,t),getStorageAt:(t)=>b7(e,t),getTransaction:(t)=>Zp(e,t),getTransactionConfirmations:(t)=>x7(e,t),getTransactionCount:(t)=>c1(e,t),getTransactionReceipt:(t)=>Wp(e,t),multicall:(t)=>v7(e,t),prepareTransactionRequest:(t)=>f1(e,t),readContract:(t)=>mr(e,t),sendRawTransaction:(t)=>zV(e,t),sendRawTransactionSync:(t)=>NV(e,t),simulate:(t)=>oy(e,t),simulateBlocks:(t)=>oy(e,t),simulateCalls:(t)=>K7(e,t),simulateContract:(t)=>J7(e,t),verifyHash:(t)=>lc(e,t),verifyMessage:(t)=>gV(e,t),verifySiweMessage:(t)=>CV(e,t),verifyTypedData:(t)=>TV(e,t),uninstallFilter:(t)=>cc(e,t),waitForTransactionReceipt:(t)=>IV(e,t),watchBlocks:(t)=>PV(e,t),watchBlockNumber:(t)=>$1(e,t),watchContractEvent:(t)=>kV(e,t),watchEvent:(t)=>AV(e,t),watchPendingTransactions:(t)=>RV(e,t)}}function MO(e){let{key:t="public",name:r="Public Client"}=e;return uq({...e,key:t,name:r,type:"publicClient"}).extend(MV)}Ou();pt();class BO extends j{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}A2();Ou();function BV(e,{errorInstance:t=Error("timed out"),timeout:r,signal:o}){return new Promise((n,i)=>{(async()=>{let a;try{let s=new AbortController;if(r>0)a=setTimeout(()=>{if(o)s.abort();else i(t)},r);n(await e({signal:s?.signal||null}))}catch(s){if(s?.name==="AbortError")i(t);i(s)}finally{clearTimeout(a)}})()})}function u0e(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var DO=u0e();function DV(e,t={}){let{url:r,headers:o}=l0e(e);return{async request(n){let{body:i,fetchFn:a=t.fetchFn??fetch,onRequest:s=t.onRequest,onResponse:c=t.onResponse,timeout:u=t.timeout??1e4}=n,d={...t.fetchOptions??{},...n.fetchOptions??{}},{headers:p,method:m,signal:h}=d;try{let y=await BV(async({signal:S})=>{let v={...d,body:Array.isArray(i)?vt(i.map((T)=>({jsonrpc:"2.0",id:T.id??DO.take(),...T}))):vt({jsonrpc:"2.0",id:i.id??DO.take(),...i}),headers:{...o,"Content-Type":"application/json",...p},method:m||"POST",signal:h||(u>0?S:null)},E=new Request(r,v),w=await s?.(E,v)??{...v,url:r};return await a(w.url??r,w)},{errorInstance:new Bw({body:i,url:r}),timeout:u,signal:!0});if(c)await c(y);let x;if(y.headers.get("Content-Type")?.startsWith("application/json"))x=await y.json();else{x=await y.text();try{x=JSON.parse(x||"{}")}catch(S){if(y.ok)throw S;x={error:x}}}if(!y.ok){if(typeof x.error?.code==="number"&&typeof x.error?.message==="string")return x;throw new ei({body:i,details:vt(x.error)||y.statusText,headers:y.headers,status:y.status,url:r})}return x}catch(y){if(y instanceof ei)throw y;if(y instanceof Bw)throw y;throw new ei({body:i,cause:y,url:r})}}}}function l0e(e){try{let t=new URL(e),r=(()=>{if(t.username){let o=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(o)}`}}}return})();return{url:t.toString(),...r}}catch{return{url:e}}}pt();Ou();Bg();Tg();var O1=new ka(8192);function UV(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(O1.get(r))return O1.get(r);let o=e().finally(()=>O1.delete(r));return O1.set(r,o),o}function LV(e,t={}){return async(r,o={})=>{let{dedupe:n=!1,methods:i,retryDelay:a=150,retryCount:s=3,uid:c}={...t,...o},{method:u}=r;if(i?.exclude?.includes(u))throw new Js(Error("method not supported"),{method:u});if(i?.include&&!i.include.includes(u))throw new Js(Error("method not supported"),{method:u});let d=n?p0e(`${c}.${vt(r)}`):void 0;return UV(()=>fy(async()=>{try{return await e(r)}catch(p){let m=p;switch(m.code){case lp.code:throw new lp(m);case dp.code:throw new dp(m);case pp.code:throw new pp(m,{method:r.method});case fp.code:throw new fp(m);case Ua.code:throw new Ua(m);case xo.code:throw new xo(m);case mp.code:throw new mp(m);case hp.code:throw new hp(m);case gp.code:throw new gp(m);case Js.code:throw new Js(m,{method:r.method});case Cu.code:throw new Cu(m);case yp.code:throw new yp(m);case zu.code:throw new zu(m);case bp.code:throw new bp(m);case xp.code:throw new xp(m);case vp.code:throw new vp(m);case _p.code:throw new _p(m);case wp.code:throw new wp(m);case Sp.code:throw new Sp(m);case Tp.code:throw new Tp(m);case Ep.code:throw new Ep(m);case Ip.code:throw new Ip(m);case Pp.code:throw new Pp(m);case kp.code:throw new kp(m);case Ap.code:throw new Ap(m);case 5000:throw new zu(m);case Rp.code:throw new Rp(m);default:if(p instanceof j)throw p;throw new l2(m)}}},{delay:({count:p,error:m})=>{if(m&&m instanceof ei){let h=m?.headers?.get("Retry-After");if(h?.match(/\d/))return Number.parseInt(h,10)*1000}return~~(1<<p)*a},retryCount:s,shouldRetry:({error:p})=>d0e(p)}),{enabled:n,id:d})}}function d0e(e){if("code"in e&&typeof e.code==="number"){if(e.code===-1)return!0;if(e.code===Cu.code)return!0;if(e.code===Ua.code)return!0;if(e.code===429)return!0;return!1}if(e instanceof ei&&e.status){if(e.status===403)return!0;if(e.status===408)return!0;if(e.status===413)return!0;if(e.status===429)return!0;if(e.status===500)return!0;if(e.status===502)return!0;if(e.status===503)return!0;if(e.status===504)return!0;return!1}return!0}function p0e(e,t=0){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);r=Math.imul(r^i,2654435761),o=Math.imul(o^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>16,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&o)+(r>>>0)).toString(36)}function jV({key:e,methods:t,name:r,request:o,retryCount:n=3,retryDelay:i=150,timeout:a,type:s},c){let u=rw();return{config:{key:e,methods:t,name:r,request:o,retryCount:n,retryDelay:i,timeout:a,type:s},request:LV(o,{methods:t,retryCount:n,retryDelay:i,uid:u}),value:c}}function UO(e,t={}){let{batch:r,fetchFn:o,fetchOptions:n,key:i="http",methods:a,name:s="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:d,raw:p}=t;return({chain:m,retryCount:h,timeout:y})=>{let{batchSize:x=1000,wait:S=0}=typeof r==="object"?r:{},v=t.retryCount??h,E=y??t.timeout??1e4,w=e||m?.rpcUrls.default.http[0];if(!w)throw new BO;let _=DV(w,{fetchFn:o,fetchOptions:n,onRequest:c,onResponse:u,timeout:E});return jV({key:i,methods:a,name:s,async request({method:T,params:k}){let O={method:T,params:k},{schedule:z}=Ww({id:w,wait:S,shouldSplitBatch(G){return G.length>x},fn:(G)=>_.request({body:G}),sort:(G,ue)=>G.id-ue.id}),L=async(G)=>r?z(G):[await _.request({body:G})],[{error:P,result:F}]=await L(O);if(p)return{error:P,result:F};if(P)throw new $u({body:O,error:P,url:w});return F},retryCount:v,retryDelay:d,timeout:E,type:"http"},{fetchOptions:n,url:w})}}Ri();function C1(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(o){return(n)=>{let i=typeof n==="function"?n(o):n,a={...o,...i};return Object.assign(a,{extend:r(a)})}}return Object.assign(t,{extend:r(t)})}var LO=C1({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 jO=C1({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});fo();var z1=on(X_(),1);var f0e="@0xmonaco/core",FO={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},qO="Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",m0e=new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2}) (${qO}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`),h0e=new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-(${qO})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`),g0e=new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (${qO}) ([ \\d]\\d) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$`);function y0e(e,t,r,o,n,i){let a=new Date(Date.now()),s=Math.floor(a.getUTCFullYear()/100)*100+e,c=Date.UTC(s,t,r,o,n,i),u=Date.UTC(a.getUTCFullYear()+50,a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds());return c>u?s-100:s}function b0e(e){let t,r,o,n,i,a,s=m0e.exec(e),c=h0e.exec(e),u=g0e.exec(e);if(s)t=Number(s[1]),r=FO[s[2]],o=Number(s[3]),n=Number(s[4]),i=Number(s[5]),a=Number(s[6]);else if(c){if(t=Number(c[1]),r=FO[c[2]],n=Number(c[4]),i=Number(c[5]),a=Number(c[6]),r===void 0)return;o=y0e(Number(c[3]),r,t,n,i,a)}else if(u)r=FO[u[1]],t=Number((u[2]??"").trim()),n=Number(u[3]),i=Number(u[4]),a=Number(u[5]),o=Number(u[6]);else return;if(r===void 0)return;let d=Date.UTC(o,r,t,n,i,a),p=new Date(d);if(p.getUTCFullYear()!==o||p.getUTCMonth()!==r||p.getUTCDate()!==t||p.getUTCHours()!==n||p.getUTCMinutes()!==i||p.getUTCSeconds()!==a)return;return d}class tt{apiUrl;sessionKeypair;serverKey;retryOptions;constructor(e,t){this.apiUrl=e,this.retryOptions={maxRetries:t?.maxRetries??3,baseDelayMs:t?.baseDelayMs??1000}}setSessionKeypair(e){this.sessionKeypair=e?GF(e.publicKey,e.privateKey):void 0}setServerKey(e){this.serverKey=e}parseRequestBody(e){if(!e)return;if(typeof e==="string")try{return JSON.parse(e)}catch{return e}if(e instanceof FormData){let t={};return e.forEach((r,o)=>{t[o]=r instanceof File?`[File: ${r.name}]`:r}),t}if(e instanceof URLSearchParams){let t={};return e.forEach((r,o)=>{t[o]=r}),t}if(e instanceof Blob)return{type:"[Blob]",size:e.size,contentType:e.type};if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return{type:"[ArrayBuffer]",size:e instanceof ArrayBuffer?e.byteLength:e.byteLength};if(typeof ReadableStream<"u"&&e instanceof ReadableStream)return{type:"[ReadableStream]",note:"Stream body not captured for logging"};return{type:"[Unknown]",bodyType:typeof e}}extractResponseMetadata(e){if(!e)return{};let t=e.get("x-request-id")||e.get("request-id")||e.get("x-correlation-id")||void 0,r=e.get("retry-after"),o;if(r!==null){let n=r.trim();if(/^\d+$/.test(n))o=Number.parseInt(n,10);else{let i=b0e(n);if(i!==void 0)o=Math.max(0,Math.ceil((i-Date.now())/1000))}}return{requestId:t,retryAfter:o}}async executeRequest(e,t,r,o){let n,i={"User-Agent":f0e,...r.headers};try{n=await fetch(e,{...r,headers:i})}catch(u){throw new cr(`Network request failed for ${t}`,{endpoint:e,cause:u instanceof Error?u:Error(String(u)),requestBody:o})}let a,s=n.headers?.get("content-type")||"unknown",c=n.clone?n.clone():n;try{a=await n.json()}catch(u){let d;try{d=await c.text()}catch{d="[Unable to read response body]"}if(!n.ok){let p=`API request failed: ${n.status}. Response is not JSON (Content-Type: ${s})`,{requestId:m,retryAfter:h}=this.extractResponseMetadata(n.headers);throw new cr(p,{endpoint:e,statusCode:n.status,responseBody:{rawResponse:d.substring(0,500),contentType:s,parseError:u instanceof Error?u.message:String(u)},cause:u instanceof Error?u:void 0,requestBody:o,requestId:m,retryAfter:h})}if(d.trim()==="")return;throw new cr(`Expected JSON response but received ${s}`,{endpoint:e,statusCode:n.status,responseBody:{rawResponse:d.substring(0,500),contentType:s},cause:u instanceof Error?u:void 0,requestBody:o})}if(!n.ok){let u=a!==null&&typeof a==="object"?a:void 0,d=(typeof u?.message==="string"?u.message:void 0)||(typeof u?.error==="string"?u.error:void 0)||`API request failed: ${n.status}`,{requestId:p,retryAfter:m}=this.extractResponseMetadata(n.headers);throw new cr(d,{endpoint:e,statusCode:n.status,responseBody:a,requestBody:o,requestId:p,retryAfter:m})}return a}async makeAuthenticatedRequest(e,t={}){if(!this.sessionKeypair)throw new cr("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:z1.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,o=this.parseRequestBody(t.body),n=this.buildSignatureHeaders(e,t);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json",...n,...t.headers}},o)}buildSignatureHeaders(e,t){if(!this.sessionKeypair)throw new cr("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:z1.StatusCodes.UNAUTHORIZED});let r=(t.method??"GET").toUpperCase(),o=Date.now(),n=typeof t.body==="string"?jd(t.body):new Uint8Array(0),i=VF(n),a=ZF(r,e,o,i),s=Y_(this.sessionKeypair.privateKey,a);return{"X-Monaco-PublicKey":lu(this.sessionKeypair.publicKey),"X-Monaco-Timestamp":String(o),"X-Monaco-Signature":s}}async makeBackendRequest(e,t={}){if(!this.serverKey)throw new cr("Server key not set. Call setServerKey(sk_...) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:z1.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,o=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json","x-server-key":this.serverKey,...t.headers}},o)}async makePublicRequest(e,t={}){let r=`${this.apiUrl}${e}`,o=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json",...t.headers}},o)}}function ut(e){return encodeURIComponent(e)}function qt(e,t){if(!t)return e;let r=new URLSearchParams;for(let[n,i]of Object.entries(t))if(i!==void 0)r.set(n,String(i));let o=r.toString();return o?`${e}?${o}`:e}var ce={orders:{create:()=>"/api/v1/orders",list:(e)=>qt("/api/v1/orders",e),get:(e)=>`/api/v1/orders/${ut(e)}`,replace:(e)=>`/api/v1/orders/${ut(e)}`,cancel:()=>"/api/v1/orders/cancel",batchCancel:()=>"/api/v1/orders/batch-cancel",batchCancelAll:()=>"/api/v1/orders/batch-cancel-all",batchCancelAllByPair:(e)=>`/api/v1/orders/batch-cancel-all/${ut(e)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:(e)=>qt("/api/v1/orders/conditional",e),cancelConditional:(e)=>`/api/v1/orders/conditional/${ut(e)}`,getConditional:(e)=>`/api/v1/orders/conditional/${ut(e)}`,createTwap:()=>"/api/v1/orders/twap",listTwap:(e)=>qt("/api/v1/orders/twap",e),getTwap:(e)=>`/api/v1/orders/twap/${ut(e)}`,cancelTwap:(e)=>`/api/v1/orders/twap/${ut(e)}/cancel`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:(e)=>`/api/v1/delegated-agents/${ut(e)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:(e)=>`/api/v1/withdrawals/${ut(String(e))}`,list:(e)=>qt("/api/v1/withdrawals",e)},market:{listTradingPairs:(e)=>qt("/api/v1/market/pairs",e),getTradingPair:(e)=>`/api/v1/market/pairs/${ut(e)}`,getCandles:(e,t,r)=>qt(`/api/v1/market/pairs/charts/candlestick/${ut(e)}/${ut(t)}`,r),getMarketMetadata:(e)=>`/api/v1/market/pairs/${ut(e)}/metadata`,getPerpMarketConfig:(e)=>`/api/v1/market/pairs/${ut(e)}/perp/config`,getPerpMarketSummary:(e)=>`/api/v1/market/pairs/${ut(e)}/perp/summary`,getMarkPrice:(e)=>`/api/v1/market/pairs/${ut(e)}/mark-price`,getIndexPrice:(e)=>`/api/v1/market/pairs/${ut(e)}/index-price`,getFundingState:(e)=>`/api/v1/market/pairs/${ut(e)}/funding`,listFundingHistory:(e,t)=>qt(`/api/v1/market/pairs/${ut(e)}/funding/history`,t),listAllFundingHistory:(e)=>qt("/api/v1/market/funding/history",e),getOpenInterest:(e)=>`/api/v1/market/pairs/${ut(e)}/open-interest`,getScreener:(e)=>qt("/api/v1/market/screener",e),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:(e,t)=>qt(`/api/v1/orderbook/${ut(e)}`,t)},trades:{publicByPair:(e,t)=>qt(`/api/v1/trades/${ut(e)}`,t),byId:(e)=>`/api/v1/trades/by-id/${ut(e)}`,user:(e)=>qt("/api/v1/accounts/trades",e)},applications:{orders:(e)=>qt("/api/v1/applications/orders",e),users:(e)=>qt("/api/v1/applications/users",e),movements:(e)=>qt("/api/v1/applications/movements",e),balances:(e)=>qt("/api/v1/applications/balances",e),stats:(e)=>qt("/api/v1/applications/stats",e)},subAccounts:{list:()=>"/api/v1/accounts/sub-accounts",createLimit:()=>"/api/v1/accounts/sub-accounts/limits",getLimits:(e)=>`/api/v1/accounts/sub-accounts/${ut(e)}/limits`,limit:(e,t)=>`/api/v1/accounts/sub-accounts/${ut(e)}/limits/${ut(t)}`},faucet:{mint:()=>"/api/v1/faucet/mint",info:()=>"/api/v1/faucet/info"},sweeper:{register:()=>"/api/v1/sweeper/register"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:(e)=>qt("/api/v1/positions",e),get:(e)=>`/api/v1/positions/${ut(e)}`,close:(e)=>`/api/v1/positions/${ut(e)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:(e)=>`/api/v1/positions/${ut(e)}/risk`,attachTpSl:(e)=>`/api/v1/positions/${ut(e)}/tp-sl`,history:(e)=>qt("/api/v1/positions/history",e),pnlHistory:(e,t)=>qt(`/api/v1/positions/${ut(e)}/pnl/history`,t)},marginAccounts:{list:(e)=>qt("/api/v1/margin/accounts",e),parentSummary:(e)=>qt("/api/v1/margin/parent-margin-account",e),summary:(e,t)=>qt(`/api/v1/margin/accounts/${ut(e)}`,t),availableCollateral:(e)=>qt("/api/v1/margin/collateral/available",e),transferIn:(e)=>`/api/v1/margin/accounts/${ut(e)}/collateral/transfer-in`,transferInParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-in",transferInRiskBucket:()=>"/api/v1/margin/risk-buckets/collateral/transfer-in",transferOut:(e)=>`/api/v1/margin/accounts/${ut(e)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:(e,t)=>qt(`/api/v1/margin/accounts/${ut(e)}/movements`,t),parentMovements:(e)=>qt("/api/v1/margin/parent-margin-account/movements",e),simulateParentMarginOrderRisk:()=>"/api/v1/margin/parent-margin-account/simulate-order-risk",simulateOrderRisk:(e)=>`/api/v1/margin/accounts/${ut(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 N1 extends tt{async getApplicationConfig(){let e=await this.makeAuthenticatedRequest("/api/v1/applications/config",{method:"GET"});return{id:e.id,name:e.name,allowedOrigins:e.allowedOrigins,webhookUrl:e.webhookUrl,vaultContractAddress:e.vaultContractAddress,clientId:e.clientId}}async listApplicationOrders(e){return await this.makeBackendRequest(ce.applications.orders(e))}async listApplicationUsers(e){return await this.makeBackendRequest(ce.applications.users(e))}async listApplicationMovements(e){return await this.makeBackendRequest(ce.applications.movements(e))}async listApplicationBalances(e){return await this.makeBackendRequest(ce.applications.balances(e))}async getApplicationStats(e){return await this.makeBackendRequest(ce.applications.stats(e))}}class HO extends tt{async upsertDelegatedAgent(e){return this.makeAuthenticatedRequest(ce.delegatedAgents.list(),{method:"POST",body:JSON.stringify({agentAddress:e.agentAddress,name:e.name,expiresAt:e.expiresAt,allowedActions:e.allowedActions,allowedTradingPairIds:e.allowedTradingPairIds,allowedMarginAccountIds:e.allowedMarginAccountIds,allowedOrderTypes:e.allowedOrderTypes,allowedTimeInForce:e.allowedTimeInForce,maxLeverage:e.maxLeverage,maxOrderNotional:e.maxOrderNotional,maxOpenOrders:e.maxOpenOrders})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(ce.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(ce.delegatedAgents.owners())}async revokeDelegatedAgent(e){return this.makeAuthenticatedRequest(ce.delegatedAgents.byId(e),{method:"DELETE"})}async createDelegatedSession(e){return this.makeAuthenticatedRequest(ce.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:e.ownerUserId,sessionPublicKey:e.sessionPublicKey})})}}class M1 extends tt{async mint(e){return await this.makeAuthenticatedRequest(ce.faucet.mint(),{method:"POST",body:JSON.stringify({turnstileToken:e.turnstileToken})})}async getInfo(){return await this.makeAuthenticatedRequest(ce.faucet.info(),{method:"GET"})}}var GO=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:f.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:f.string().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:f.string().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:f.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:f.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((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:f.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),x0e=f.object({applicationName:f.string().nullable().optional(),applicationTakerFee:f.string(),applicationTakerFeeBps:f.number(),buyOrderLockAmount:f.string().nullable().optional(),makerTotalReceipt:f.string(),monacoMakerRebate:f.string(),monacoMakerRebateBps:f.number(),monacoMakerRebateBpsExact:f.string(),monacoTakerFee:f.string(),monacoTakerFeeBps:f.number(),monacoTakerFeeBpsExact:f.string(),notional:f.string(),takerTotalPayment:f.string(),totalTakerFees:f.string(),maxQuantity:f.string().nullable(),maxQuantityRaw:f.string().nullable(),slippageToleranceBps:f.number().nullable()}),VO=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),FV=f.object({tierLevel:f.number().int(),minVolumeThreshold:f.string(),makerFeeBps:f.string(),takerFeeBps:f.string()}),v0e=f.object({currentTierLevel:f.number().int(),weightedVolume14d:f.string(),spotVolume14d:f.string(),perpVolume14d:f.string(),volumeToNextTier:f.string().nullable().optional(),nextTierLevel:f.number().int().nullable().optional(),feeSchedule:f.array(FV)});var qV=f.object({token:f.string(),available:f.string()}),_0e=f.object({balances:f.array(qV)}),w0e=f.object({code:f.string(),createdAt:f.string(),customCode:f.string(),isCustom:f.boolean(),display:f.string()}),HV=f.enum(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),S0e=f.object({available:f.boolean(),reason:f.preprocess((e)=>e===""||e===null?void 0:e,HV.optional())}),ZO=f.object({code:f.string().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),T0e=f.object({code:f.string()}),WO=f.object({token:f.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:f.string().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),E0e=f.object({rewardsBalance:f.string(),tradingBalance:f.string()});var B1=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];class GV extends Error{issues;constructor(e){let t=e.issues.map((r)=>{let o=r.path.join(".");return`${o?`${o}: `:""}${r.message}`});super(`Validation failed:
145
145
  - ${t.join(`
146
- - `)}`);this.name="ValidationError",this.issues=e.issues}getErrors(){let e={};for(let t of this.issues){let r=t.path.join(".");e[r||"root"]=t.message}return e}}function _e(e,t){let r=e.safeParse(t);if(!r.success)throw new GV(r.error);return r.data}var Yp=f.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),my=f.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),j1=f.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),hy=f.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),VV=f.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),KO=f.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Qp=f.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),gt=f.string().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),Ae=f.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Ju=f.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),ZV=f.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),gy=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),I0e=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),D1=f.object({triggerPrice:gt,orderType:Qp,limitPrice:gt.optional(),quantity:gt.optional(),closePosition:f.boolean().optional(),timeInForce:KO.optional(),slippageToleranceBps:gy.optional(),expiresAt:Ju.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),U1=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,JO=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),WV=f.object({tradingPairId:Ae,side:Yp,quantity:gt,price:gt,options:f.object({tradingMode:my.optional(),useMasterBalance:f.boolean().optional(),expirationDate:Ju.optional(),timeInForce:VV.optional(),marginAccountId:Ae.optional(),marginMode:j1.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:gt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:hy.optional(),leverage:gt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional(),takeProfit:D1.optional(),stopLoss:D1.optional()}).optional()}).refine((e)=>JO(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!U1(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!U1(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),KV=f.object({tradingPairId:Ae,side:Yp,quantity:gt,options:f.object({tradingMode:my.optional(),slippageTolerance:ZV,marginAccountId:Ae.optional(),marginMode:j1.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:gt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:hy.optional(),leverage:gt.optional(),reduceOnly:f.boolean().optional(),takeProfit:D1.optional(),stopLoss:D1.optional()}).optional()}).refine((e)=>JO(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!U1(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!U1(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),JV=f.object({orderId:Ae,remainingQuantityTarget:gt.optional()}),YV=f.object({orderId:Ae,newOrder:f.object({price:gt.optional(),quantity:gt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()})}),QV=f.object({status:f.union([f.enum(B1),f.array(f.enum(B1)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Ae.optional(),tradingMode:my.optional(),marginAccountId:Ae.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),t2t=f.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),r2t=f.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),P0e=f.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),n2t=f.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),YO=f.object({conditionalOrderId:Ae}),XV=f.object({marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),state:P0e.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),k0e=f.enum(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),A0e=f.union([f.number().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),f.string().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),eZ=f.object({tradingPairId:Ae,side:Yp,quantity:gt,options:f.object({durationSeconds:A0e.optional(),startTime:Ju.optional(),endTime:Ju.optional(),limitPrice:gt.optional(),slippageToleranceBps:I0e.optional(),randomize:f.boolean().optional(),reduceOnly:f.boolean().optional(),tradingMode:my.optional(),marginAccountId:Ae.optional(),riskBucketId:Ae.optional(),marginMode:j1.optional(),leverage:gt.optional(),strategyKey:f.string().min(1).max(128).optional(),useMasterBalance:f.boolean().optional(),clientTwapId:f.string().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}),QO=f.object({twapOrderId:Ae}),tZ=f.object({state:k0e.optional(),tradingPairId:Ae.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),R0e=f.object({tradingPairId:Ae,orderType:Qp,side:Yp,price:gt.optional(),quantity:gt,tradingMode:my.optional(),slippageTolerance:ZV,useMasterBalance:f.boolean().optional(),expirationDate:Ju.optional(),timeInForce:VV.optional(),marginAccountId:Ae.optional(),marginMode:j1.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:gt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:hy.optional(),leverage:gt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>JO(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),L1=100,rZ=f.object({orders:f.array(R0e).min(1,"At least one order is required").max(L1,`At most ${L1} orders per batch request`)}),$0e=f.object({orderId:Ae,price:gt.optional(),quantity:gt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),nZ=f.object({orders:f.array($0e).min(1,"At least one order is required").max(L1,`At most ${L1} orders per batch request`)});var XO=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),oZ=XO.extend({state:f.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:Ae.optional()}),iZ=f.object({marginAccountId:Ae,tradingPairId:Ae.optional()}),aZ=f.object({tradingPairId:Ae.optional()}).optional(),sZ=f.object({asset:f.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),O0e=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:gt,tradingPairId:Ae.optional(),strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:f.enum(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),F1=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:gt}),C0e=f.object({tradingPairId:Ae,strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional()}),z0e=f.array(Ae).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),cZ=C0e.extend({marginMode:f.literal("ISOLATED").optional(),selectedTradingPairIds:f.never().optional()}),uZ=f.object({marginMode:f.literal("CROSS"),selectedTradingPairIds:z0e,strategyKey:f.never().optional()}),N0e=uZ.extend({tradingPairId:f.never().optional()}),eC=f.object({marginAccountId:Ae,request:O0e}),lZ=f.object({request:F1}),dZ=f.object({request:f.union([F1.merge(cZ).strict(),F1.merge(N0e).strict()])}),pZ=f.object({request:F1}),fZ=XO.extend({marginAccountId:Ae,movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}),mZ=XO.extend({movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),tC=f.object({tradingPairId:Ae,side:Yp,positionSide:hy.optional(),orderType:Qp,price:gt.optional(),quantity:gt,leverage:gt.optional(),reduceOnly:f.boolean().optional()}),rC=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:f.ZodIssueCode.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:f.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},hZ=tC.strict().superRefine(rC),M0e=tC.merge(cZ).strict().superRefine(rC),B0e=tC.merge(uZ).strict().superRefine(rC).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),D0e=f.union([M0e,B0e]),gZ=f.object({marginAccountId:Ae,request:hZ}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),yZ=f.object({request:hZ}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),bZ=f.object({request:D0e}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var xZ=f.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"'}),U0e=31536000000,L0e=946684800000,q1=f.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(L0e,{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((e)=>e<=Date.now()+U0e,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),l2t=f.object({tradingPairId:Ae,interval:xZ,startTime:q1,endTime:q1}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),d2t=f.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")'}),j0e=f.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),vZ=f.object({tradingPairId:Ae,interval:xZ,startTime:q1.optional(),endTime:q1.optional(),limit:j0e,priceType:f.enum(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var p2t=f.object({tradingPairId:Ae}),f2t=f.object({query:f.string().min(1,"Search query cannot be empty").optional(),pageSize:f.number().int().min(1).max(100).optional(),page:f.number().int().min(1).optional()}),Li=f.object({tradingPairId:Ae});var wZ=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),F0e=f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),q0e=f.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),yy=f.object({positionId:Ae}),SZ=wZ.extend({marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),status:F0e.optional()}),TZ=yy,EZ=yy.extend({request:f.object({closeType:q0e,limitPrice:gt.optional(),slippageToleranceBps:gy.optional(),quantity:gt.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),IZ=f.object({tradingPairId:Ae.optional(),slippageToleranceBps:gy.optional()}),PZ=yy,_Z=f.object({triggerPrice:gt,orderType:Qp,limitPrice:gt.optional(),quantity:gt.optional(),closePosition:f.boolean().optional(),timeInForce:KO.optional(),slippageToleranceBps:gy.optional(),expiresAt:Ju.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),kZ=yy.extend({request:f.object({takeProfit:_Z.optional(),stopLoss:_Z.optional(),oco:f.boolean().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),AZ=wZ.extend({positionId:Ae.optional(),marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),reductionOnly:f.boolean().optional()}),H0e=f.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),RZ=yy.extend({params:f.object({interval:H0e,startTime:f.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:f.number().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var G0e=f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),V0e=f.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),$Z=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.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:G0e.optional(),transactionType:V0e.optional(),assetId:Ae.optional()}),OZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:Ae.optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),CZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.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:Ae.optional(),positionId:Ae.optional(),marginAccountId:Ae.optional()});var S2t=f.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),nC=f.union([f.string().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),f.bigint().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),zZ=f.object({assetId:Ae,amount:nC,autoWait:f.boolean().optional()}),NZ=f.object({assetId:Ae,amount:nC,autoWait:f.boolean().optional(),target:f.enum(["spot","margin"]).optional(),options:f.object({asErc20:f.boolean().optional()}).optional()}),MZ=f.object({assetId:Ae,amount:nC,destination:f.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:f.boolean().optional(),source:f.enum(["spot","margin"]).optional()}),T2t=f.object({assetId:Ae});class H1 extends tt{async simulateFees(e){let t=_e(GO,e),r=new URLSearchParams;if(r.append("tradingPairId",t.tradingPairId),r.append("side",t.side),r.append("price",t.price),r.append("quantity",t.quantity),t.orderType!==void 0)r.append("orderType",t.orderType);if(t.slippageToleranceBps!==void 0)r.append("slippageToleranceBps",String(t.slippageToleranceBps));let o=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(o,{method:"GET"})}async getMyFeeTier(e){let t=_e(VO,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let o=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(o,{method:"GET"})}}class G1 extends tt{async listMarginAccounts(e){if(e)_e(oZ,e);return await this.makeAuthenticatedRequest(ce.marginAccounts.list(e?{page:e.page,pageSize:e.pageSize,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return _e(iZ,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ce.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return _e(aZ,e),await this.makeAuthenticatedRequest(ce.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return _e(sZ,e),await this.makeAuthenticatedRequest(ce.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return _e(eC,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return _e(lZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return _e(dZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds})})}async transferCollateralFromMarginAccount(e,t){return _e(eC,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferOut(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey,marginMode:t.marginMode})})}async transferCollateralFromParentMarginAccount(e){return _e(pZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return _e(fZ,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ce.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return _e(mZ,e),await this.makeAuthenticatedRequest(ce.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return _e(gZ,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ce.marginAccounts.simulateOrderRisk(e),{method:"POST",body:JSON.stringify({tradingPairId:t.tradingPairId,side:t.side,positionSide:t.positionSide,orderType:t.orderType,price:t.price,quantity:t.quantity,leverage:t.leverage,reduceOnly:t.reduceOnly})})}async simulateParentMarginOrderRisk(e){return _e(yZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.simulateParentMarginOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}async simulateRiskBucketOrderRisk(e){return _e(bZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}}class V1 extends tt{async getPaginatedTradingPairs(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.marketType)t.append("marketType",e.marketType);if(e?.baseToken)t.append("baseToken",e.baseToken);if(e?.quoteToken)t.append("quoteToken",e.quoteToken);if(e?.isActive!==void 0)t.append("isActive",e.isActive.toString());if(e?.category)t.append("category",e.category);let r=t.toString(),o=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(o)}async getTradingPair(e){return _e(Li,{tradingPairId:e}),(await this.makePublicRequest(ce.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((o)=>o.symbol===e)}async getCandlesticks(e,t,r){_e(vZ,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit,priceType:r?.priceType});let o=new URLSearchParams;if(r?.startTime!==void 0)o.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)o.append("endTime",r.endTime.toString());if(r?.limit!==void 0)o.append("limit",r.limit.toString());if(r?.priceType!==void 0)o.append("priceType",r.priceType);let n=o.toString(),i=n?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${n}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getPerpMarketSummary(e))}async getMarkPrice(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getMarkPrice(e))}async getIndexPrice(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getIndexPrice(e))}async getFundingState(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getFundingState(e))}async listFundingHistory(e,t){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return await this.makePublicRequest(ce.market.listAllFundingHistory(e))}async getOpenInterest(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(ce.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(ce.market.getMarketStats())}}class Z1 extends tt{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:o,magnitude:n,denomination:i}=t,a=new URLSearchParams;if(a.set("levels",String(r)),o)a.set("tradingMode",o);if(n!==void 0)a.set("magnitude",String(n));if(i)a.set("denomination",i.toLowerCase());let s=await this.makePublicRequest(`/api/v1/orderbook/${encodeURIComponent(e)}?${a.toString()}`);return{tradingPairId:s.tradingPairId,tradingMode:s.tradingMode,bids:s.data.bids.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),asks:s.data.asks.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),bestBid:s.data.bestBid,bestAsk:s.data.bestAsk,bidVolume:s.data.bidVolume,askVolume:s.data.askVolume,baseDecimals:s.baseDecimals,quoteDecimals:s.quoteDecimals,timestamp:s.timestamp,sequence:s.sequenceNumber}}}class W1 extends tt{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me",{method:"GET"})}async setTraderCode(e){let t=_e(ZO,{code:e});return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/pitpass/codes/available?${t}`,{method:"GET"});return{available:r.available,reason:r.reason?r.reason:void 0}}async getTraderCodeInfo(e){let t=encodeURIComponent(e.trim());return await this.makePublicRequest(`/api/v1/pitpass/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/balance",{method:"GET"})}async transferRewards(e){let t=_e(WO,e);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}}var by="/api/v1/accounts/me/portfolio";function K1(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class J1 extends tt{async getSummary(e){return await this.makeAuthenticatedRequest(K1(`${by}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(K1(`${by}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(K1(`${by}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(K1(`${by}/assets`,e))}async getMargin(){return await this.makeAuthenticatedRequest(`${by}/margin`)}}class Y1 extends tt{async listPositions(e){if(e)_e(SZ,e);return await this.makeAuthenticatedRequest(ce.positions.list(e))}async getPosition(e){return _e(TZ,{positionId:e}),await this.makeAuthenticatedRequest(ce.positions.get(e))}async closePosition(e,t){return _e(EZ,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ce.positions.close(e),{method:"POST",body:JSON.stringify({closeType:t.closeType,limitPrice:t.limitPrice,slippageToleranceBps:t.slippageToleranceBps,quantity:t.quantity})})}async batchCloseAllPositions(e){if(e)_e(IZ,e);return await this.makeAuthenticatedRequest(ce.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return _e(PZ,{positionId:e}),await this.makeAuthenticatedRequest(ce.positions.risk(e))}async attachPositionTpSl(e,t){return _e(kZ,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ce.positions.attachTpSl(e),{method:"POST",body:JSON.stringify({takeProfit:t.takeProfit?{triggerPrice:t.takeProfit.triggerPrice,orderType:t.takeProfit.orderType,limitPrice:t.takeProfit.limitPrice,quantity:t.takeProfit.quantity,closePosition:t.takeProfit.closePosition,timeInForce:t.takeProfit.timeInForce,slippageToleranceBps:t.takeProfit.slippageToleranceBps,expiresAt:t.takeProfit.expiresAt}:void 0,stopLoss:t.stopLoss?{triggerPrice:t.stopLoss.triggerPrice,orderType:t.stopLoss.orderType,limitPrice:t.stopLoss.limitPrice,quantity:t.stopLoss.quantity,closePosition:t.stopLoss.closePosition,timeInForce:t.stopLoss.timeInForce,slippageToleranceBps:t.stopLoss.slippageToleranceBps,expiresAt:t.stopLoss.expiresAt}:void 0,oco:t.oco})})}async listPositionHistory(e){if(e)_e(AZ,e);return await this.makeAuthenticatedRequest(ce.positions.history(e))}async getPositionPnlHistory(e,t){return _e(RZ,{positionId:e,params:t}),await this.makeAuthenticatedRequest(ce.positions.pnlHistory(e,t))}}class oC extends tt{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)_e($Z,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.entryType!==void 0)t.append("entryType",e.entryType);if(e?.transactionType!==void 0)t.append("transactionType",e.transactionType);if(e?.assetId!==void 0)t.append("assetId",e.assetId);let r=t.toString(),o=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(o)}async getUserBalances(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());let r=t.toString(),o=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(o)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new cr("assetId is required and cannot be empty",{endpoint:"/api/v1/accounts/balances/{assetId}"});let t=`/api/v1/accounts/balances/${e}`;return await this.makeAuthenticatedRequest(t)}async getPortfolioStats(e){let t=new URLSearchParams({period:e});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio?${t}`)}async getPortfolioChart(e,t){let r=new URLSearchParams({period:e,metric:t});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio/chart?${r}`)}async getUserTrades(e){if(e)_e(OZ,e);let t=e?.page!==void 0&&e?.pageToken===void 0,r=new URLSearchParams;if(t&&e?.page!==void 0)r.append("page",e.page.toString());if(e?.pageSize!==void 0)r.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)r.append("tradingPairId",e.tradingPairId);if(!t)r.append("pageToken",e?.pageToken??"");let o=r.toString(),n=o?`/api/v1/accounts/trades?${o}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(n)}async*iterateUserTrades(e){let t="";for(;;){let r=await this.getUserTrades({...e,pageToken:t});if(yield*r.trades,!r.nextPageToken)return;t=r.nextPageToken}}async listFundingPayments(e){if(e)_e(CZ,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);if(e?.positionId!==void 0)t.append("positionId",e.positionId);if(e?.marginAccountId!==void 0)t.append("marginAccountId",e.marginAccountId);let r=t.toString(),o=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(o)}}class Q1 extends tt{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class X1 extends tt{async list(){return await this.makeAuthenticatedRequest(ce.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(ce.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(ce.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(ce.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(ce.subAccounts.limit(e,t),{method:"DELETE"})}}class eS extends tt{async register(e){return await this.makePublicRequest(ce.sweeper.register(),{method:"POST",body:JSON.stringify(e)})}}function BZ(e){return{eventType:"trade",tradingPairId:e.tradingPairId,tradingMode:e.tradingMode.toUpperCase(),data:{tradeId:e.data.tradeId,price:e.data.price,quantity:e.data.quantity,makerSide:e.data.makerSide.toUpperCase(),executedAt:e.data.executedAt??""}}}class iC extends tt{async getTrades(e,t={}){let{page:r=1}=t,o=t.pageSize!=null&&t.pageSize>0?Math.min(t.pageSize,100):25,n=new URLSearchParams;if(r>1)n.set("page",String(r));return n.set("pageSize",String(o)),(await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}?${n.toString()}`)).trades.map(BZ)}async getTradeById(e){let t=await this.makePublicRequest(ce.trades.byId(e));return BZ(t)}}function tS(e){if(!e)return;return{triggerPrice:e.triggerPrice,orderType:e.orderType,limitPrice:e.limitPrice,timeInForce:e.timeInForce,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt,quantity:e.quantity,closePosition:e.closePosition}}class rS extends tt{async placeLimitOrder(e,t,r,o,n){_e(WV,{tradingPairId:e,side:t,quantity:r,price:o,options:n});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:o,quantity:r,tradingMode:n?.tradingMode||"SPOT",useMasterBalance:n?.useMasterBalance,expirationDate:n?.expirationDate,timeInForce:n?.timeInForce,marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,postOnly:n?.postOnly,clientOrderId:n?.clientOrderId,takeProfit:tS(n?.takeProfit),stopLoss:tS(n?.stopLoss)};return await this.makeAuthenticatedRequest(ce.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,o){_e(KV,{tradingPairId:e,side:t,quantity:r,options:o});let n={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:o?.slippageTolerance!==void 0?Math.round(o.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:o?.tradingMode||"SPOT",marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,takeProfit:tS(o?.takeProfit),stopLoss:tS(o?.stopLoss),clientOrderId:o?.clientOrderId};return await this.makeAuthenticatedRequest(ce.orders.create(),{method:"POST",body:JSON.stringify(n)})}async cancelOrder(e,t){_e(JV,{orderId:e,remainingQuantityTarget:t?.remainingQuantityTarget});let r={orderId:e,...t?.remainingQuantityTarget!==void 0&&{remainingQuantityTarget:t.remainingQuantityTarget}};return await this.makeAuthenticatedRequest(ce.orders.cancel(),{method:"POST",body:JSON.stringify(r)})}async cancelConditionalOrder(e){return _e(YO,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ce.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return _e(YO,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ce.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)_e(XV,e);let{page:t=1,pageSize:r=20,marginAccountId:o,tradingPairId:n,state:i}=e||{};return await this.makeAuthenticatedRequest(ce.orders.listConditional({page:t,pageSize:Math.min(Math.max(r,1),100),marginAccountId:o,tradingPairId:n,state:i}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(ce.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?ce.orders.batchCancelAllByPair(e):ce.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){_e(YV,{orderId:e,newOrder:t});let r={useMasterBalance:t.useMasterBalance??!1};if(t.price!==void 0)r.price=t.price;if(t.quantity!==void 0)r.quantity=t.quantity;if(t.postOnly!==void 0)r.postOnly=t.postOnly;if(t.clientOrderId!==void 0)r.clientOrderId=t.clientOrderId;return await this.makeAuthenticatedRequest(ce.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){_e(rZ,{orders:e});let t={orders:e.map((r)=>({tradingPairId:r.tradingPairId,orderType:r.orderType,side:r.side,price:r.price,quantity:r.quantity,tradingMode:r.tradingMode||"SPOT",slippageToleranceBps:r.slippageTolerance!==void 0?Math.round(r.slippageTolerance*1e4):void 0,useMasterBalance:r.useMasterBalance,expirationDate:r.expirationDate,timeInForce:r.timeInForce,marginAccountId:r.marginAccountId,marginMode:r.marginMode,riskBucketId:r.riskBucketId,riskBucketCollateral:r.riskBucketCollateral,strategyKey:r.strategyKey,positionSide:r.positionSide,leverage:r.leverage,reduceOnly:r.reduceOnly,postOnly:r.postOnly,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ce.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){_e(nZ,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ce.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)_e(QV,e);let{page:t,pageSize:r=10,status:o,tradingPairId:n,tradingMode:i,marginAccountId:a,pageToken:s}=e||{},c=r>0?r:10,u=t!==void 0&&s===void 0,d=Math.min(c,u?100:1000),p=new URLSearchParams;if(u){let y=t>0?t:1;p.append("page",y.toString())}p.append("pageSize",d.toString());let m=typeof o==="string"?o:o?.join(",");if(m)p.append("status",m);if(n)p.append("tradingPairId",n);if(i)p.append("tradingMode",i);if(a)p.append("marginAccountId",a);if(!u)p.append("pageToken",s??"");let h=`/api/v1/orders?${p.toString()}`;return await this.makeAuthenticatedRequest(h,{method:"GET"})}async*iterateOrders(e){let t="";for(;;){let r=await this.getPaginatedOrders({...e,pageToken:t});if(yield*r.orders,!r.nextPageToken)return;t=r.nextPageToken}}async getOrder(e){return{order:await this.makeAuthenticatedRequest(ce.orders.get(e),{method:"GET"}),status:"SUCCESS"}}async createTwapOrder(e,t,r,o){_e(eZ,{tradingPairId:e,side:t,quantity:r,options:o});let n={tradingPairId:e,side:t,quantity:r,durationSeconds:o.durationSeconds!==void 0?Number(o.durationSeconds):void 0,startTime:o.startTime,endTime:o.endTime,limitPrice:o.limitPrice,slippageToleranceBps:o.slippageToleranceBps,randomize:o.randomize,reduceOnly:o.reduceOnly,tradingMode:o.tradingMode||"SPOT",marginAccountId:o.marginAccountId,riskBucketId:o.riskBucketId,marginMode:o.marginMode,leverage:o.leverage,strategyKey:o.strategyKey,useMasterBalance:o.useMasterBalance,clientTwapId:o.clientTwapId};return await this.makeAuthenticatedRequest(ce.orders.createTwap(),{method:"POST",body:JSON.stringify(n)})}async cancelTwapOrder(e){return _e(QO,{twapOrderId:e}),await this.makeAuthenticatedRequest(ce.orders.cancelTwap(e),{method:"POST"})}async getTwapOrder(e){return _e(QO,{twapOrderId:e}),await this.makeAuthenticatedRequest(ce.orders.getTwap(e),{method:"GET"})}async listTwapOrders(e){if(e)_e(tZ,e);let{page:t=1,pageSize:r=20,state:o,tradingPairId:n}=e||{};return await this.makeAuthenticatedRequest(ce.orders.listTwap({page:t,pageSize:Math.min(Math.max(r,1),100),state:o,tradingPairId:n}),{method:"GET"})}}var aC=[{inputs:[{internalType:"address",name:"rollup_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Refunded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"RefundedNative",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Swept",type:"event"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"contract IRollup",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"nonpayable",type:"function"}];var sC=[{inputs:[{internalType:"address",name:"rollup_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"sweeper",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"string",name:"applicationId",type:"string"}],name:"SweeperDeployed",type:"event"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"deploy",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"implementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"contract IRollup",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"sweeperFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];var cC=[{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 UCt=new Uint8Array(32);var uC={vault:cC,sweeper:aC,sweeperFactory:sC};var Z0e=5000,W0e=300000,K0e=(e)=>new Promise((t)=>setTimeout(t,e));function DZ(e,t){return t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}class nS extends tt{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,o,n,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=o,this.profileAPI=n}setWalletClient(e){this.walletClient=e}async getVaultAddress(){return(await this.applicationsAPI.getApplicationConfig()).vaultContractAddress}async getClientId(){return(await this.applicationsAPI.getApplicationConfig()).clientId}async resolveAsset(e){let t,r;try{let o=await this.profileAPI.getUserBalanceByAssetId(e);t=o.token,r=o.wrappedNative===!0}catch(o){if(o instanceof cr){if(o.statusCode===404)throw new Ta(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:o});throw new Ta(`Failed to resolve asset ID '${e}': ${o.retryable?"Network error occurred":"API request failed"}`,{revertReason:o.retryable?"NETWORK_ERROR":"API_ERROR",cause:o})}throw new Ta(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:o instanceof Error?o:void 0})}return{tokenAddress:t,isWrappedNative:r}}async approve(e,t,r=!0){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");_e(zZ,{assetId:e,amount:t,autoWait:r});let o=await this.getVaultAddress(),{tokenAddress:n}=await this.resolveAsset(e),i=this.walletClient.account;if(!i)throw new Ft("No account available in wallet client","account");let a=i.getNonce?await i.getNonce():0n,s=await this.walletClient.writeContract({address:n,abi:iw,functionName:"approve",args:[o,t],chain:this.chain,account:i}),c={nonce:a,hash:s,status:"pending"};return await this.waitForTransaction(c,r)}async deposit(e,t,r=!0,o="spot",n={}){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");_e(NZ,{assetId:e,amount:t,autoWait:r,target:o,options:n});let i=await this.getVaultAddress(),a=await this.getClientId(),s=DZ(a,o),{tokenAddress:c,isWrappedNative:u}=await this.resolveAsset(e),d=u&&n.asErc20!==!0;if(!d){if(await this.needsApproval(e,t,n))throw new Ta(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${c}).`,{revertReason:"APPROVAL_REQUIRED"})}let p=this.walletClient.account;if(!p)throw new Ft("No account available in wallet client","account");let m;if(d)m=await this.walletClient.writeContract({address:i,abi:uC.vault,functionName:"depositNative",args:[p.address,s],account:p,chain:this.chain,value:t});else m=await this.walletClient.writeContract({address:i,abi:uC.vault,functionName:"depositERC20",args:[p.address,s,c,t],account:p,chain:this.chain});let h=p.getNonce?await p.getNonce():0n,y={hash:m,status:"pending",nonce:h};return await this.waitForTransaction(y,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??Z0e,o=t?.timeoutMs??W0e,n=Date.now()+o;for(;;){try{let{vaultAddress:i,calldata:a}=await this.makePublicRequest(`/api/v1/withdrawals/${e}`);if(a&&a!=="0x")return{vaultAddress:i,calldata:a}}catch(i){if(!(i instanceof cr&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>n)return null;await K0e(r)}}async withdraw(e,t,r=!0,o,n){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let i=this.walletClient.account;if(!i)throw new Ft("No account available in wallet client","account");let a=i.address.toLowerCase(),s=typeof o==="string"?o:"spot",c=typeof o==="string"?n:o;_e(MZ,{assetId:e,amount:t,destination:a,autoWait:r,source:s});let{withdrawalIndex:u}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:a,source:s})});if(!r)return{withdrawalIndex:u,status:"awaiting_proof"};let d=await this.pollWithdrawalCalldata(u,c);if(!d)return{withdrawalIndex:u,status:"awaiting_proof"};let{vaultAddress:p,calldata:m}=d,h;try{h=await this.walletClient.sendTransaction({to:p,data:m,account:i,chain:this.chain})}catch(v){throw new Ta(`Failed to submit executeWithdrawal for withdrawal ${u}: ${v instanceof Error?v.message:"unknown error"}`,{cause:v instanceof Error?v:void 0})}let y=i.getNonce?await i.getNonce():0n,x={hash:h,status:"pending",nonce:y};return{...await this.waitForTransaction(x,r),withdrawalIndex:u}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let o=this.walletClient.account;if(!o)throw new Ft("No account available in wallet client","account");let n=await this.pollWithdrawalCalldata(e,r);if(!n)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:a}=n,s;try{s=await this.walletClient.sendTransaction({to:i,data:a,account:o,chain:this.chain})}catch(p){throw new Ta(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${p instanceof Error?p.message:"unknown error"}`,{cause:p instanceof Error?p:void 0})}let c=o.getNonce?await o.getNonce():0n,u={hash:s,status:"pending",nonce:c};return{...await this.waitForTransaction(u,t),withdrawalIndex:e}}async getBalance(e){throw new cr("getBalance() is deprecated and no longer supported. Please use profileAPI.getUserBalances() or profileAPI.getUserBalanceByAssetId() instead for balance data.",{statusCode:410})}async getAllowance(e){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let t=await this.getVaultAddress(),o=(await this.walletClient.getAddresses())[0];if(!o)throw new Ft("No account found in wallet client.","walletClient");let{tokenAddress:n}=await this.resolveAsset(e);return await this.publicClient.readContract({address:n,abi:iw,functionName:"allowance",args:[o,t]})}async needsApproval(e,t,r={}){let{isWrappedNative:o}=await this.resolveAsset(e);if(o&&r.asErc20!==!0)return!1;return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:o=1,timeout:n=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:o,timeout:n});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class oS extends tt{async submit(e){return await this.makePublicRequest(ce.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class lC extends tt{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(ce.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:e.assetId,amount:e.amount,destination:e.destination,source:e.source??"spot"})})}async getWithdrawal(e){return this.makePublicRequest(ce.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return this.makeAuthenticatedRequest(ce.withdrawals.list({page:e?.page,pageSize:e?.pageSize}))}}class iS extends tt{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let r=this.walletClient.account;if(!r)throw new Ft("No account available in wallet client","account");let o=W_(),n={publicKey:K_(o),privateKey:J_(o)},i=await this.createChallenge(r.address,e,n.publicKey),a=await this.signChallenge(i.message);return await this.verifySignature(r.address,a,i.nonce,e,n,t)}async signChallenge(e){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let t=this.walletClient.account;if(!t)throw new Ft("No account available in wallet client","account");return await this.walletClient.signMessage({account:t,message:e})}async createChallenge(e,t,r){let o=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:o.nonce,message:o.message,expiresAt:o.expiresAt}}async verifySignature(e,t,r,o,n,i){let a=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:o,chainId:this.chain.id,sessionPublicKey:n.publicKey,...i?{referralCode:i}:{}})});return{sessionPublicKey:n.publicKey,sessionPrivateKey:n.privateKey,expiresAt:a.expiresAt,user:{id:a.user.id,address:a.user.address,username:a.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 J0e=750;function UZ(e,t){try{new URL(e)}catch(r){throw new Ft(`${t} must be a valid URL, got: ${e}`,t)}return e}class pC{auth;delegatedAgents;applications;fees;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;whitelist;profile;pulse;orderbook;trades;ws;walletClient;publicClient;authState;network;chain;propagateSession(e){this.auth.setSessionKeypair(e),this.delegatedAgents.setSessionKeypair(e),this.applications.setSessionKeypair(e),this.fees.setSessionKeypair(e),this.pitpass.setSessionKeypair(e),this.vault.setSessionKeypair(e),this.withdrawals.setSessionKeypair(e),this.trading.setSessionKeypair(e),this.market.setSessionKeypair(e),this.marginAccounts.setSessionKeypair(e),this.positions.setSessionKeypair(e),this.portfolio.setSessionKeypair(e),this.subAccounts.setSessionKeypair(e),this.faucet.setSessionKeypair(e),this.sweeper.setSessionKeypair(e),this.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}setServerKey(e){this.auth.setServerKey(e),this.delegatedAgents.setServerKey(e),this.applications.setServerKey(e),this.fees.setServerKey(e),this.pitpass.setServerKey(e),this.vault.setServerKey(e),this.withdrawals.setServerKey(e),this.trading.setServerKey(e),this.market.setServerKey(e),this.marginAccounts.setServerKey(e),this.positions.setServerKey(e),this.portfolio.setServerKey(e),this.subAccounts.setServerKey(e),this.faucet.setServerKey(e),this.sweeper.setServerKey(e),this.whitelist.setServerKey(e),this.pulse.setServerKey(e),this.profile.setServerKey(e),this.orderbook.setServerKey(e),this.trades.setServerKey(e)}sessionFromAuthState(e){return{publicKey:e.sessionPublicKey,privateKey:e.sessionPrivateKey}}constructor(e){let t=["mainnet","development","staging","local"];if(!e.network||!t.includes(e.network))throw new Ft(`network must be one of: ${t.join(", ")}. Got: ${e.network}`,"network");if(this.network=e.network,!e.seiRpcUrl)throw new Ft("seiRpcUrl is required","seiRpcUrl");try{new URL(e.seiRpcUrl)}catch(a){throw new Ft(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?UZ(e.wsUrl,"wsUrl"):GR(this.network),o=this.network==="mainnet"?LO:jO;if(this.chain=o,e.pollingInterval!==void 0&&(!Number.isFinite(e.pollingInterval)||e.pollingInterval<=0))throw new Ft(`pollingInterval must be a positive number of milliseconds, got: ${e.pollingInterval}`,"pollingInterval");let n=UO(e.seiRpcUrl);this.publicClient=MO({chain:o,transport:n,pollingInterval:e.pollingInterval??J0e});let i=e.apiUrl?UZ(e.apiUrl,"apiUrl"):HR(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==o.id)throw new Ft(`Wallet client chain mismatch. Expected ${o.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}this.applications=new N1(i),this.market=new V1(i),this.marginAccounts=new G1(i),this.positions=new Y1(i),this.portfolio=new J1(i),this.subAccounts=new X1(i),this.faucet=new M1(i),this.sweeper=new eS(i),this.whitelist=new oS(i),this.pulse=new Q1(i),this.auth=new iS(this.walletClient,this.chain,i),this.delegatedAgents=new HO(i),this.fees=new H1(i),this.pitpass=new W1(i),this.profile=new oC(i),this.vault=new nS(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i),this.withdrawals=new lC(i),this.trading=new rS(i),this.orderbook=new Z1(i),this.trades=new iC(i),this.ws=BR(r,e.ws),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new cr("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:dC.StatusCodes.UNAUTHORIZED});let t=W_(),r={publicKey:K_(t),privateKey:J_(t)},o=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:o.expiresAt,user:{id:o.ownerUserId,address:o.agentAddress}},this.propagateSession(this.sessionFromAuthState(this.authState)),this.authState}getAuthState(){return this.authState}setAuthState(e){this.authState=e,this.propagateSession(this.sessionFromAuthState(e))}async logout(){if(this.authState)try{await this.auth.revokeSession()}catch(e){console.warn("Failed to revoke session on logout:",e)}this.authState=void 0,this.propagateSession(void 0),this.ws.disconnect()}async refreshAuth(){if(!this.authState)throw new cr("No active session to refresh",{endpoint:"auth/refresh",statusCode:dC.StatusCodes.UNAUTHORIZED});try{let e=await this.auth.refreshSession();return this.authState={...this.authState,expiresAt:e.expiresAt},this.authState}catch(e){throw this.authState=void 0,this.propagateSession(void 0),e}}isAuthenticated(){return!!this.authState}isConnected(){return!!this.walletClient&&!!this.publicClient}setWalletClient(e){if(e.chain?.id!==this.chain.id)throw new Ft(`Wallet client chain mismatch. Expected ${this.chain.id}, got ${e.chain?.id}`,"walletClient");this.walletClient=e,this.auth.setWalletClient(e),this.vault.setWalletClient(e)}getAccountAddress(){if(!this.walletClient)throw new hg("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new hg("No account available","account")}getNetwork(){return this.network}getChainId(){return this.chain.id}async waitForTransaction(e,t,r){return this.publicClient.waitForTransactionReceipt({hash:e,confirmations:t,timeout:r})}}function fC(e){return new pC(e)}function wt(e){if(typeof e==="string")return{address:e,type:"json-rpc"};return e}var aS=256,sS;function cS(e=11){if(!sS||aS+e>512){sS="",aS=0;for(let t=0;t<256;t++)sS+=(256+Math.random()*256|0).toString(16).substring(1)}return sS.substring(aS,aS+++e)}function LZ(e){let{batch:t,chain:r,ccipRead:o,dataSuffix:n,key:i="base",name:a="Base Client",type:s="base"}=e,c=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),u=r?.blockTime??12000,d=Math.min(Math.max(Math.floor(u/2),500),4000),p=e.pollingInterval??d,m=e.cacheTime??p,h=e.account?wt(e.account):void 0,{config:y,request:x,value:S}=e.transport({account:h,chain:r,pollingInterval:p}),v={...y,...S},E={account:h,batch:t,cacheTime:m,ccipRead:o,chain:r,dataSuffix:n,key:i,name:a,pollingInterval:p,request:x,transport:v,type:s,uid:cS(),...c?{experimental_blockTag:c}:{}};function w(_){return(T)=>{let k=T(_);for(let z in E)delete k[z];let O={..._,...k};return Object.assign(O,{extend:w(O)})}}return Object.assign(E,{extend:w(E)})}var jZ={gwei:9,wei:18},FZ={ether:-9,wei:9};function uS(e,t){let r=e.toString(),o=r.startsWith("-");if(o)r=r.slice(1);r=r.padStart(t,"0");let[n,i]=[r.slice(0,r.length-t),r.slice(r.length-t)];return i=i.replace(/(0+)$/,""),`${o?"-":""}${n||"0"}${i?`.${i}`:""}`}function Tn(e,t="wei"){return uS(e,FZ[t])}var mC="2.53.1";var hC={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${mC}`};class q extends Error{constructor(e,t={}){let r=(()=>{if(t.cause instanceof q)return t.cause.details;if(t.cause?.message)return t.cause.message;return t.details})(),o=(()=>{if(t.cause instanceof q)return t.cause.docsPath||t.docsPath;return t.docsPath})(),n=hC.getDocsUrl?.({...t,docsPath:o}),i=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...hC.version?[`Version: ${hC.version}`]:[]].join(`
146
+ - `)}`);this.name="ValidationError",this.issues=e.issues}getErrors(){let e={};for(let t of this.issues){let r=t.path.join(".");e[r||"root"]=t.message}return e}}function _e(e,t){let r=e.safeParse(t);if(!r.success)throw new GV(r.error);return r.data}var Yp=f.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),my=f.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),j1=f.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),hy=f.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),VV=f.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),KO=f.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Qp=f.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),gt=f.string().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),Ae=f.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Ju=f.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),ZV=f.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),gy=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),I0e=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),D1=f.object({triggerPrice:gt,orderType:Qp,limitPrice:gt.optional(),quantity:gt.optional(),closePosition:f.boolean().optional(),timeInForce:KO.optional(),slippageToleranceBps:gy.optional(),expiresAt:Ju.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),U1=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,JO=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),WV=f.object({tradingPairId:Ae,side:Yp,quantity:gt,price:gt,options:f.object({tradingMode:my.optional(),useMasterBalance:f.boolean().optional(),expirationDate:Ju.optional(),timeInForce:VV.optional(),marginAccountId:Ae.optional(),marginMode:j1.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:gt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:hy.optional(),leverage:gt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional(),takeProfit:D1.optional(),stopLoss:D1.optional()}).optional()}).refine((e)=>JO(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!U1(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!U1(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),KV=f.object({tradingPairId:Ae,side:Yp,quantity:gt,options:f.object({tradingMode:my.optional(),slippageTolerance:ZV,marginAccountId:Ae.optional(),marginMode:j1.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:gt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:hy.optional(),leverage:gt.optional(),reduceOnly:f.boolean().optional(),takeProfit:D1.optional(),stopLoss:D1.optional()}).optional()}).refine((e)=>JO(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!U1(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!U1(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),JV=f.object({orderId:Ae,remainingQuantityTarget:gt.optional()}),YV=f.object({orderId:Ae,newOrder:f.object({price:gt.optional(),quantity:gt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()})}),QV=f.object({status:f.union([f.enum(B1),f.array(f.enum(B1)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Ae.optional(),tradingMode:my.optional(),marginAccountId:Ae.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),t2t=f.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),r2t=f.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),P0e=f.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),n2t=f.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),YO=f.object({conditionalOrderId:Ae}),XV=f.object({marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),state:P0e.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),k0e=f.enum(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),A0e=f.union([f.number().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),f.string().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),eZ=f.object({tradingPairId:Ae,side:Yp,quantity:gt,options:f.object({durationSeconds:A0e.optional(),startTime:Ju.optional(),endTime:Ju.optional(),limitPrice:gt.optional(),slippageToleranceBps:I0e.optional(),randomize:f.boolean().optional(),reduceOnly:f.boolean().optional(),tradingMode:my.optional(),marginAccountId:Ae.optional(),riskBucketId:Ae.optional(),marginMode:j1.optional(),leverage:gt.optional(),strategyKey:f.string().min(1).max(128).optional(),useMasterBalance:f.boolean().optional(),clientTwapId:f.string().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}),QO=f.object({twapOrderId:Ae}),tZ=f.object({state:k0e.optional(),tradingPairId:Ae.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),R0e=f.object({tradingPairId:Ae,orderType:Qp,side:Yp,price:gt.optional(),quantity:gt,tradingMode:my.optional(),slippageTolerance:ZV,useMasterBalance:f.boolean().optional(),expirationDate:Ju.optional(),timeInForce:VV.optional(),marginAccountId:Ae.optional(),marginMode:j1.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:gt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:hy.optional(),leverage:gt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>JO(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),L1=100,rZ=f.object({orders:f.array(R0e).min(1,"At least one order is required").max(L1,`At most ${L1} orders per batch request`)}),$0e=f.object({orderId:Ae,price:gt.optional(),quantity:gt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),nZ=f.object({orders:f.array($0e).min(1,"At least one order is required").max(L1,`At most ${L1} orders per batch request`)});var XO=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),oZ=XO.extend({state:f.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:Ae.optional()}),iZ=f.object({marginAccountId:Ae,tradingPairId:Ae.optional()}),aZ=f.object({tradingPairId:Ae.optional()}).optional(),sZ=f.object({asset:f.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),O0e=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:gt,tradingPairId:Ae.optional(),strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:f.enum(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),F1=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:gt}),C0e=f.object({tradingPairId:Ae,strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional()}),z0e=f.array(Ae).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),cZ=C0e.extend({marginMode:f.literal("ISOLATED").optional(),selectedTradingPairIds:f.never().optional()}),uZ=f.object({marginMode:f.literal("CROSS"),selectedTradingPairIds:z0e,strategyKey:f.never().optional()}),N0e=uZ.extend({tradingPairId:f.never().optional()}),eC=f.object({marginAccountId:Ae,request:O0e}),lZ=f.object({request:F1}),dZ=f.object({request:f.union([F1.merge(cZ).strict(),F1.merge(N0e).strict()])}),pZ=f.object({request:F1}),fZ=XO.extend({marginAccountId:Ae,movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}),mZ=XO.extend({movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),tC=f.object({tradingPairId:Ae,side:Yp,positionSide:hy.optional(),orderType:Qp,price:gt.optional(),quantity:gt,leverage:gt.optional(),reduceOnly:f.boolean().optional()}),rC=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:f.ZodIssueCode.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:f.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},hZ=tC.strict().superRefine(rC),M0e=tC.merge(cZ).strict().superRefine(rC),B0e=tC.merge(uZ).strict().superRefine(rC).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),D0e=f.union([M0e,B0e]),gZ=f.object({marginAccountId:Ae,request:hZ}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),yZ=f.object({request:hZ}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),bZ=f.object({request:D0e}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var xZ=f.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"'}),U0e=31536000000,L0e=946684800000,q1=f.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(L0e,{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((e)=>e<=Date.now()+U0e,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),l2t=f.object({tradingPairId:Ae,interval:xZ,startTime:q1,endTime:q1}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),d2t=f.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")'}),j0e=f.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),vZ=f.object({tradingPairId:Ae,interval:xZ,startTime:q1.optional(),endTime:q1.optional(),limit:j0e,priceType:f.enum(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var p2t=f.object({tradingPairId:Ae}),f2t=f.object({query:f.string().min(1,"Search query cannot be empty").optional(),pageSize:f.number().int().min(1).max(100).optional(),page:f.number().int().min(1).optional()}),Li=f.object({tradingPairId:Ae});var wZ=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),F0e=f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),q0e=f.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),yy=f.object({positionId:Ae}),SZ=wZ.extend({marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),status:F0e.optional()}),TZ=yy,EZ=yy.extend({request:f.object({closeType:q0e,limitPrice:gt.optional(),slippageToleranceBps:gy.optional(),quantity:gt.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),IZ=f.object({tradingPairId:Ae.optional(),slippageToleranceBps:gy.optional()}),PZ=yy,_Z=f.object({triggerPrice:gt,orderType:Qp,limitPrice:gt.optional(),quantity:gt.optional(),closePosition:f.boolean().optional(),timeInForce:KO.optional(),slippageToleranceBps:gy.optional(),expiresAt:Ju.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),kZ=yy.extend({request:f.object({takeProfit:_Z.optional(),stopLoss:_Z.optional(),oco:f.boolean().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),AZ=wZ.extend({positionId:Ae.optional(),marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),reductionOnly:f.boolean().optional()}),H0e=f.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),RZ=yy.extend({params:f.object({interval:H0e,startTime:f.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:f.number().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var G0e=f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),V0e=f.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),$Z=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.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:G0e.optional(),transactionType:V0e.optional(),assetId:Ae.optional()}),OZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:Ae.optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),CZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.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:Ae.optional(),positionId:Ae.optional(),marginAccountId:Ae.optional()});var S2t=f.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),nC=f.union([f.string().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),f.bigint().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),zZ=f.object({assetId:Ae,amount:nC,autoWait:f.boolean().optional()}),NZ=f.object({assetId:Ae,amount:nC,autoWait:f.boolean().optional(),target:f.enum(["spot","margin"]).optional(),options:f.object({asErc20:f.boolean().optional()}).optional()}),MZ=f.object({assetId:Ae,amount:nC,destination:f.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:f.boolean().optional(),source:f.enum(["spot","margin"]).optional()}),T2t=f.object({assetId:Ae});class H1 extends tt{async simulateFees(e){let t=_e(GO,e),r=new URLSearchParams;if(r.append("tradingPairId",t.tradingPairId),r.append("side",t.side),r.append("price",t.price),r.append("quantity",t.quantity),t.orderType!==void 0)r.append("orderType",t.orderType);if(t.slippageToleranceBps!==void 0)r.append("slippageToleranceBps",String(t.slippageToleranceBps));let o=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(o,{method:"GET"})}async getMyFeeTier(e){let t=_e(VO,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let o=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(o,{method:"GET"})}}class G1 extends tt{async listMarginAccounts(e){if(e)_e(oZ,e);return await this.makeAuthenticatedRequest(ce.marginAccounts.list(e?{page:e.page,pageSize:e.pageSize,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return _e(iZ,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ce.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return _e(aZ,e),await this.makeAuthenticatedRequest(ce.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return _e(sZ,e),await this.makeAuthenticatedRequest(ce.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return _e(eC,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return _e(lZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return _e(dZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds})})}async transferCollateralFromMarginAccount(e,t){return _e(eC,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferOut(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey,marginMode:t.marginMode})})}async transferCollateralFromParentMarginAccount(e){return _e(pZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return _e(fZ,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ce.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return _e(mZ,e),await this.makeAuthenticatedRequest(ce.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return _e(gZ,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ce.marginAccounts.simulateOrderRisk(e),{method:"POST",body:JSON.stringify({tradingPairId:t.tradingPairId,side:t.side,positionSide:t.positionSide,orderType:t.orderType,price:t.price,quantity:t.quantity,leverage:t.leverage,reduceOnly:t.reduceOnly})})}async simulateParentMarginOrderRisk(e){return _e(yZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.simulateParentMarginOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}async simulateRiskBucketOrderRisk(e){return _e(bZ,{request:e}),await this.makeAuthenticatedRequest(ce.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}}class V1 extends tt{async getPaginatedTradingPairs(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.marketType)t.append("marketType",e.marketType);if(e?.baseToken)t.append("baseToken",e.baseToken);if(e?.quoteToken)t.append("quoteToken",e.quoteToken);if(e?.isActive!==void 0)t.append("isActive",e.isActive.toString());if(e?.category)t.append("category",e.category);let r=t.toString(),o=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(o)}async getTradingPair(e){return _e(Li,{tradingPairId:e}),(await this.makePublicRequest(ce.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((o)=>o.symbol===e)}async getCandlesticks(e,t,r){_e(vZ,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit,priceType:r?.priceType});let o=new URLSearchParams;if(r?.startTime!==void 0)o.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)o.append("endTime",r.endTime.toString());if(r?.limit!==void 0)o.append("limit",r.limit.toString());if(r?.priceType!==void 0)o.append("priceType",r.priceType);let n=o.toString(),i=n?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${n}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getPerpMarketSummary(e))}async getMarkPrice(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getMarkPrice(e))}async getIndexPrice(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getIndexPrice(e))}async getFundingState(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getFundingState(e))}async listFundingHistory(e,t){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return await this.makePublicRequest(ce.market.listAllFundingHistory(e))}async getOpenInterest(e){return _e(Li,{tradingPairId:e}),await this.makePublicRequest(ce.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(ce.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(ce.market.getMarketStats())}}class Z1 extends tt{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:o,magnitude:n,denomination:i}=t,a=new URLSearchParams;if(a.set("levels",String(r)),o)a.set("tradingMode",o);if(n!==void 0)a.set("magnitude",String(n));if(i)a.set("denomination",i.toLowerCase());let s=await this.makePublicRequest(`/api/v1/orderbook/${encodeURIComponent(e)}?${a.toString()}`);return{tradingPairId:s.tradingPairId,tradingMode:s.tradingMode,bids:s.data.bids.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),asks:s.data.asks.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),bestBid:s.data.bestBid,bestAsk:s.data.bestAsk,bidVolume:s.data.bidVolume,askVolume:s.data.askVolume,baseDecimals:s.baseDecimals,quoteDecimals:s.quoteDecimals,timestamp:s.timestamp,sequence:s.sequenceNumber}}}class W1 extends tt{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me",{method:"GET"})}async setTraderCode(e){let t=_e(ZO,{code:e});return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/pitpass/codes/available?${t}`,{method:"GET"});return{available:r.available,reason:r.reason?r.reason:void 0}}async getTraderCodeInfo(e){let t=encodeURIComponent(e.trim());return await this.makePublicRequest(`/api/v1/pitpass/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/balance",{method:"GET"})}async transferRewards(e){let t=_e(WO,e);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}}var by="/api/v1/accounts/me/portfolio";function K1(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class J1 extends tt{async getSummary(e){return await this.makeAuthenticatedRequest(K1(`${by}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(K1(`${by}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(K1(`${by}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(K1(`${by}/assets`,e))}async getMargin(){return await this.makeAuthenticatedRequest(`${by}/margin`)}}class Y1 extends tt{async listPositions(e){if(e)_e(SZ,e);return await this.makeAuthenticatedRequest(ce.positions.list(e))}async getPosition(e){return _e(TZ,{positionId:e}),await this.makeAuthenticatedRequest(ce.positions.get(e))}async closePosition(e,t){return _e(EZ,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ce.positions.close(e),{method:"POST",body:JSON.stringify({closeType:t.closeType,limitPrice:t.limitPrice,slippageToleranceBps:t.slippageToleranceBps,quantity:t.quantity})})}async batchCloseAllPositions(e){if(e)_e(IZ,e);return await this.makeAuthenticatedRequest(ce.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return _e(PZ,{positionId:e}),await this.makeAuthenticatedRequest(ce.positions.risk(e))}async attachPositionTpSl(e,t){return _e(kZ,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ce.positions.attachTpSl(e),{method:"POST",body:JSON.stringify({takeProfit:t.takeProfit?{triggerPrice:t.takeProfit.triggerPrice,orderType:t.takeProfit.orderType,limitPrice:t.takeProfit.limitPrice,quantity:t.takeProfit.quantity,closePosition:t.takeProfit.closePosition,timeInForce:t.takeProfit.timeInForce,slippageToleranceBps:t.takeProfit.slippageToleranceBps,expiresAt:t.takeProfit.expiresAt}:void 0,stopLoss:t.stopLoss?{triggerPrice:t.stopLoss.triggerPrice,orderType:t.stopLoss.orderType,limitPrice:t.stopLoss.limitPrice,quantity:t.stopLoss.quantity,closePosition:t.stopLoss.closePosition,timeInForce:t.stopLoss.timeInForce,slippageToleranceBps:t.stopLoss.slippageToleranceBps,expiresAt:t.stopLoss.expiresAt}:void 0,oco:t.oco})})}async listPositionHistory(e){if(e)_e(AZ,e);return await this.makeAuthenticatedRequest(ce.positions.history(e))}async getPositionPnlHistory(e,t){return _e(RZ,{positionId:e,params:t}),await this.makeAuthenticatedRequest(ce.positions.pnlHistory(e,t))}}class oC extends tt{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)_e($Z,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.entryType!==void 0)t.append("entryType",e.entryType);if(e?.transactionType!==void 0)t.append("transactionType",e.transactionType);if(e?.assetId!==void 0)t.append("assetId",e.assetId);let r=t.toString(),o=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(o)}async getUserBalances(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());let r=t.toString(),o=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(o)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new cr("assetId is required and cannot be empty",{endpoint:"/api/v1/accounts/balances/{assetId}"});let t=`/api/v1/accounts/balances/${e}`;return await this.makeAuthenticatedRequest(t)}async getPortfolioStats(e){let t=new URLSearchParams({period:e});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio?${t}`)}async getPortfolioChart(e,t){let r=new URLSearchParams({period:e,metric:t});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio/chart?${r}`)}async getUserTrades(e){if(e)_e(OZ,e);let t=e?.page!==void 0&&e?.pageToken===void 0,r=new URLSearchParams;if(t&&e?.page!==void 0)r.append("page",e.page.toString());if(e?.pageSize!==void 0)r.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)r.append("tradingPairId",e.tradingPairId);if(!t)r.append("pageToken",e?.pageToken??"");let o=r.toString(),n=o?`/api/v1/accounts/trades?${o}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(n)}async*iterateUserTrades(e){let t="";for(;;){let r=await this.getUserTrades({...e,pageToken:t});if(yield*r.trades,!r.nextPageToken)return;t=r.nextPageToken}}async listFundingPayments(e){if(e)_e(CZ,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);if(e?.positionId!==void 0)t.append("positionId",e.positionId);if(e?.marginAccountId!==void 0)t.append("marginAccountId",e.marginAccountId);let r=t.toString(),o=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(o)}}class Q1 extends tt{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class X1 extends tt{async list(){return await this.makeAuthenticatedRequest(ce.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(ce.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(ce.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(ce.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(ce.subAccounts.limit(e,t),{method:"DELETE"})}}class eS extends tt{async register(e){return await this.makePublicRequest(ce.sweeper.register(),{method:"POST",body:JSON.stringify(e)})}}function BZ(e){return{eventType:"trade",tradingPairId:e.tradingPairId,tradingMode:e.tradingMode.toUpperCase(),data:{tradeId:e.data.tradeId,price:e.data.price,quantity:e.data.quantity,makerSide:e.data.makerSide.toUpperCase(),executedAt:e.data.executedAt??""}}}class iC extends tt{async getTrades(e,t={}){let{page:r=1}=t,o=t.pageSize!=null&&t.pageSize>0?Math.min(t.pageSize,100):25,n=new URLSearchParams;if(r>1)n.set("page",String(r));return n.set("pageSize",String(o)),(await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}?${n.toString()}`)).trades.map(BZ)}async getTradeById(e){let t=await this.makePublicRequest(ce.trades.byId(e));return BZ(t)}}function tS(e){if(!e)return;return{triggerPrice:e.triggerPrice,orderType:e.orderType,limitPrice:e.limitPrice,timeInForce:e.timeInForce,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt,quantity:e.quantity,closePosition:e.closePosition}}class rS extends tt{async placeLimitOrder(e,t,r,o,n){_e(WV,{tradingPairId:e,side:t,quantity:r,price:o,options:n});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:o,quantity:r,tradingMode:n?.tradingMode||"SPOT",useMasterBalance:n?.useMasterBalance,expirationDate:n?.expirationDate,timeInForce:n?.timeInForce,marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,postOnly:n?.postOnly,clientOrderId:n?.clientOrderId,takeProfit:tS(n?.takeProfit),stopLoss:tS(n?.stopLoss)};return await this.makeAuthenticatedRequest(ce.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,o){_e(KV,{tradingPairId:e,side:t,quantity:r,options:o});let n={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:o?.slippageTolerance!==void 0?Math.round(o.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:o?.tradingMode||"SPOT",marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,takeProfit:tS(o?.takeProfit),stopLoss:tS(o?.stopLoss),clientOrderId:o?.clientOrderId};return await this.makeAuthenticatedRequest(ce.orders.create(),{method:"POST",body:JSON.stringify(n)})}async cancelOrder(e,t){_e(JV,{orderId:e,remainingQuantityTarget:t?.remainingQuantityTarget});let r={orderId:e,...t?.remainingQuantityTarget!==void 0&&{remainingQuantityTarget:t.remainingQuantityTarget}};return await this.makeAuthenticatedRequest(ce.orders.cancel(),{method:"POST",body:JSON.stringify(r)})}async cancelConditionalOrder(e){return _e(YO,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ce.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return _e(YO,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ce.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)_e(XV,e);let{page:t=1,pageSize:r=20,marginAccountId:o,tradingPairId:n,state:i}=e||{};return await this.makeAuthenticatedRequest(ce.orders.listConditional({page:t,pageSize:Math.min(Math.max(r,1),100),marginAccountId:o,tradingPairId:n,state:i}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(ce.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?ce.orders.batchCancelAllByPair(e):ce.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){_e(YV,{orderId:e,newOrder:t});let r={useMasterBalance:t.useMasterBalance??!1};if(t.price!==void 0)r.price=t.price;if(t.quantity!==void 0)r.quantity=t.quantity;if(t.postOnly!==void 0)r.postOnly=t.postOnly;if(t.clientOrderId!==void 0)r.clientOrderId=t.clientOrderId;return await this.makeAuthenticatedRequest(ce.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){_e(rZ,{orders:e});let t={orders:e.map((r)=>({tradingPairId:r.tradingPairId,orderType:r.orderType,side:r.side,price:r.price,quantity:r.quantity,tradingMode:r.tradingMode||"SPOT",slippageToleranceBps:r.slippageTolerance!==void 0?Math.round(r.slippageTolerance*1e4):void 0,useMasterBalance:r.useMasterBalance,expirationDate:r.expirationDate,timeInForce:r.timeInForce,marginAccountId:r.marginAccountId,marginMode:r.marginMode,riskBucketId:r.riskBucketId,riskBucketCollateral:r.riskBucketCollateral,strategyKey:r.strategyKey,positionSide:r.positionSide,leverage:r.leverage,reduceOnly:r.reduceOnly,postOnly:r.postOnly,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ce.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){_e(nZ,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ce.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)_e(QV,e);let{page:t,pageSize:r=10,status:o,tradingPairId:n,tradingMode:i,marginAccountId:a,pageToken:s}=e||{},c=r>0?r:10,u=t!==void 0&&s===void 0,d=Math.min(c,u?100:1000),p=new URLSearchParams;if(u){let y=t>0?t:1;p.append("page",y.toString())}p.append("pageSize",d.toString());let m=typeof o==="string"?o:o?.join(",");if(m)p.append("status",m);if(n)p.append("tradingPairId",n);if(i)p.append("tradingMode",i);if(a)p.append("marginAccountId",a);if(!u)p.append("pageToken",s??"");let h=`/api/v1/orders?${p.toString()}`;return await this.makeAuthenticatedRequest(h,{method:"GET"})}async*iterateOrders(e){let t="";for(;;){let r=await this.getPaginatedOrders({...e,pageToken:t});if(yield*r.orders,!r.nextPageToken)return;t=r.nextPageToken}}async getOrder(e){return{order:await this.makeAuthenticatedRequest(ce.orders.get(e),{method:"GET"}),status:"SUCCESS"}}async createTwapOrder(e,t,r,o){_e(eZ,{tradingPairId:e,side:t,quantity:r,options:o});let n={tradingPairId:e,side:t,quantity:r,durationSeconds:o.durationSeconds!==void 0?Number(o.durationSeconds):void 0,startTime:o.startTime,endTime:o.endTime,limitPrice:o.limitPrice,slippageToleranceBps:o.slippageToleranceBps,randomize:o.randomize,reduceOnly:o.reduceOnly,tradingMode:o.tradingMode||"SPOT",marginAccountId:o.marginAccountId,riskBucketId:o.riskBucketId,marginMode:o.marginMode,leverage:o.leverage,strategyKey:o.strategyKey,useMasterBalance:o.useMasterBalance,clientTwapId:o.clientTwapId};return await this.makeAuthenticatedRequest(ce.orders.createTwap(),{method:"POST",body:JSON.stringify(n)})}async cancelTwapOrder(e){return _e(QO,{twapOrderId:e}),await this.makeAuthenticatedRequest(ce.orders.cancelTwap(e),{method:"POST"})}async getTwapOrder(e){return _e(QO,{twapOrderId:e}),await this.makeAuthenticatedRequest(ce.orders.getTwap(e),{method:"GET"})}async listTwapOrders(e){if(e)_e(tZ,e);let{page:t=1,pageSize:r=20,state:o,tradingPairId:n}=e||{};return await this.makeAuthenticatedRequest(ce.orders.listTwap({page:t,pageSize:Math.min(Math.max(r,1),100),state:o,tradingPairId:n}),{method:"GET"})}}var aC=[{inputs:[{internalType:"address",name:"rollup_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Refunded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"RefundedNative",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Swept",type:"event"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"contract IRollup",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"nonpayable",type:"function"}];var sC=[{inputs:[{internalType:"address",name:"rollup_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"sweeper",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"string",name:"applicationId",type:"string"}],name:"SweeperDeployed",type:"event"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"deploy",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"implementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"contract IRollup",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"sweeperFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];var cC=[{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 LCt=new Uint8Array(32);var uC={vault:cC,sweeper:aC,sweeperFactory:sC};var Z0e=5000,W0e=300000,K0e=(e)=>new Promise((t)=>setTimeout(t,e));function DZ(e,t){return t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}class nS extends tt{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,o,n,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=o,this.profileAPI=n}setWalletClient(e){this.walletClient=e}async getVaultAddress(){return(await this.applicationsAPI.getApplicationConfig()).vaultContractAddress}async getClientId(){return(await this.applicationsAPI.getApplicationConfig()).clientId}async resolveAsset(e){let t,r;try{let o=await this.profileAPI.getUserBalanceByAssetId(e);t=o.token,r=o.wrappedNative===!0}catch(o){if(o instanceof cr){if(o.statusCode===404)throw new Ta(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:o});throw new Ta(`Failed to resolve asset ID '${e}': ${o.retryable?"Network error occurred":"API request failed"}`,{revertReason:o.retryable?"NETWORK_ERROR":"API_ERROR",cause:o})}throw new Ta(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:o instanceof Error?o:void 0})}return{tokenAddress:t,isWrappedNative:r}}async approve(e,t,r=!0){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");_e(zZ,{assetId:e,amount:t,autoWait:r});let o=await this.getVaultAddress(),{tokenAddress:n}=await this.resolveAsset(e),i=this.walletClient.account;if(!i)throw new Ft("No account available in wallet client","account");let a=i.getNonce?await i.getNonce():0n,s=await this.walletClient.writeContract({address:n,abi:iw,functionName:"approve",args:[o,t],chain:this.chain,account:i}),c={nonce:a,hash:s,status:"pending"};return await this.waitForTransaction(c,r)}async deposit(e,t,r=!0,o="spot",n={}){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");_e(NZ,{assetId:e,amount:t,autoWait:r,target:o,options:n});let i=await this.getVaultAddress(),a=await this.getClientId(),s=DZ(a,o),{tokenAddress:c,isWrappedNative:u}=await this.resolveAsset(e),d=u&&n.asErc20!==!0;if(!d){if(await this.needsApproval(e,t,n))throw new Ta(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${c}).`,{revertReason:"APPROVAL_REQUIRED"})}let p=this.walletClient.account;if(!p)throw new Ft("No account available in wallet client","account");let m;if(d)m=await this.walletClient.writeContract({address:i,abi:uC.vault,functionName:"depositNative",args:[p.address,s],account:p,chain:this.chain,value:t});else m=await this.walletClient.writeContract({address:i,abi:uC.vault,functionName:"depositERC20",args:[p.address,s,c,t],account:p,chain:this.chain});let h=p.getNonce?await p.getNonce():0n,y={hash:m,status:"pending",nonce:h};return await this.waitForTransaction(y,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??Z0e,o=t?.timeoutMs??W0e,n=Date.now()+o;for(;;){try{let{vaultAddress:i,calldata:a}=await this.makePublicRequest(`/api/v1/withdrawals/${e}`);if(a&&a!=="0x")return{vaultAddress:i,calldata:a}}catch(i){if(!(i instanceof cr&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>n)return null;await K0e(r)}}async withdraw(e,t,r=!0,o,n){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let i=this.walletClient.account;if(!i)throw new Ft("No account available in wallet client","account");let a=i.address.toLowerCase(),s=typeof o==="string"?o:"spot",c=typeof o==="string"?n:o;_e(MZ,{assetId:e,amount:t,destination:a,autoWait:r,source:s});let{withdrawalIndex:u}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:a,source:s})});if(!r)return{withdrawalIndex:u,status:"awaiting_proof"};let d=await this.pollWithdrawalCalldata(u,c);if(!d)return{withdrawalIndex:u,status:"awaiting_proof"};let{vaultAddress:p,calldata:m}=d,h;try{h=await this.walletClient.sendTransaction({to:p,data:m,account:i,chain:this.chain})}catch(v){throw new Ta(`Failed to submit executeWithdrawal for withdrawal ${u}: ${v instanceof Error?v.message:"unknown error"}`,{cause:v instanceof Error?v:void 0})}let y=i.getNonce?await i.getNonce():0n,x={hash:h,status:"pending",nonce:y};return{...await this.waitForTransaction(x,r),withdrawalIndex:u}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let o=this.walletClient.account;if(!o)throw new Ft("No account available in wallet client","account");let n=await this.pollWithdrawalCalldata(e,r);if(!n)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:a}=n,s;try{s=await this.walletClient.sendTransaction({to:i,data:a,account:o,chain:this.chain})}catch(p){throw new Ta(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${p instanceof Error?p.message:"unknown error"}`,{cause:p instanceof Error?p:void 0})}let c=o.getNonce?await o.getNonce():0n,u={hash:s,status:"pending",nonce:c};return{...await this.waitForTransaction(u,t),withdrawalIndex:e}}async getBalance(e){throw new cr("getBalance() is deprecated and no longer supported. Please use profileAPI.getUserBalances() or profileAPI.getUserBalanceByAssetId() instead for balance data.",{statusCode:410})}async getAllowance(e){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let t=await this.getVaultAddress(),o=(await this.walletClient.getAddresses())[0];if(!o)throw new Ft("No account found in wallet client.","walletClient");let{tokenAddress:n}=await this.resolveAsset(e);return await this.publicClient.readContract({address:n,abi:iw,functionName:"allowance",args:[o,t]})}async needsApproval(e,t,r={}){let{isWrappedNative:o}=await this.resolveAsset(e);if(o&&r.asErc20!==!0)return!1;return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:o=1,timeout:n=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:o,timeout:n});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class oS extends tt{async submit(e){return await this.makePublicRequest(ce.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class lC extends tt{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(ce.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:e.assetId,amount:e.amount,destination:e.destination,source:e.source??"spot"})})}async getWithdrawal(e){return this.makePublicRequest(ce.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return this.makeAuthenticatedRequest(ce.withdrawals.list({page:e?.page,pageSize:e?.pageSize}))}}class iS extends tt{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let r=this.walletClient.account;if(!r)throw new Ft("No account available in wallet client","account");let o=W_(),n={publicKey:K_(o),privateKey:J_(o)},i=await this.createChallenge(r.address,e,n.publicKey),a=await this.signChallenge(i.message);return await this.verifySignature(r.address,a,i.nonce,e,n,t)}async signChallenge(e){if(!this.walletClient)throw new Ft("Wallet client not set. Connect a wallet first.","walletClient");let t=this.walletClient.account;if(!t)throw new Ft("No account available in wallet client","account");return await this.walletClient.signMessage({account:t,message:e})}async createChallenge(e,t,r){let o=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:o.nonce,message:o.message,expiresAt:o.expiresAt}}async verifySignature(e,t,r,o,n,i){let a=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:o,chainId:this.chain.id,sessionPublicKey:n.publicKey,...i?{referralCode:i}:{}})});return{sessionPublicKey:n.publicKey,sessionPrivateKey:n.privateKey,expiresAt:a.expiresAt,user:{id:a.user.id,address:a.user.address,username:a.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 J0e=750;function UZ(e,t){try{new URL(e)}catch(r){throw new Ft(`${t} must be a valid URL, got: ${e}`,t)}return e}class pC{auth;delegatedAgents;applications;fees;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;whitelist;profile;pulse;orderbook;trades;ws;walletClient;publicClient;authState;network;chain;propagateSession(e){this.auth.setSessionKeypair(e),this.delegatedAgents.setSessionKeypair(e),this.applications.setSessionKeypair(e),this.fees.setSessionKeypair(e),this.pitpass.setSessionKeypair(e),this.vault.setSessionKeypair(e),this.withdrawals.setSessionKeypair(e),this.trading.setSessionKeypair(e),this.market.setSessionKeypair(e),this.marginAccounts.setSessionKeypair(e),this.positions.setSessionKeypair(e),this.portfolio.setSessionKeypair(e),this.subAccounts.setSessionKeypair(e),this.faucet.setSessionKeypair(e),this.sweeper.setSessionKeypair(e),this.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}setServerKey(e){this.auth.setServerKey(e),this.delegatedAgents.setServerKey(e),this.applications.setServerKey(e),this.fees.setServerKey(e),this.pitpass.setServerKey(e),this.vault.setServerKey(e),this.withdrawals.setServerKey(e),this.trading.setServerKey(e),this.market.setServerKey(e),this.marginAccounts.setServerKey(e),this.positions.setServerKey(e),this.portfolio.setServerKey(e),this.subAccounts.setServerKey(e),this.faucet.setServerKey(e),this.sweeper.setServerKey(e),this.whitelist.setServerKey(e),this.pulse.setServerKey(e),this.profile.setServerKey(e),this.orderbook.setServerKey(e),this.trades.setServerKey(e)}sessionFromAuthState(e){return{publicKey:e.sessionPublicKey,privateKey:e.sessionPrivateKey}}constructor(e){let t=["mainnet","development","staging","local"];if(!e.network||!t.includes(e.network))throw new Ft(`network must be one of: ${t.join(", ")}. Got: ${e.network}`,"network");if(this.network=e.network,!e.seiRpcUrl)throw new Ft("seiRpcUrl is required","seiRpcUrl");try{new URL(e.seiRpcUrl)}catch(a){throw new Ft(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?UZ(e.wsUrl,"wsUrl"):GR(this.network),o=this.network==="mainnet"?LO:jO;if(this.chain=o,e.pollingInterval!==void 0&&(!Number.isFinite(e.pollingInterval)||e.pollingInterval<=0))throw new Ft(`pollingInterval must be a positive number of milliseconds, got: ${e.pollingInterval}`,"pollingInterval");let n=UO(e.seiRpcUrl);this.publicClient=MO({chain:o,transport:n,pollingInterval:e.pollingInterval??J0e});let i=e.apiUrl?UZ(e.apiUrl,"apiUrl"):HR(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==o.id)throw new Ft(`Wallet client chain mismatch. Expected ${o.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}this.applications=new N1(i),this.market=new V1(i),this.marginAccounts=new G1(i),this.positions=new Y1(i),this.portfolio=new J1(i),this.subAccounts=new X1(i),this.faucet=new M1(i),this.sweeper=new eS(i),this.whitelist=new oS(i),this.pulse=new Q1(i),this.auth=new iS(this.walletClient,this.chain,i),this.delegatedAgents=new HO(i),this.fees=new H1(i),this.pitpass=new W1(i),this.profile=new oC(i),this.vault=new nS(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i),this.withdrawals=new lC(i),this.trading=new rS(i),this.orderbook=new Z1(i),this.trades=new iC(i),this.ws=BR(r,e.ws),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new cr("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:dC.StatusCodes.UNAUTHORIZED});let t=W_(),r={publicKey:K_(t),privateKey:J_(t)},o=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:o.expiresAt,user:{id:o.ownerUserId,address:o.agentAddress}},this.propagateSession(this.sessionFromAuthState(this.authState)),this.authState}getAuthState(){return this.authState}setAuthState(e){this.authState=e,this.propagateSession(this.sessionFromAuthState(e))}async logout(){if(this.authState)try{await this.auth.revokeSession()}catch(e){console.warn("Failed to revoke session on logout:",e)}this.authState=void 0,this.propagateSession(void 0),this.ws.disconnect()}async refreshAuth(){if(!this.authState)throw new cr("No active session to refresh",{endpoint:"auth/refresh",statusCode:dC.StatusCodes.UNAUTHORIZED});try{let e=await this.auth.refreshSession();return this.authState={...this.authState,expiresAt:e.expiresAt},this.authState}catch(e){throw this.authState=void 0,this.propagateSession(void 0),e}}isAuthenticated(){return!!this.authState}isConnected(){return!!this.walletClient&&!!this.publicClient}setWalletClient(e){if(e.chain?.id!==this.chain.id)throw new Ft(`Wallet client chain mismatch. Expected ${this.chain.id}, got ${e.chain?.id}`,"walletClient");this.walletClient=e,this.auth.setWalletClient(e),this.vault.setWalletClient(e)}getAccountAddress(){if(!this.walletClient)throw new hg("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new hg("No account available","account")}getNetwork(){return this.network}getChainId(){return this.chain.id}async waitForTransaction(e,t,r){return this.publicClient.waitForTransactionReceipt({hash:e,confirmations:t,timeout:r})}}function fC(e){return new pC(e)}function wt(e){if(typeof e==="string")return{address:e,type:"json-rpc"};return e}var aS=256,sS;function cS(e=11){if(!sS||aS+e>512){sS="",aS=0;for(let t=0;t<256;t++)sS+=(256+Math.random()*256|0).toString(16).substring(1)}return sS.substring(aS,aS+++e)}function LZ(e){let{batch:t,chain:r,ccipRead:o,dataSuffix:n,key:i="base",name:a="Base Client",type:s="base"}=e,c=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),u=r?.blockTime??12000,d=Math.min(Math.max(Math.floor(u/2),500),4000),p=e.pollingInterval??d,m=e.cacheTime??p,h=e.account?wt(e.account):void 0,{config:y,request:x,value:S}=e.transport({account:h,chain:r,pollingInterval:p}),v={...y,...S},E={account:h,batch:t,cacheTime:m,ccipRead:o,chain:r,dataSuffix:n,key:i,name:a,pollingInterval:p,request:x,transport:v,type:s,uid:cS(),...c?{experimental_blockTag:c}:{}};function w(_){return(T)=>{let k=T(_);for(let z in E)delete k[z];let O={..._,...k};return Object.assign(O,{extend:w(O)})}}return Object.assign(E,{extend:w(E)})}var jZ={gwei:9,wei:18},FZ={ether:-9,wei:9};function uS(e,t){let r=e.toString(),o=r.startsWith("-");if(o)r=r.slice(1);r=r.padStart(t,"0");let[n,i]=[r.slice(0,r.length-t),r.slice(r.length-t)];return i=i.replace(/(0+)$/,""),`${o?"-":""}${n||"0"}${i?`.${i}`:""}`}function Tn(e,t="wei"){return uS(e,FZ[t])}var mC="2.53.1";var hC={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${mC}`};class q extends Error{constructor(e,t={}){let r=(()=>{if(t.cause instanceof q)return t.cause.details;if(t.cause?.message)return t.cause.message;return t.details})(),o=(()=>{if(t.cause instanceof q)return t.cause.docsPath||t.docsPath;return t.docsPath})(),n=hC.getDocsUrl?.({...t,docsPath:o}),i=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...hC.version?[`Version: ${hC.version}`]:[]].join(`
147
147
  `);super(i,t.cause?{cause:t.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=r,this.docsPath=o,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=mC}walk(e){return qZ(this,e)}}function qZ(e,t){if(t?.(e))return e;if(e&&typeof e==="object"&&"cause"in e&&e.cause!==void 0)return qZ(e.cause,t);return t?null:e}class xy extends q{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Yu extends q{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class gC extends q{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Tn(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class dc extends q{constructor({cause:e,message:t}={}){let r=t?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${r?`with reason: ${r}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(dc,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(dc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});class ii extends q{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${Tn(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(ii,"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 vy extends q{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${Tn(t)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(vy,"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 _y extends q{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(_y,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class wy extends q{constructor({cause:e,nonce:t}={}){super([`Nonce provided for the transaction ${t?`(${t}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
148
148
  `),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(wy,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class Sy extends q{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(Sy,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class Ty extends q{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
149
149
  `),{cause:e,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(Ty,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class Ey extends q{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(Ey,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Iy extends q{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(Iy,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class Py extends q{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(Py,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class qa extends q{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${Tn(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${Tn(r)} gwei`:""}).`].join(`
150
150
  `),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(qa,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class Qu extends q{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function lS(e,t="wei"){return uS(e,jZ[t])}function Xp(e){let t=Object.entries(e).map(([o,n])=>{if(n===void 0||n===!1)return null;return[o,n]}).filter(Boolean),r=t.reduce((o,[n])=>Math.max(o,n.length),0);return t.map(([o,n])=>` ${`${o}:`.padEnd(r+1)} ${n}`).join(`
151
151
  `)}class yC extends q{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class bC extends q{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Xp(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class xC extends q{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class vC extends q{constructor(e,{account:t,docsPath:r,chain:o,data:n,gas:i,gasPrice:a,maxFeePerGas:s,maxPriorityFeePerGas:c,nonce:u,to:d,value:p}){let m=Xp({chain:o&&`${o?.name} (id: ${o?.id})`,from:t?.address,to:d,value:typeof p<"u"&&`${lS(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:n,gas:i,gasPrice:typeof a<"u"&&`${Tn(a)} gwei`,maxFeePerGas:typeof s<"u"&&`${Tn(s)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${Tn(c)} gwei`,nonce:u});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",m].filter(Boolean),name:"TransactionExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class ky extends q{constructor({blockHash:e,blockNumber:t,blockTag:r,hash:o,index:n}){let i="Transaction";if(r&&n!==void 0)i=`Transaction at block time "${r}" at index "${n}"`;if(e&&n!==void 0)i=`Transaction at block hash "${e}" at index "${n}"`;if(t&&n!==void 0)i=`Transaction at block number "${t}" at index "${n}"`;if(o)i=`Transaction with hash "${o}"`;super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}}class Ay extends q{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class ef extends q{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"});Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class _C extends q{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}var rr=(e,t,r)=>JSON.stringify(e,(o,n)=>{let i=typeof n==="bigint"?n.toString():n;return typeof t==="function"?t(o,i):i},r);var HZ=(e)=>e;function ai(e){if(e?.reason)return e.reason;if(typeof DOMException==="function")return new DOMException("This operation was aborted","AbortError");let t=Error("This operation was aborted");return t.name="AbortError",t}function Ha(e){return typeof e==="object"&&e!==null&&"name"in e&&e.name==="AbortError"}var dS=(e)=>{try{let t=new URL(e);if(!t.username&&!t.password)return e;return t.username="",t.password="",t.toString()}catch{return e}};class pc extends q{constructor({body:e,cause:t,details:r,headers:o,status:n,url:i}){super("HTTP request failed.",{cause:t,details:r,metaMessages:[n&&`Status: ${n}`,`URL: ${dS(i)}`,e&&`Request body: ${rr(e)}`].filter(Boolean),name:"HttpRequestError"});Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=o,this.status=n,this.url=i}}class Xu extends q{constructor({body:e,error:t,url:r}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${dS(r)}`,`Request body: ${rr(e)}`],name:"RpcRequestError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t.code,this.data=t.data,this.url=r}}class pS extends q{constructor({body:e,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${dS(t)}`,`Request body: ${rr(e)}`],name:"TimeoutError"});Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}}var Y0e=-1;class En extends q{constructor(e,{code:t,docsPath:r,metaMessages:o,name:n,shortMessage:i}){super(i,{cause:e,docsPath:r,metaMessages:o||e?.metaMessages,name:n||"RpcError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=n||e.name,this.code=e instanceof Xu?e.code:t??Y0e}}class In extends En{constructor(e,t){super(e,t);Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}}class tf extends En{constructor(e){super(e,{code:tf.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(tf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class rf extends En{constructor(e){super(e,{code:rf.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(rf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class nf extends En{constructor(e,{method:t}={}){super(e,{code:nf.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}}Object.defineProperty(nf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class of extends En{constructor(e){super(e,{code:of.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
152
152
  `)})}}Object.defineProperty(of,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Ga extends En{constructor(e){super(e,{code:Ga.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Ga,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class fc extends En{constructor(e){super(e,{code:fc.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
153
- `)})}}Object.defineProperty(fc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32000});class af extends En{constructor(e){super(e,{code:af.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(af,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class sf extends En{constructor(e){super(e,{code:sf.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(sf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class cf extends En{constructor(e){super(e,{code:cf.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(cf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class mc extends En{constructor(e,{method:t}={}){super(e,{code:mc.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(mc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class el extends En{constructor(e){super(e,{code:el.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(el,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class uf extends En{constructor(e){super(e,{code:uf.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(uf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class tl extends In{constructor(e){super(e,{code:tl.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(tl,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class lf extends In{constructor(e){super(e,{code:lf.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(lf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class df extends In{constructor(e,{method:t}={}){super(e,{code:df.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(df,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class pf extends In{constructor(e){super(e,{code:pf.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(pf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class ff extends In{constructor(e){super(e,{code:ff.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(ff,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class mf extends In{constructor(e){super(e,{code:mf.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(mf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class hc extends In{constructor(e){super(e,{code:hc.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(hc,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class hf extends In{constructor(e){super(e,{code:hf.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(hf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class gf extends In{constructor(e){super(e,{code:gf.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(gf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class yf extends In{constructor(e){super(e,{code:yf.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(yf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class bf extends In{constructor(e){super(e,{code:bf.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(bf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class xf extends In{constructor(e){super(e,{code:xf.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(xf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class gc extends In{constructor(e){super(e,{code:gc.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(gc,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class vf extends In{constructor(e){super(e,{code:vf.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}}Object.defineProperty(vf,"code",{enumerable:!0,configurable:!0,writable:!0,value:7000});class wC extends En{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}function fS(e,t){let r=(e.details||"").toLowerCase(),o=e instanceof q?e.walk((n)=>n?.code===dc.code):e;if(o instanceof q)return new dc({cause:e,message:o.details});if(dc.nodeMessage.test(r))return new dc({cause:e,message:e.details});if(ii.nodeMessage.test(r))return new ii({cause:e,maxFeePerGas:t?.maxFeePerGas});if(vy.nodeMessage.test(r))return new vy({cause:e,maxFeePerGas:t?.maxFeePerGas});if(_y.nodeMessage.test(r))return new _y({cause:e,nonce:t?.nonce});if(wy.nodeMessage.test(r))return new wy({cause:e,nonce:t?.nonce});if(Sy.nodeMessage.test(r))return new Sy({cause:e,nonce:t?.nonce});if(Ty.nodeMessage.test(r))return new Ty({cause:e});if(Ey.nodeMessage.test(r))return new Ey({cause:e,gas:t?.gas});if(Iy.nodeMessage.test(r))return new Iy({cause:e,gas:t?.gas});if(Py.nodeMessage.test(r))return new Py({cause:e});if(qa.nodeMessage.test(r))return new qa({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Qu({cause:e})}function yc(e,{docsPath:t,...r}){let o=(()=>{let n=fS(e,r);if(n instanceof Qu)return e;return n})();return new vC(o,{docsPath:t,...r})}function bc(e,{format:t}){if(!t)return{};let r={};function o(i){let a=Object.keys(i);for(let s of a){if(s in e)r[s]=e[s];if(i[s]&&typeof i[s]==="object"&&!Array.isArray(i[s]))o(i[s])}}let n=t(e||{});return o(n),r}class rl extends q{constructor({max:e,min:t,signed:r,size:o,value:n}){super(`Number "${n}" is not in safe ${o?`${o*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class SC extends q{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class TC extends q{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Wr(e,{strict:t=!0}={}){if(!e)return!1;if(typeof e!=="string")return!1;return t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function St(e){if(Wr(e,{strict:!1}))return Math.ceil((e.length-2)/2);return e.length}function To(e,{dir:t="left"}={}){let r=typeof e==="string"?e.replace("0x",""):e,o=0;for(let n=0;n<r.length-1;n++)if(r[t==="left"?n:r.length-n-1].toString()==="0")o++;else break;if(r=t==="left"?r.slice(o):r.slice(0,r.length-o),typeof e==="string"){if(r.length===1&&t==="right")r=`${r}0`;return`0x${r.length%2===1?`0${r}`:r}`}return r}class mS extends q{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${r}).`,{name:"SliceOffsetOutOfBoundsError"})}}class hS extends q{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}class gS extends q{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} is expected to be ${t} ${r} long, but is ${e} ${r} long.`,{name:"InvalidBytesLengthError"})}}function xc(e,{dir:t,size:r=32}={}){if(typeof e==="string")return Va(e,{dir:t,size:r});return Q0e(e,{dir:t,size:r})}function Va(e,{dir:t,size:r=32}={}){if(r===null)return e;let o=e.replace("0x","");if(o.length>r*2)throw new hS({size:Math.ceil(o.length/2),targetSize:r,type:"hex"});return`0x${o[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function Q0e(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new hS({size:e.length,targetSize:r,type:"bytes"});let o=new Uint8Array(r);for(let n=0;n<r;n++){let i=t==="right";o[i?n:r-n-1]=e[i?n:e.length-n-1]}return o}var X0e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Kr(e,t={}){if(typeof e==="number"||typeof e==="bigint")return ae(e,t);if(typeof e==="string")return vc(e,t);if(typeof e==="boolean")return EC(e,t);return Ht(e,t)}function EC(e,t={}){let r=`0x${Number(e)}`;if(typeof t.size==="number")return Qn(r,{size:t.size}),xc(r,{size:t.size});return r}function Ht(e,t={}){let r="";for(let n=0;n<e.length;n++)r+=X0e[e[n]];let o=`0x${r}`;if(typeof t.size==="number")return Qn(o,{size:t.size}),xc(o,{dir:"right",size:t.size});return o}function ae(e,t={}){let{signed:r,size:o}=t,n=BigInt(e),i;if(o)if(r)i=(1n<<BigInt(o)*8n-1n)-1n;else i=2n**(BigInt(o)*8n)-1n;else if(typeof e==="number")i=BigInt(Number.MAX_SAFE_INTEGER);let a=typeof i==="bigint"&&r?-i-1n:0;if(i&&n>i||n<a){let c=typeof e==="bigint"?"n":"";throw new rl({max:i?`${i}${c}`:void 0,min:`${a}${c}`,signed:r,size:o,value:`${e}${c}`})}let s=`0x${(r&&n<0?(1n<<BigInt(o*8))+BigInt(n):n).toString(16)}`;if(o)return xc(s,{size:o});return s}var exe=new TextEncoder;function vc(e,t={}){let r=exe.encode(e);return Ht(r,t)}var txe=new TextEncoder;function _f(e,t={}){if(typeof e==="number"||typeof e==="bigint")return nxe(e,t);if(typeof e==="boolean")return rxe(e,t);if(Wr(e))return vr(e,t);return IC(e,t)}function rxe(e,t={}){let r=new Uint8Array(1);if(r[0]=Number(e),typeof t.size==="number")return Qn(r,{size:t.size}),xc(r,{size:t.size});return r}var Za={zero:48,nine:57,A:65,F:70,a:97,f:102};function GZ(e){if(e>=Za.zero&&e<=Za.nine)return e-Za.zero;if(e>=Za.A&&e<=Za.F)return e-(Za.A-10);if(e>=Za.a&&e<=Za.f)return e-(Za.a-10);return}function vr(e,t={}){let r=e;if(t.size)Qn(r,{size:t.size}),r=xc(r,{dir:"right",size:t.size});let o=r.slice(2);if(o.length%2)o=`0${o}`;let n=o.length/2,i=new Uint8Array(n);for(let a=0,s=0;a<n;a++){let c=GZ(o.charCodeAt(s++)),u=GZ(o.charCodeAt(s++));if(c===void 0||u===void 0)throw new q(`Invalid byte sequence ("${o[s-2]}${o[s-1]}" in "${o}").`);i[a]=c*16+u}return i}function nxe(e,t){let r=ae(e,t);return vr(r)}function IC(e,t={}){let r=txe.encode(e);if(typeof t.size==="number")return Qn(r,{size:t.size}),xc(r,{dir:"right",size:t.size});return r}function Qn(e,{size:t}){if(St(e)>t)throw new TC({givenSize:St(e),maxSize:t})}function Rr(e,t={}){let{signed:r}=t;if(t.size)Qn(e,{size:t.size});let o=BigInt(e);if(!r)return o;let n=(e.length-2)/2,i=(1n<<BigInt(n)*8n-1n)-1n;if(o<=i)return o;return o-BigInt(`0x${"f".padStart(n*2,"f")}`)-1n}function $r(e,t={}){let r=Rr(e,t),o=Number(r);if(!Number.isSafeInteger(o))throw new rl({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${r}n`});return o}var PC={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function wf(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?$r(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?$r(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?PC[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=oxe(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function oxe(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var ixe={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function ji(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=axe(e.authorizationList);if(typeof e.accessList<"u")r.accessList=e.accessList;if(typeof e.blobVersionedHashes<"u")r.blobVersionedHashes=e.blobVersionedHashes;if(typeof e.blobs<"u")if(typeof e.blobs[0]!=="string")r.blobs=e.blobs.map((o)=>Ht(o));else r.blobs=e.blobs;if(typeof e.data<"u")r.data=e.data;if(e.account)r.from=e.account.address;if(typeof e.from<"u")r.from=e.from;if(typeof e.gas<"u")r.gas=ae(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=ae(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=ae(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=ae(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=ae(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=ae(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=ixe[e.type];if(typeof e.value<"u")r.value=ae(e.value);return r}function axe(e){return e.map((t)=>({address:t.address,r:t.r?ae(BigInt(t.r)):t.r,s:t.s?ae(BigInt(t.s)):t.s,chainId:ae(t.chainId),nonce:ae(t.nonce),...typeof t.yParity<"u"?{yParity:ae(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:ae(t.v)}:{}}))}function Le(e,t,r){let o=e[t.name];if(typeof o==="function")return o;let n=e[r];if(typeof n==="function")return n;return(i)=>t(e,i)}var BNt=2n**(8n-1n)-1n,DNt=2n**(16n-1n)-1n,UNt=2n**(24n-1n)-1n,LNt=2n**(32n-1n)-1n,jNt=2n**(40n-1n)-1n,FNt=2n**(48n-1n)-1n,qNt=2n**(56n-1n)-1n,HNt=2n**(64n-1n)-1n,GNt=2n**(72n-1n)-1n,VNt=2n**(80n-1n)-1n,ZNt=2n**(88n-1n)-1n,WNt=2n**(96n-1n)-1n,KNt=2n**(104n-1n)-1n,JNt=2n**(112n-1n)-1n,YNt=2n**(120n-1n)-1n,QNt=2n**(128n-1n)-1n,XNt=2n**(136n-1n)-1n,eMt=2n**(144n-1n)-1n,tMt=2n**(152n-1n)-1n,rMt=2n**(160n-1n)-1n,nMt=2n**(168n-1n)-1n,oMt=2n**(176n-1n)-1n,iMt=2n**(184n-1n)-1n,aMt=2n**(192n-1n)-1n,sMt=2n**(200n-1n)-1n,cMt=2n**(208n-1n)-1n,uMt=2n**(216n-1n)-1n,lMt=2n**(224n-1n)-1n,dMt=2n**(232n-1n)-1n,pMt=2n**(240n-1n)-1n,fMt=2n**(248n-1n)-1n,mMt=2n**(256n-1n)-1n,hMt=-(2n**(8n-1n)),gMt=-(2n**(16n-1n)),yMt=-(2n**(24n-1n)),bMt=-(2n**(32n-1n)),xMt=-(2n**(40n-1n)),vMt=-(2n**(48n-1n)),_Mt=-(2n**(56n-1n)),wMt=-(2n**(64n-1n)),SMt=-(2n**(72n-1n)),TMt=-(2n**(80n-1n)),EMt=-(2n**(88n-1n)),IMt=-(2n**(96n-1n)),PMt=-(2n**(104n-1n)),kMt=-(2n**(112n-1n)),AMt=-(2n**(120n-1n)),RMt=-(2n**(128n-1n)),$Mt=-(2n**(136n-1n)),OMt=-(2n**(144n-1n)),CMt=-(2n**(152n-1n)),zMt=-(2n**(160n-1n)),NMt=-(2n**(168n-1n)),MMt=-(2n**(176n-1n)),BMt=-(2n**(184n-1n)),DMt=-(2n**(192n-1n)),UMt=-(2n**(200n-1n)),LMt=-(2n**(208n-1n)),jMt=-(2n**(216n-1n)),FMt=-(2n**(224n-1n)),qMt=-(2n**(232n-1n)),HMt=-(2n**(240n-1n)),GMt=-(2n**(248n-1n)),VMt=-(2n**(256n-1n)),ZMt=2n**8n-1n,WMt=2n**16n-1n,KMt=2n**24n-1n,JMt=2n**32n-1n,YMt=2n**40n-1n,QMt=2n**48n-1n,XMt=2n**56n-1n,e4t=2n**64n-1n,t4t=2n**72n-1n,r4t=2n**80n-1n,n4t=2n**88n-1n,o4t=2n**96n-1n,i4t=2n**104n-1n,a4t=2n**112n-1n,s4t=2n**120n-1n,c4t=2n**128n-1n,u4t=2n**136n-1n,l4t=2n**144n-1n,d4t=2n**152n-1n,p4t=2n**160n-1n,f4t=2n**168n-1n,m4t=2n**176n-1n,h4t=2n**184n-1n,g4t=2n**192n-1n,y4t=2n**200n-1n,b4t=2n**208n-1n,x4t=2n**216n-1n,v4t=2n**224n-1n,_4t=2n**232n-1n,w4t=2n**240n-1n,S4t=2n**248n-1n,Sf=2n**256n-1n;class Wt extends q{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class Xn extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e))super.delete(e),super.set(e,t);return t}set(e,t){if(super.has(e))super.delete(e);if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=super.keys().next().value;if(r!==void 0)super.delete(r)}return this}}mw();function hr(e,t){let r=t||"hex",o=Kd(Wr(e,{strict:!1})?_f(e):e);if(r==="bytes")return o;return Kr(o)}var kC=new Xn(8192);function Wa(e,t){if(kC.has(`${e}.${t}`))return kC.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),o=hr(IC(r),"bytes"),n=(t?r.substring(`${t}0x`.length):r).split("");for(let a=0;a<40;a+=2){if(o[a>>1]>>4>=8&&n[a])n[a]=n[a].toUpperCase();if((o[a>>1]&15)>=8&&n[a+1])n[a+1]=n[a+1].toUpperCase()}let i=`0x${n.join("")}`;return kC.set(`${e}.${t}`,i),i}function VZ(e,t){if(!Nt(e,{strict:!1}))throw new Wt({address:e});return Wa(e,t)}var sxe=/^0x[a-fA-F0-9]{40}$/,AC=new Xn(8192);function Nt(e,t){let{strict:r=!0}=t??{},o=`${e}.${r}`;if(AC.has(o))return AC.get(o);let n=(()=>{if(!sxe.test(e))return!1;if(e.toLowerCase()===e)return!0;if(r)return Wa(e)===e;return!0})();return AC.set(o,n),n}function Eo(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:o,to:n}=e,i=t?wt(t):void 0;if(i&&!Nt(i.address))throw new Wt({address:i.address});if(n&&!Nt(n))throw new Wt({address:n});if(r&&r>Sf)throw new ii({maxFeePerGas:r});if(o&&r&&o>r)throw new qa({maxFeePerGas:r,maxPriorityFeePerGas:o})}class Ry extends q{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}function ZZ(e,t){let r=(e.transactions??[]).map((o)=>{if(typeof o==="string")return o;return wf(o)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function si(e,{blockHash:t,blockNumber:r,blockTag:o=e.experimental_blockTag??"latest",includeTransactions:n}={}){let i=n??!1,a=r!==void 0?ae(r):void 0,s=null;if(t)s=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else s=await e.request({method:"eth_getBlockByNumber",params:[a||o,i]},{dedupe:Boolean(a)});if(!s)throw new Ry({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||ZZ)(s,"getBlock")}async function rn(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return $r(t)}async function yS(e,t){let{account:r=e.account,accessList:o,authorizationList:n,chain:i=e.chain,blobVersionedHashes:a,blobs:s,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:y,nonceManager:x,to:S,type:v,value:E,...w}=t,_=await(async()=>{if(!r)return y;if(!x)return y;if(typeof y<"u")return y;let z=wt(r),L=i?i.id:await Le(e,rn,"getChainId")({});return await x.consume({address:z.address,chainId:L,client:e})})();Eo(t);let T=i?.formatters?.transactionRequest?.format,O=(T||ji)({...bc(w,{format:T}),account:r?wt(r):void 0,accessList:o,authorizationList:n,blobs:s,blobVersionedHashes:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:_,to:S,type:v,value:E},"fillTransaction");try{let z=await e.request({method:"eth_fillTransaction",params:[O]}),P=(i?.formatters?.transaction?.format||wf)(z.tx);if(delete P.blockHash,delete P.blockNumber,delete P.r,delete P.s,delete P.transactionIndex,delete P.v,delete P.yParity,P.data=P.input,P.gas)P.gas=t.gas??P.gas;if(P.gasPrice)P.gasPrice=t.gasPrice??P.gasPrice;if(P.maxFeePerBlobGas)P.maxFeePerBlobGas=t.maxFeePerBlobGas??P.maxFeePerBlobGas;if(P.maxFeePerGas)P.maxFeePerGas=t.maxFeePerGas??P.maxFeePerGas;if(P.maxPriorityFeePerGas)P.maxPriorityFeePerGas=t.maxPriorityFeePerGas??P.maxPriorityFeePerGas;if(typeof P.nonce<"u")P.nonce=t.nonce??P.nonce;let F=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let H=await Le(e,si,"getBlock")({});return i.fees.baseFeeMultiplier({block:H,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(F<1)throw new xy;let ue=10**(F.toString().split(".")[1]?.length??0),W=(H)=>H*BigInt(Math.ceil(F*ue))/BigInt(ue);if(!P.feePayerSignature){if(P.maxFeePerGas&&!t.maxFeePerGas)P.maxFeePerGas=W(P.maxFeePerGas);if(P.gasPrice&&!t.gasPrice)P.gasPrice=W(P.gasPrice)}return{raw:z.raw,transaction:{from:O.from,...P},...z.capabilities?{capabilities:z.capabilities}:{}}}catch(z){throw yc(z,{...t,chain:e.chain})}}async function WZ(e,{chain:t}){let{id:r,name:o,nativeCurrency:n,rpcUrls:i,blockExplorers:a}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:ae(r),chainName:o,nativeCurrency:n,rpcUrls:i.default.http,blockExplorerUrls:a?Object.values(a).map(({url:s})=>s):void 0}]},{dedupe:!0,retryCount:0})}function Fi(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new RC(e.type);return`${e.name}(${bS(e.inputs,{includeName:t})})`}function bS(e,{includeName:t=!1}={}){if(!e)return"";return e.map((r)=>cxe(r,{includeName:t})).join(t?", ":",")}function cxe(e,{includeName:t}){if(e.type.startsWith("tuple"))return`(${bS(e.components,{includeName:t})})${e.type.slice(5)}`;return e.type+(t&&e.name?` ${e.name}`:"")}class $C extends q{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
153
+ `)})}}Object.defineProperty(fc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32000});class af extends En{constructor(e){super(e,{code:af.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(af,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class sf extends En{constructor(e){super(e,{code:sf.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(sf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class cf extends En{constructor(e){super(e,{code:cf.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(cf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class mc extends En{constructor(e,{method:t}={}){super(e,{code:mc.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(mc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class el extends En{constructor(e){super(e,{code:el.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(el,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class uf extends En{constructor(e){super(e,{code:uf.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(uf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class tl extends In{constructor(e){super(e,{code:tl.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(tl,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class lf extends In{constructor(e){super(e,{code:lf.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(lf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class df extends In{constructor(e,{method:t}={}){super(e,{code:df.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(df,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class pf extends In{constructor(e){super(e,{code:pf.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(pf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class ff extends In{constructor(e){super(e,{code:ff.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(ff,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class mf extends In{constructor(e){super(e,{code:mf.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(mf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class hc extends In{constructor(e){super(e,{code:hc.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(hc,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class hf extends In{constructor(e){super(e,{code:hf.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(hf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class gf extends In{constructor(e){super(e,{code:gf.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(gf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class yf extends In{constructor(e){super(e,{code:yf.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(yf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class bf extends In{constructor(e){super(e,{code:bf.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(bf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class xf extends In{constructor(e){super(e,{code:xf.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(xf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class gc extends In{constructor(e){super(e,{code:gc.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(gc,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class vf extends In{constructor(e){super(e,{code:vf.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}}Object.defineProperty(vf,"code",{enumerable:!0,configurable:!0,writable:!0,value:7000});class wC extends En{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}function fS(e,t){let r=(e.details||"").toLowerCase(),o=e instanceof q?e.walk((n)=>n?.code===dc.code):e;if(o instanceof q)return new dc({cause:e,message:o.details});if(dc.nodeMessage.test(r))return new dc({cause:e,message:e.details});if(ii.nodeMessage.test(r))return new ii({cause:e,maxFeePerGas:t?.maxFeePerGas});if(vy.nodeMessage.test(r))return new vy({cause:e,maxFeePerGas:t?.maxFeePerGas});if(_y.nodeMessage.test(r))return new _y({cause:e,nonce:t?.nonce});if(wy.nodeMessage.test(r))return new wy({cause:e,nonce:t?.nonce});if(Sy.nodeMessage.test(r))return new Sy({cause:e,nonce:t?.nonce});if(Ty.nodeMessage.test(r))return new Ty({cause:e});if(Ey.nodeMessage.test(r))return new Ey({cause:e,gas:t?.gas});if(Iy.nodeMessage.test(r))return new Iy({cause:e,gas:t?.gas});if(Py.nodeMessage.test(r))return new Py({cause:e});if(qa.nodeMessage.test(r))return new qa({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Qu({cause:e})}function yc(e,{docsPath:t,...r}){let o=(()=>{let n=fS(e,r);if(n instanceof Qu)return e;return n})();return new vC(o,{docsPath:t,...r})}function bc(e,{format:t}){if(!t)return{};let r={};function o(i){let a=Object.keys(i);for(let s of a){if(s in e)r[s]=e[s];if(i[s]&&typeof i[s]==="object"&&!Array.isArray(i[s]))o(i[s])}}let n=t(e||{});return o(n),r}class rl extends q{constructor({max:e,min:t,signed:r,size:o,value:n}){super(`Number "${n}" is not in safe ${o?`${o*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class SC extends q{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class TC extends q{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Wr(e,{strict:t=!0}={}){if(!e)return!1;if(typeof e!=="string")return!1;return t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function St(e){if(Wr(e,{strict:!1}))return Math.ceil((e.length-2)/2);return e.length}function To(e,{dir:t="left"}={}){let r=typeof e==="string"?e.replace("0x",""):e,o=0;for(let n=0;n<r.length-1;n++)if(r[t==="left"?n:r.length-n-1].toString()==="0")o++;else break;if(r=t==="left"?r.slice(o):r.slice(0,r.length-o),typeof e==="string"){if(r.length===1&&t==="right")r=`${r}0`;return`0x${r.length%2===1?`0${r}`:r}`}return r}class mS extends q{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${r}).`,{name:"SliceOffsetOutOfBoundsError"})}}class hS extends q{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}class gS extends q{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} is expected to be ${t} ${r} long, but is ${e} ${r} long.`,{name:"InvalidBytesLengthError"})}}function xc(e,{dir:t,size:r=32}={}){if(typeof e==="string")return Va(e,{dir:t,size:r});return Q0e(e,{dir:t,size:r})}function Va(e,{dir:t,size:r=32}={}){if(r===null)return e;let o=e.replace("0x","");if(o.length>r*2)throw new hS({size:Math.ceil(o.length/2),targetSize:r,type:"hex"});return`0x${o[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function Q0e(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new hS({size:e.length,targetSize:r,type:"bytes"});let o=new Uint8Array(r);for(let n=0;n<r;n++){let i=t==="right";o[i?n:r-n-1]=e[i?n:e.length-n-1]}return o}var X0e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Kr(e,t={}){if(typeof e==="number"||typeof e==="bigint")return ae(e,t);if(typeof e==="string")return vc(e,t);if(typeof e==="boolean")return EC(e,t);return Ht(e,t)}function EC(e,t={}){let r=`0x${Number(e)}`;if(typeof t.size==="number")return Qn(r,{size:t.size}),xc(r,{size:t.size});return r}function Ht(e,t={}){let r="";for(let n=0;n<e.length;n++)r+=X0e[e[n]];let o=`0x${r}`;if(typeof t.size==="number")return Qn(o,{size:t.size}),xc(o,{dir:"right",size:t.size});return o}function ae(e,t={}){let{signed:r,size:o}=t,n=BigInt(e),i;if(o)if(r)i=(1n<<BigInt(o)*8n-1n)-1n;else i=2n**(BigInt(o)*8n)-1n;else if(typeof e==="number")i=BigInt(Number.MAX_SAFE_INTEGER);let a=typeof i==="bigint"&&r?-i-1n:0;if(i&&n>i||n<a){let c=typeof e==="bigint"?"n":"";throw new rl({max:i?`${i}${c}`:void 0,min:`${a}${c}`,signed:r,size:o,value:`${e}${c}`})}let s=`0x${(r&&n<0?(1n<<BigInt(o*8))+BigInt(n):n).toString(16)}`;if(o)return xc(s,{size:o});return s}var exe=new TextEncoder;function vc(e,t={}){let r=exe.encode(e);return Ht(r,t)}var txe=new TextEncoder;function _f(e,t={}){if(typeof e==="number"||typeof e==="bigint")return nxe(e,t);if(typeof e==="boolean")return rxe(e,t);if(Wr(e))return vr(e,t);return IC(e,t)}function rxe(e,t={}){let r=new Uint8Array(1);if(r[0]=Number(e),typeof t.size==="number")return Qn(r,{size:t.size}),xc(r,{size:t.size});return r}var Za={zero:48,nine:57,A:65,F:70,a:97,f:102};function GZ(e){if(e>=Za.zero&&e<=Za.nine)return e-Za.zero;if(e>=Za.A&&e<=Za.F)return e-(Za.A-10);if(e>=Za.a&&e<=Za.f)return e-(Za.a-10);return}function vr(e,t={}){let r=e;if(t.size)Qn(r,{size:t.size}),r=xc(r,{dir:"right",size:t.size});let o=r.slice(2);if(o.length%2)o=`0${o}`;let n=o.length/2,i=new Uint8Array(n);for(let a=0,s=0;a<n;a++){let c=GZ(o.charCodeAt(s++)),u=GZ(o.charCodeAt(s++));if(c===void 0||u===void 0)throw new q(`Invalid byte sequence ("${o[s-2]}${o[s-1]}" in "${o}").`);i[a]=c*16+u}return i}function nxe(e,t){let r=ae(e,t);return vr(r)}function IC(e,t={}){let r=txe.encode(e);if(typeof t.size==="number")return Qn(r,{size:t.size}),xc(r,{dir:"right",size:t.size});return r}function Qn(e,{size:t}){if(St(e)>t)throw new TC({givenSize:St(e),maxSize:t})}function Rr(e,t={}){let{signed:r}=t;if(t.size)Qn(e,{size:t.size});let o=BigInt(e);if(!r)return o;let n=(e.length-2)/2,i=(1n<<BigInt(n)*8n-1n)-1n;if(o<=i)return o;return o-BigInt(`0x${"f".padStart(n*2,"f")}`)-1n}function $r(e,t={}){let r=Rr(e,t),o=Number(r);if(!Number.isSafeInteger(o))throw new rl({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${r}n`});return o}var PC={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function wf(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?$r(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?$r(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?PC[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=oxe(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function oxe(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var ixe={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function ji(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=axe(e.authorizationList);if(typeof e.accessList<"u")r.accessList=e.accessList;if(typeof e.blobVersionedHashes<"u")r.blobVersionedHashes=e.blobVersionedHashes;if(typeof e.blobs<"u")if(typeof e.blobs[0]!=="string")r.blobs=e.blobs.map((o)=>Ht(o));else r.blobs=e.blobs;if(typeof e.data<"u")r.data=e.data;if(e.account)r.from=e.account.address;if(typeof e.from<"u")r.from=e.from;if(typeof e.gas<"u")r.gas=ae(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=ae(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=ae(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=ae(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=ae(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=ae(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=ixe[e.type];if(typeof e.value<"u")r.value=ae(e.value);return r}function axe(e){return e.map((t)=>({address:t.address,r:t.r?ae(BigInt(t.r)):t.r,s:t.s?ae(BigInt(t.s)):t.s,chainId:ae(t.chainId),nonce:ae(t.nonce),...typeof t.yParity<"u"?{yParity:ae(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:ae(t.v)}:{}}))}function Le(e,t,r){let o=e[t.name];if(typeof o==="function")return o;let n=e[r];if(typeof n==="function")return n;return(i)=>t(e,i)}var DNt=2n**(8n-1n)-1n,UNt=2n**(16n-1n)-1n,LNt=2n**(24n-1n)-1n,jNt=2n**(32n-1n)-1n,FNt=2n**(40n-1n)-1n,qNt=2n**(48n-1n)-1n,HNt=2n**(56n-1n)-1n,GNt=2n**(64n-1n)-1n,VNt=2n**(72n-1n)-1n,ZNt=2n**(80n-1n)-1n,WNt=2n**(88n-1n)-1n,KNt=2n**(96n-1n)-1n,JNt=2n**(104n-1n)-1n,YNt=2n**(112n-1n)-1n,QNt=2n**(120n-1n)-1n,XNt=2n**(128n-1n)-1n,eMt=2n**(136n-1n)-1n,tMt=2n**(144n-1n)-1n,rMt=2n**(152n-1n)-1n,nMt=2n**(160n-1n)-1n,oMt=2n**(168n-1n)-1n,iMt=2n**(176n-1n)-1n,aMt=2n**(184n-1n)-1n,sMt=2n**(192n-1n)-1n,cMt=2n**(200n-1n)-1n,uMt=2n**(208n-1n)-1n,lMt=2n**(216n-1n)-1n,dMt=2n**(224n-1n)-1n,pMt=2n**(232n-1n)-1n,fMt=2n**(240n-1n)-1n,mMt=2n**(248n-1n)-1n,hMt=2n**(256n-1n)-1n,gMt=-(2n**(8n-1n)),yMt=-(2n**(16n-1n)),bMt=-(2n**(24n-1n)),xMt=-(2n**(32n-1n)),vMt=-(2n**(40n-1n)),_Mt=-(2n**(48n-1n)),wMt=-(2n**(56n-1n)),SMt=-(2n**(64n-1n)),TMt=-(2n**(72n-1n)),EMt=-(2n**(80n-1n)),IMt=-(2n**(88n-1n)),PMt=-(2n**(96n-1n)),kMt=-(2n**(104n-1n)),AMt=-(2n**(112n-1n)),RMt=-(2n**(120n-1n)),$Mt=-(2n**(128n-1n)),OMt=-(2n**(136n-1n)),CMt=-(2n**(144n-1n)),zMt=-(2n**(152n-1n)),NMt=-(2n**(160n-1n)),MMt=-(2n**(168n-1n)),BMt=-(2n**(176n-1n)),DMt=-(2n**(184n-1n)),UMt=-(2n**(192n-1n)),LMt=-(2n**(200n-1n)),jMt=-(2n**(208n-1n)),FMt=-(2n**(216n-1n)),qMt=-(2n**(224n-1n)),HMt=-(2n**(232n-1n)),GMt=-(2n**(240n-1n)),VMt=-(2n**(248n-1n)),ZMt=-(2n**(256n-1n)),WMt=2n**8n-1n,KMt=2n**16n-1n,JMt=2n**24n-1n,YMt=2n**32n-1n,QMt=2n**40n-1n,XMt=2n**48n-1n,e4t=2n**56n-1n,t4t=2n**64n-1n,r4t=2n**72n-1n,n4t=2n**80n-1n,o4t=2n**88n-1n,i4t=2n**96n-1n,a4t=2n**104n-1n,s4t=2n**112n-1n,c4t=2n**120n-1n,u4t=2n**128n-1n,l4t=2n**136n-1n,d4t=2n**144n-1n,p4t=2n**152n-1n,f4t=2n**160n-1n,m4t=2n**168n-1n,h4t=2n**176n-1n,g4t=2n**184n-1n,y4t=2n**192n-1n,b4t=2n**200n-1n,x4t=2n**208n-1n,v4t=2n**216n-1n,_4t=2n**224n-1n,w4t=2n**232n-1n,S4t=2n**240n-1n,T4t=2n**248n-1n,Sf=2n**256n-1n;class Wt extends q{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class Xn extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e))super.delete(e),super.set(e,t);return t}set(e,t){if(super.has(e))super.delete(e);if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=super.keys().next().value;if(r!==void 0)super.delete(r)}return this}}mw();function hr(e,t){let r=t||"hex",o=Kd(Wr(e,{strict:!1})?_f(e):e);if(r==="bytes")return o;return Kr(o)}var kC=new Xn(8192);function Wa(e,t){if(kC.has(`${e}.${t}`))return kC.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),o=hr(IC(r),"bytes"),n=(t?r.substring(`${t}0x`.length):r).split("");for(let a=0;a<40;a+=2){if(o[a>>1]>>4>=8&&n[a])n[a]=n[a].toUpperCase();if((o[a>>1]&15)>=8&&n[a+1])n[a+1]=n[a+1].toUpperCase()}let i=`0x${n.join("")}`;return kC.set(`${e}.${t}`,i),i}function VZ(e,t){if(!Nt(e,{strict:!1}))throw new Wt({address:e});return Wa(e,t)}var sxe=/^0x[a-fA-F0-9]{40}$/,AC=new Xn(8192);function Nt(e,t){let{strict:r=!0}=t??{},o=`${e}.${r}`;if(AC.has(o))return AC.get(o);let n=(()=>{if(!sxe.test(e))return!1;if(e.toLowerCase()===e)return!0;if(r)return Wa(e)===e;return!0})();return AC.set(o,n),n}function Eo(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:o,to:n}=e,i=t?wt(t):void 0;if(i&&!Nt(i.address))throw new Wt({address:i.address});if(n&&!Nt(n))throw new Wt({address:n});if(r&&r>Sf)throw new ii({maxFeePerGas:r});if(o&&r&&o>r)throw new qa({maxFeePerGas:r,maxPriorityFeePerGas:o})}class Ry extends q{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}function ZZ(e,t){let r=(e.transactions??[]).map((o)=>{if(typeof o==="string")return o;return wf(o)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function si(e,{blockHash:t,blockNumber:r,blockTag:o=e.experimental_blockTag??"latest",includeTransactions:n}={}){let i=n??!1,a=r!==void 0?ae(r):void 0,s=null;if(t)s=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else s=await e.request({method:"eth_getBlockByNumber",params:[a||o,i]},{dedupe:Boolean(a)});if(!s)throw new Ry({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||ZZ)(s,"getBlock")}async function rn(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return $r(t)}async function yS(e,t){let{account:r=e.account,accessList:o,authorizationList:n,chain:i=e.chain,blobVersionedHashes:a,blobs:s,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:y,nonceManager:x,to:S,type:v,value:E,...w}=t,_=await(async()=>{if(!r)return y;if(!x)return y;if(typeof y<"u")return y;let z=wt(r),L=i?i.id:await Le(e,rn,"getChainId")({});return await x.consume({address:z.address,chainId:L,client:e})})();Eo(t);let T=i?.formatters?.transactionRequest?.format,O=(T||ji)({...bc(w,{format:T}),account:r?wt(r):void 0,accessList:o,authorizationList:n,blobs:s,blobVersionedHashes:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:_,to:S,type:v,value:E},"fillTransaction");try{let z=await e.request({method:"eth_fillTransaction",params:[O]}),P=(i?.formatters?.transaction?.format||wf)(z.tx);if(delete P.blockHash,delete P.blockNumber,delete P.r,delete P.s,delete P.transactionIndex,delete P.v,delete P.yParity,P.data=P.input,P.gas)P.gas=t.gas??P.gas;if(P.gasPrice)P.gasPrice=t.gasPrice??P.gasPrice;if(P.maxFeePerBlobGas)P.maxFeePerBlobGas=t.maxFeePerBlobGas??P.maxFeePerBlobGas;if(P.maxFeePerGas)P.maxFeePerGas=t.maxFeePerGas??P.maxFeePerGas;if(P.maxPriorityFeePerGas)P.maxPriorityFeePerGas=t.maxPriorityFeePerGas??P.maxPriorityFeePerGas;if(typeof P.nonce<"u")P.nonce=t.nonce??P.nonce;let F=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let H=await Le(e,si,"getBlock")({});return i.fees.baseFeeMultiplier({block:H,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(F<1)throw new xy;let ue=10**(F.toString().split(".")[1]?.length??0),W=(H)=>H*BigInt(Math.ceil(F*ue))/BigInt(ue);if(!P.feePayerSignature){if(P.maxFeePerGas&&!t.maxFeePerGas)P.maxFeePerGas=W(P.maxFeePerGas);if(P.gasPrice&&!t.gasPrice)P.gasPrice=W(P.gasPrice)}return{raw:z.raw,transaction:{from:O.from,...P},...z.capabilities?{capabilities:z.capabilities}:{}}}catch(z){throw yc(z,{...t,chain:e.chain})}}async function WZ(e,{chain:t}){let{id:r,name:o,nativeCurrency:n,rpcUrls:i,blockExplorers:a}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:ae(r),chainName:o,nativeCurrency:n,rpcUrls:i.default.http,blockExplorerUrls:a?Object.values(a).map(({url:s})=>s):void 0}]},{dedupe:!0,retryCount:0})}function Fi(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new RC(e.type);return`${e.name}(${bS(e.inputs,{includeName:t})})`}function bS(e,{includeName:t=!1}={}){if(!e)return"";return e.map((r)=>cxe(r,{includeName:t})).join(t?", ":",")}function cxe(e,{includeName:t}){if(e.type.startsWith("tuple"))return`(${bS(e.components,{includeName:t})})${e.type.slice(5)}`;return e.type+(t&&e.name?` ${e.name}`:"")}class $C extends q{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
154
154
  `),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class xS extends q{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
155
155
  `),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class OC extends q{constructor({data:e,params:t,size:r}){super([`Data size of ${r} bytes is too small for given parameters.`].join(`
156
156
  `),{metaMessages:[`Params: (${bS(t,{includeName:!0})})`,`Data: ${e} (${r} bytes)`],name:"AbiDecodingDataSizeTooSmallError"});Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=t,this.size=r}}class nl extends q{constructor({cause:e}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:e})}}class CC extends q{constructor({expectedLength:e,givenLength:t,type:r}){super([`ABI encoding array length mismatch for type ${r}.`,`Expected length: ${e}`,`Given length: ${t}`].join(`
@@ -166,4 +166,4 @@ ${t}`}function Y_(e,t){return lu(Z_.sign(jd(t),e))}var mg=[0.0001,0.001,0.01,0.1
166
166
  `),{name:"ChainNotFoundError"})}}class If extends q{constructor({chainId:e}){super(typeof e==="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}function Pf({chain:e,currentChainId:t}){if(!e)throw new WC;if(t!==e.id)throw new ZC({chain:e,currentChainId:t})}async function PS(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function oW(e,t){let{block:r,chain:o=e.chain,request:n}=t||{};try{let i=o?.fees?.maxPriorityFeePerGas??o?.fees?.defaultPriorityFee;if(typeof i==="function"){let s=r||await Le(e,si,"getBlock")({}),c=await i({block:s,client:e,request:n});if(c===null)throw Error();return c}if(typeof i<"u")return i;let a=await e.request({method:"eth_maxPriorityFeePerGas"});return Rr(a)}catch{let[i,a]=await Promise.all([r?Promise.resolve(r):Le(e,si,"getBlock")({}),Le(e,PS,"getGasPrice")({})]);if(typeof i.baseFeePerGas!=="bigint")throw new Yu;let s=a-i.baseFeePerGas;if(s<0n)return 0n;return s}}async function KC(e,t){let{block:r,chain:o=e.chain,request:n,type:i="eip1559"}=t||{},a=await(async()=>{if(typeof o?.fees?.baseFeeMultiplier==="function")return o.fees.baseFeeMultiplier({block:r,client:e,request:n});return o?.fees?.baseFeeMultiplier??1.2})();if(a<1)throw new xy;let c=10**(a.toString().split(".")[1]?.length??0),u=(m)=>m*BigInt(Math.ceil(a*c))/BigInt(c),d=r?r:await Le(e,si,"getBlock")({});if(typeof o?.fees?.estimateFeesPerGas==="function"){let m=await o.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:n,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof d.baseFeePerGas!=="bigint")throw new Yu;let m=typeof n?.maxPriorityFeePerGas==="bigint"?n.maxPriorityFeePerGas:await oW(e,{block:d,chain:o,request:n}),h=u(d.baseFeePerGas);return{maxFeePerGas:n?.maxFeePerGas??h+m,maxPriorityFeePerGas:m}}return{gasPrice:n?.gasPrice??u(await Le(e,PS,"getGasPrice")({}))}}class JC extends q{constructor(e,{account:t,docsPath:r,chain:o,data:n,gas:i,gasPrice:a,maxFeePerGas:s,maxPriorityFeePerGas:c,nonce:u,to:d,value:p}){let m=Xp({from:t?.address,to:d,value:typeof p<"u"&&`${lS(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:n,gas:i,gasPrice:typeof a<"u"&&`${Tn(a)} gwei`,maxFeePerGas:typeof s<"u"&&`${Tn(s)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${Tn(c)} gwei`,nonce:u});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",m].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}function iW(e,{docsPath:t,...r}){let o=(()=>{let n=fS(e,r);if(n instanceof Qu)return e;return n})();return new JC(o,{docsPath:t,...r})}class YC extends q{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class QC extends q{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function aW(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:o})=>{if(r.length!==66)throw new gS({size:r.length,targetSize:66,type:"hex"});if(o.length!==66)throw new gS({size:o.length,targetSize:66,type:"hex"});return t[r]=o,t},{})}function _xe(e){let{balance:t,nonce:r,state:o,stateDiff:n,code:i}=e,a={};if(i!==void 0)a.code=i;if(t!==void 0)a.balance=ae(t);if(r!==void 0)a.nonce=ae(r);if(o!==void 0)a.state=aW(o);if(n!==void 0){if(a.state)throw new QC;a.stateDiff=aW(n)}return a}function sW(e){if(!e)return;let t={};for(let{address:r,...o}of e){if(!Nt(r,{strict:!1}))throw new Wt({address:r});if(t[r])throw new YC({address:r});t[r]=_xe(o)}return t}async function cW(e,t){let{account:r=e.account,prepare:o=!0}=t,n=r?wt(r):void 0,i=(()=>{if(Array.isArray(o))return o;if(n?.type!=="local")return["blobVersionedHashes"];return})();try{let a=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await Ef({authorization:t.authorizationList[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:s,authorizationList:c,blobs:u,blobVersionedHashes:d,blockNumber:p,blockTag:m,data:h,gas:y,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,value:_,stateOverride:T,...k}=o?await _c(e,{...t,parameters:i,to:a}):t;if(y&&t.gas!==y)return y;let z=(typeof p==="bigint"?ae(p):void 0)||m,L=sW(T);Eo(t);let P=e.chain?.formatters?.transactionRequest?.format,G=(P||ji)({...bc(k,{format:P}),account:n,accessList:s,authorizationList:c,blobs:u,blobVersionedHashes:d,data:h,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,to:a,value:_},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:L?[G,z??e.experimental_blockTag??"latest",L]:z?[G,z]:[G]}))}catch(a){throw iW(a,{...t,account:n,chain:e.chain})}}function uW(e){let{blockHash:t,blockNumber:r,blockTag:o,requireCanonical:n}=e;if(n!==void 0&&!t)throw new q("`requireCanonical` can only be provided when `blockHash` is set.");if(t)return n?{blockHash:t,requireCanonical:n}:{blockHash:t};if(typeof r==="bigint")return ae(r);return o??"latest"}async function kS(e,{address:t,blockHash:r,blockNumber:o,blockTag:n="latest",requireCanonical:i}){let a=uW({blockHash:r,blockNumber:o,blockTag:n,requireCanonical:i}),s=await e.request({method:"eth_getTransactionCount",params:[t,a]},{dedupe:typeof o==="bigint"||r!==void 0});return $r(s)}function kf(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),o=typeof e.blobs[0]==="string"?e.blobs.map((i)=>vr(i)):e.blobs,n=[];for(let i of o)n.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?n:n.map((i)=>Ht(i))}function Af(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),o=typeof e.blobs[0]==="string"?e.blobs.map((a)=>vr(a)):e.blobs,n=typeof e.commitments[0]==="string"?e.commitments.map((a)=>vr(a)):e.commitments,i=[];for(let a=0;a<o.length;a++){let s=o[a],c=n[a];i.push(Uint8Array.from(t.computeBlobKzgProof(s,c)))}return r==="bytes"?i:i.map((a)=>Ht(a))}function lW(e,t){let r=t||"hex",o=d1(Wr(e,{strict:!1})?_f(e):e);if(r==="bytes")return o;return Kr(o)}function dW(e){let{commitment:t,version:r=1}=e,o=e.to??(typeof t==="string"?"hex":"bytes"),n=lW(t,"bytes");return n.set([r],0),o==="bytes"?n:Ht(n)}function AS(e){let{commitments:t,version:r}=e,o=e.to??(typeof t[0]==="string"?"hex":"bytes"),n=[];for(let i of t)n.push(dW({commitment:i,to:o,version:r}));return n}var pW=32,fW=4096,mW=131072,XC=761855;var RS=1;class e5 extends q{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class Oy extends q{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class t5 extends q{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class r5 extends q{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${RS}`,`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}function hW(e){let t=e.to??(typeof e.data==="string"?"hex":"bytes"),r=typeof e.data==="string"?vr(e.data):e.data,o=St(r);if(!o)throw new Oy;if(o>XC)throw new e5({maxSize:XC,size:o});let n=[],i=!0,a=0;while(i){let s=Tf(new Uint8Array(mW)),c=0;while(c<fW){let u=r.slice(a,a+(pW-1));if(s.pushByte(0),s.pushBytes(u),u.length<31){s.pushByte(128),i=!1;break}c++,a+=31}n.push(s)}return t==="bytes"?n.map((s)=>s.bytes):n.map((s)=>Ht(s.bytes))}function $S(e){let{data:t,kzg:r,to:o}=e,n=e.blobs??hW({data:t,to:o}),i=e.commitments??kf({blobs:n,kzg:r,to:o}),a=e.proofs??Af({blobs:n,commitments:i,kzg:r,to:o}),s=[];for(let c=0;c<n.length;c++)s.push({blob:n[c],commitment:i[c],proof:a[c]});return s}function OS(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u"){if(typeof e.accessList<"u")return"eip2930";return"legacy"}throw new bC({transaction:e})}var Cy=["blobVersionedHashes","chainId","fees","gas","nonce","type"],gW=new Map,n5=new Xn(128);async function _c(e,t){let r=t;r.account??=e.account,r.parameters??=Cy;let{account:o,chain:n=e.chain,nonceManager:i,parameters:a}=r,s=(()=>{if(typeof n?.prepareTransactionRequest==="function")return{fn:n.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(n?.prepareTransactionRequest))return{fn:n.prepareTransactionRequest[0],runAt:n.prepareTransactionRequest[1].runAt};return})(),c;async function u(){if(c)return c;if(typeof r.chainId<"u")return r.chainId;if(n)return n.id;return c=await Le(e,rn,"getChainId")({}),c}let d=o?wt(o):o,p=r.nonce;if(a.includes("nonce")&&typeof p>"u"&&d&&i){let _=await u();p=await i.consume({address:d.address,chainId:_,client:e})}if(s?.fn&&s.runAt?.includes("beforeFillTransaction"))r=await s.fn({...r,chain:n},{client:e,phase:"beforeFillTransaction"}),p??=r.nonce;let h=(()=>{if((a.includes("blobVersionedHashes")||a.includes("sidecars"))&&r.kzg&&r.blobs)return!1;if(n5.get(e.uid)===!1)return!1;if(!["fees","gas"].some((T)=>a.includes(T)))return!1;if(a.includes("chainId")&&typeof r.chainId!=="number")return!0;if(a.includes("nonce")&&typeof p!=="number")return!0;if(a.includes("fees")&&typeof r.gasPrice!=="bigint"&&(typeof r.maxFeePerGas!=="bigint"||typeof r.maxPriorityFeePerGas!=="bigint"))return!0;if(a.includes("gas")&&typeof r.gas!=="bigint")return!0;return!1})()?await Le(e,yS,"fillTransaction")({...r,nonce:p}).then((_)=>{let{chainId:T,from:k,gas:O,gasPrice:z,nonce:L,maxFeePerBlobGas:P,maxFeePerGas:F,maxPriorityFeePerGas:G,type:ue,...W}=_.transaction;return n5.set(e.uid,!0),{...r,...k?{from:k}:{},...ue&&!r.type?{type:ue}:{},...typeof T<"u"?{chainId:T}:{},...typeof O<"u"?{gas:O}:{},...typeof z<"u"?{gasPrice:z}:{},...typeof L<"u"?{nonce:L}:{},...typeof P<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:P}:{},...typeof F<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:F}:{},...typeof G<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:G}:{},..."nonceKey"in W&&typeof W.nonceKey<"u"?{nonceKey:W.nonceKey}:{},..."keyAuthorization"in W&&typeof W.keyAuthorization<"u"&&W.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:W.keyAuthorization}:{},..."feePayerSignature"in W&&typeof W.feePayerSignature<"u"&&W.feePayerSignature!==null?{feePayerSignature:W.feePayerSignature}:{},..."feeToken"in W&&typeof W.feeToken<"u"&&W.feeToken!==null&&!("feeToken"in r)?{feeToken:W.feeToken}:{},..._.capabilities?{_capabilities:_.capabilities}:{}}}).catch((_)=>{let T=_;if(T.name!=="TransactionExecutionError")return r;if(T.walk?.((z)=>z.name==="ExecutionRevertedError"))throw _;if(T.walk?.((z)=>{let L=z;return L.name==="MethodNotFoundRpcError"||L.name==="MethodNotSupportedRpcError"||L.message?.includes("eth_fillTransaction is not available")}))n5.set(e.uid,!1);return r}):r;p??=h.nonce,r={...h,...d?{from:d?.address}:{},...typeof p<"u"?{nonce:p}:{}};let{blobs:y,gas:x,kzg:S,type:v}=r;if(s?.fn&&s.runAt?.includes("beforeFillParameters"))r=await s.fn({...r,chain:n},{client:e,phase:"beforeFillParameters"});let E;async function w(){if(E)return E;return E=await Le(e,si,"getBlock")({blockTag:"latest"}),E}if(a.includes("nonce")&&typeof p>"u"&&d&&!i)r.nonce=await Le(e,kS,"getTransactionCount")({address:d.address,blockTag:"pending"});if((a.includes("blobVersionedHashes")||a.includes("sidecars"))&&y&&S){let _=kf({blobs:y,kzg:S});if(a.includes("blobVersionedHashes")){let T=AS({commitments:_,to:"hex"});r.blobVersionedHashes=T}if(a.includes("sidecars")){let T=Af({blobs:y,commitments:_,kzg:S}),k=$S({blobs:y,commitments:_,proofs:T,to:"hex"});r.sidecars=k}}if(a.includes("chainId"))r.chainId=await u();if((a.includes("fees")||a.includes("type"))&&typeof v>"u")try{r.type=OS(r)}catch{let _=gW.get(e.uid);if(typeof _>"u")_=typeof(await w())?.baseFeePerGas==="bigint",gW.set(e.uid,_);r.type=_?"eip1559":"legacy"}if(a.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let _=await w(),{maxFeePerGas:T,maxPriorityFeePerGas:k}=await KC(e,{block:_,chain:n,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<k)throw new gC({maxPriorityFeePerGas:k});r.maxPriorityFeePerGas=k,r.maxFeePerGas=T}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Yu;if(typeof r.gasPrice>"u"){let _=await w(),{gasPrice:T}=await KC(e,{block:_,chain:n,request:r,type:"legacy"});r.gasPrice=T}}if(a.includes("gas")&&typeof x>"u")r.gas=await Le(e,cW,"estimateGas")({...r,account:d,prepare:d?.type==="local"?[]:["blobVersionedHashes"]});if(s?.fn&&s.runAt?.includes("afterFillParameters"))r=await s.fn({...r,chain:n},{client:e,phase:"afterFillParameters"});return Eo(r),delete r.parameters,r}async function CS(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var o5=new Xn(128);async function wc(e,t){let{account:r=e.account,assertChainId:o=!0,chain:n=e.chain,accessList:i,authorizationList:a,blobs:s,data:c,dataSuffix:u=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,type:S,value:v,...E}=t;if(typeof r>"u")throw new Jr({docsPath:"/docs/actions/wallet/sendTransaction"});let w=r?wt(r):null,_;try{Eo(t);let T=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(a&&a.length>0)return await Ef({authorization:a[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`.")});return})();if(w?.type==="json-rpc"||w===null){let k;if(n!==null){if(k=await Le(e,rn,"getChainId")({}),o)Pf({currentChainId:k,chain:n})}let O=e.chain?.formatters?.transactionRequest?.format,L=(O||ji)({...bc(E,{format:O}),accessList:i,account:w,authorizationList:a,blobs:s,chainId:k,data:u?gr([c??"0x",u]):c,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,to:T,type:S,value:v},"sendTransaction"),P=o5.get(e.uid),F=P?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:F,params:[L]},{retryCount:0})}catch(G){if(P===!1)throw G;let ue=G;if(ue.name==="InvalidInputRpcError"||ue.name==="InvalidParamsRpcError"||ue.name==="MethodNotFoundRpcError"||ue.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[L]},{retryCount:0}).then((W)=>(o5.set(e.uid,!0),W)).catch((W)=>{let H=W;if(H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError")throw o5.set(e.uid,!1),ue;throw H});throw ue}}if(w?.type==="local"){if(w.nonceManager&&typeof x>"u"){let L=E.chainId,P=await(async()=>{if(typeof L==="number")return L;if(n)return n.id;return Le(e,rn,"getChainId")({})})();_={address:w.address,chainId:P}}let k=await Le(e,_c,"prepareTransactionRequest")({account:w,accessList:i,authorizationList:a,blobs:s,chain:n,data:u?gr([c??"0x",u]):c,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,nonceManager:w.nonceManager,parameters:[...Cy,"sidecars"],type:S,value:v,...E,to:T}),O=n?.serializers?.transaction,z=await w.signTransaction(k,{serializer:O});return await Le(e,CS,"sendRawTransaction")({serializedTransaction:z})}if(w?.type==="smart")throw new ci({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new ci({docsPath:"/docs/actions/wallet/sendTransaction",type:w?.type})}catch(T){if(T instanceof ci)throw T;if(_)w?.nonceManager?.reset(_);throw yc(T,{...t,account:w,chain:t.chain||void 0})}}function yW(e,t){let{abi:r,args:o,bytecode:n,...i}=t,a=QZ({abi:r,args:o,bytecode:n});return wc(e,{...i,...i.authorizationList?{to:null}:{},data:a})}async function bW(e){if(e.account?.type==="local")return[e.account.address];return(await e.request({method:"eth_accounts"},{dedupe:!0})).map((r)=>Wa(r))}function xW(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var i5={"0x0":"reverted","0x1":"success"};function zS(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map((o)=>xW(o)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?$r(e.transactionIndex):null,status:e.status?i5[e.status]:null,type:e.type?PC[e.type]||e.type:null};if(e.blobGasPrice)r.blobGasPrice=BigInt(e.blobGasPrice);if(e.blobGasUsed)r.blobGasUsed=BigInt(e.blobGasUsed);return r}var wxe=(e)=>hr(_f(e));function vW(e){return wxe(e)}rp();function _W(e){let t=!0,r="",o=0,n="",i=!1;for(let a=0;a<e.length;a++){let s=e[a];if(["(",")",","].includes(s))t=!0;if(s==="(")o++;if(s===")")o--;if(!t)continue;if(o===0){if(s===" "&&["event","function",""].includes(n))n="";else if(n+=s,s===")"){i=!0;break}continue}if(s===" "){if(e[a-1]!==","&&r!==","&&r!==",(")r="",t=!1;continue}n+=s,r+=s}if(!i)throw new q("Unable to normalize signature.");return n}var wW=(e)=>{let t=(()=>{if(typeof e==="string")return e;return Ca(e)})();return _W(t)};function NS(e){return vW(wW(e))}var Rf=(e)=>Ka(NS(e),0,4);var SW=NS;function MS(e){let{abi:t,args:r=[],name:o}=e,n=Wr(o,{strict:!1}),i=t.filter((s)=>{if(n){if(s.type==="function")return Rf(s)===o;if(s.type==="event")return SW(s)===o;return!1}return"name"in s&&s.name===o});if(i.length===0)return;if(i.length===1)return i[0];let a;for(let s of i){if(!("inputs"in s))continue;if(!r||r.length===0){if(!s.inputs||s.inputs.length===0)return s;continue}if(!s.inputs)continue;if(s.inputs.length===0)continue;if(s.inputs.length!==r.length)continue;if(r.every((u,d)=>{let p="inputs"in s&&s.inputs[d];if(!p)return!1;return a5(u,p)})){if(a&&"inputs"in a&&a.inputs){let u=TW(s.inputs,a.inputs,r);if(u)throw new MC({abiItem:s,type:u[0]},{abiItem:a,type:u[1]})}a=s}}if(a)return a;return i[0]}function a5(e,t){let r=typeof e,o=t.type;switch(o){case"address":return Nt(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(o==="tuple"&&"components"in t)return Object.values(t.components).every((n,i)=>r==="object"&&a5(Object.values(e)[i],n));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(o))return r==="number"||r==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(o))return r==="string"||e instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(o))return Array.isArray(e)&&e.every((n)=>a5(n,{...t,type:o.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function TW(e,t,r){for(let o in e){let n=e[o],i=t[o];if(n.type==="tuple"&&i.type==="tuple"&&"components"in n&&"components"in i)return TW(n.components,i.components,r[o]);let a=[n.type,i.type];if((()=>{if(a.includes("address")&&a.includes("bytes20"))return!0;if(a.includes("address")&&a.includes("string"))return Nt(r[o],{strict:!1});if(a.includes("address")&&a.includes("bytes"))return Nt(r[o],{strict:!1});return!1})())return a}return}var EW="/docs/contract/encodeFunctionData";function IW(e){let{abi:t,args:r,functionName:o}=e,n=t[0];if(o){let i=MS({abi:t,args:r,name:o});if(!i)throw new vS(o,{docsPath:EW});n=i}if(n.type!=="function")throw new vS(void 0,{docsPath:EW});return{abi:[n],functionName:Rf(Fi(n))}}function BS(e){let{args:t}=e,{abi:r,functionName:o}=(()=>{if(e.abi.length===1&&e.functionName?.startsWith("0x"))return e;return IW(e)})(),n=r[0],i=o,a="inputs"in n&&n.inputs?ol(n.inputs,t??[]):void 0;return Io([i,a??"0x"])}var s5="0x5792579257925792579257925792579257925792579257925792579257925792",c5=ae(0,{size:32});async function DS(e,t){let{account:r=e.account,chain:o=e.chain,experimental_fallback:n,experimental_fallbackDelay:i=32,forceAtomic:a=!1,id:s,version:c="2.0.0"}=t,u=r?wt(r):null,d=t.capabilities;if(e.dataSuffix&&!t.capabilities?.dataSuffix)if(typeof e.dataSuffix==="string")d={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}};else d={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}};let p=t.calls.map((m)=>{let h=m,y=h.abi?BS({abi:h.abi,functionName:h.functionName,args:h.args}):h.data;return{data:h.dataSuffix&&y?gr([y,h.dataSuffix]):y,to:h.to,value:h.value?ae(h.value):void 0}});try{let m=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:p,capabilities:d,chainId:ae(o.id),from:u?.address,id:s,version:c}]},{retryCount:0});if(typeof m==="string")return{id:m};return m}catch(m){let h=m;if(n&&(h.name==="MethodNotFoundRpcError"||h.name==="MethodNotSupportedRpcError"||h.name==="UnknownRpcError"||h.details.toLowerCase().includes("does not exist / is not available")||h.details.toLowerCase().includes("missing or invalid. request()")||h.details.toLowerCase().includes("did not match any variant of untagged enum")||h.details.toLowerCase().includes("account upgraded to unsupported contract")||h.details.toLowerCase().includes("eip-7702 not supported")||h.details.toLowerCase().includes("unsupported wc_ method")||h.details.toLowerCase().includes("feature toggled misconfigured")||h.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(d){if(Object.values(d).some((v)=>!v.optional))throw new hc(new q("non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.",{details:"non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`."}))}if(a&&p.length>1)throw new gc(new q("`forceAtomic` is not supported on fallback to `eth_sendTransaction`.",{details:"`forceAtomic` is not supported on fallback to `eth_sendTransaction`."}));let y=[];for(let S of p){try{let v=await wc(e,{account:u,chain:o,data:S.data,to:S.to,value:S.value?Rr(S.value):void 0});y.push({status:"fulfilled",value:v})}catch(v){y.push({reason:v,status:"rejected"})}if(i>0)await new Promise((v)=>setTimeout(v,i))}if(y.every((S)=>S.status==="rejected"))throw y[0].reason;let x=y.map((S)=>{if(S.status==="fulfilled")return S.value;return c5});return{id:gr([...x,ae(o.id,{size:32}),s5])}}throw yc(m,{...t,account:u,chain:t.chain})}}async function US(e,t){async function r(d){if(d.endsWith(s5.slice(2))){let m=To(_S(d,-64,-32)),h=_S(d,0,-64).slice(2).match(/.{1,64}/g),y=await Promise.all(h.map((S)=>c5.slice(2)!==S?e.request({method:"eth_getTransactionReceipt",params:[`0x${S}`]},{dedupe:!0}):void 0)),x=(()=>{if(y.some((S)=>S===null))return 100;if(y.every((S)=>S?.status==="0x1"))return 200;if(y.every((S)=>S?.status==="0x0"))return 500;return 600})();return{atomic:!1,chainId:$r(m),receipts:y.filter(Boolean),status:x,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}let{atomic:o=!1,chainId:n,receipts:i,version:a="2.0.0",...s}=await r(t.id),[c,u]=(()=>{let d=s.status;if(d>=100&&d<200)return["pending",d];if(d>=200&&d<300)return["success",d];if(d>=300&&d<700)return["failure",d];if(d==="CONFIRMED")return["success",200];if(d==="PENDING")return["pending",100];return[void 0,d]})();return{...s,atomic:o,chainId:n?$r(n):void 0,receipts:i?.map((d)=>({...d,blockNumber:Rr(d.blockNumber),gasUsed:Rr(d.gasUsed),status:i5[d.status]}))??[],statusCode:u,status:c,version:a}}async function PW(e,t={}){let{account:r=e.account,chainId:o}=t,n=r?wt(r):void 0,i=o?[n?.address,[ae(o)]]:[n?.address],a=await e.request({method:"wallet_getCapabilities",params:i}),s={};for(let[c,u]of Object.entries(a)){s[Number(c)]={};for(let[d,p]of Object.entries(u)){if(d==="addSubAccount")d="unstable_addSubAccount";s[Number(c)][d]=p}}return typeof o==="number"?s[o]:s}async function kW(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}function AW(e,t){if(!Nt(e,{strict:!1}))throw new Wt({address:e});if(!Nt(t,{strict:!1}))throw new Wt({address:t});return e.toLowerCase()===t.toLowerCase()}async function LS(e,t){let{account:r=e.account,chainId:o,nonce:n}=t;if(!r)throw new Jr({docsPath:"/docs/eip7702/prepareAuthorization"});let i=wt(r),a=(()=>{if(!t.executor)return;if(t.executor==="self")return t.executor;return wt(t.executor)})(),s={address:t.contractAddress??t.address,chainId:o,nonce:n};if(typeof s.chainId>"u")s.chainId=e.chain?.id??await Le(e,rn,"getChainId")({});if(typeof s.nonce>"u"){if(s.nonce=await Le(e,kS,"getTransactionCount")({address:i.address,blockTag:"pending"}),a==="self"||a?.address&&AW(a.address,i.address))s.nonce+=1}return s}async function RW(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map((r)=>VZ(r))}async function $W(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}class u5 extends q{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"});Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}var jS=new Map,l5=new Map,Sxe=0;function il(e,t,r){let o=++Sxe,n=()=>jS.get(e)||[],i=()=>{let p=n().filter((m)=>m.id!==o);if(p.length===0){jS.delete(e),l5.delete(e);return}jS.set(e,p)},a=()=>{let d=n();if(!d.some((m)=>m.id===o))return;let p=l5.get(e);if(d.length===1&&p){let m=p();if(m instanceof Promise)m.catch(()=>{})}i()},s=n();if(jS.set(e,[...s,{id:o,fns:t}]),s&&s.length>0)return a;let c={};for(let d in t)c[d]=(...p)=>{let m=n();if(m.length===0)return;for(let h of m)h.fns[d]?.(...p)};let u=r(c);if(typeof u==="function")l5.set(e,u);return a}async function zy(e,{signal:t}={}){return new Promise((r,o)=>{if(t?.aborted){o(ai(t));return}let n=()=>t?.removeEventListener("abort",a),i=setTimeout(()=>{n(),r()},e),a=()=>{clearTimeout(i),n(),o(ai(t))};t?.addEventListener("abort",a,{once:!0})})}function FS(e,{emitOnBegin:t,initialWaitTime:r,interval:o}){let n=!0,i=()=>n=!1;return(async()=>{let s;if(t)s=await e({unpoll:i});let c=await r?.(s)??o;await zy(c);let u=async()=>{if(!n)return;await e({unpoll:i}),await zy(o),u()};u()})(),i}function $f(){let e=()=>{return},t=()=>{return};return{promise:new Promise((o,n)=>{e=o,t=n}),resolve:e,reject:t}}function al(e,{delay:t=100,retryCount:r=2,shouldRetry:o=()=>!0,signal:n}={}){return new Promise((i,a)=>{let s=async({count:c=0}={})=>{if(n?.aborted){a(ai(n));return}let u=async({error:d})=>{let p=typeof t==="function"?t({count:c,error:d}):t;if(p)try{await zy(p,{signal:n})}catch(m){a(m);return}s({count:c+1})};try{let d=await e();i(d)}catch(d){if(n?.aborted){a(ai(n));return}if(Ha(d)){a(d);return}if(c<r&&await o({count:c,error:d}))return u({error:d});a(d)}};s()})}async function qS(e,t){let{id:r,pollingInterval:o=e.pollingInterval,status:n=({statusCode:x})=>x===200||x>=300,retryCount:i=4,retryDelay:a=({count:x})=>~~(1<<x)*200,timeout:s=60000,throwOnFailure:c=!1}=t,u=rr(["waitForCallsStatus",e.uid,r]),{promise:d,resolve:p,reject:m}=$f(),h,y=il(u,{resolve:p,reject:m},(x)=>{let S=FS(async()=>{let v=(E)=>{clearTimeout(h),S(),E(),y()};try{let E=await al(async()=>{let w=await Le(e,US,"getCallsStatus")({id:r});if(c&&w.status==="failure")throw new u5(w);return w},{retryCount:i,delay:a});if(!n(E))return;v(()=>x.resolve(E))}catch(E){v(()=>x.reject(E))}},{interval:o,emitOnBegin:!0});return S});return h=s?setTimeout(()=>{y(),clearTimeout(h),m(new OW({id:r}))},s):void 0,await d}class OW extends q{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}async function CW(e,t){let{chain:r=e.chain}=t,o=t.timeout??Math.max((r?.blockTime??0)*3,5000),n=await Le(e,DS,"sendCalls")(t);return await Le(e,qS,"waitForCallsStatus")({...t,id:n.id,timeout:o})}async function HS(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:o}){let n=await e.request({method:"eth_sendRawTransactionSync",params:o?[t,o]:[t]},{retryCount:0}),a=(e.chain?.formatters?.transactionReceipt?.format||zS)(n);if(a.status==="reverted"&&r)throw new ef({receipt:a});return a}async function zW(e,{blockHash:t,blockNumber:r,blockTag:o,hash:n,index:i,sender:a,nonce:s}){let c=o||"latest",u=r!==void 0?ae(r):void 0,d=null;if(n)d=await e.request({method:"eth_getTransactionByHash",params:[n]},{dedupe:!0});else if(t)d=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,ae(i)]},{dedupe:!0});else if((u||c)&&typeof i==="number")d=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,ae(i)]},{dedupe:Boolean(u)});else if(a&&typeof s==="number")d=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[a,ae(s)]},{dedupe:!0});if(!d)throw new ky({blockHash:t,blockNumber:r,blockTag:c,hash:n,index:i});return(e.chain?.formatters?.transaction?.format||wf)(d,"getTransaction")}async function GS(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new Ay({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||zS)(r,"getTransactionReceipt")}var Txe=new Map,Exe=new Map;function NW(e){let t=(n,i)=>({clear:()=>i.delete(n),get:()=>i.get(n),set:(a)=>i.set(n,a)}),r=t(e,Txe),o=t(e,Exe);return{clear:()=>{r.clear(),o.clear()},promise:r,response:o}}async function MW(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let o=NW(t),n=o.response.get();if(n&&r>0){if(Date.now()-n.created.getTime()<r)return n.data}let i=o.promise.get();if(!i)i=e(),o.promise.set(i);try{let a=await i;return o.response.set({created:new Date,data:a}),a}finally{o.promise.clear()}}var Ixe=(e)=>`blockNumber.${e}`;async function BW(e,{cacheTime:t=e.cacheTime}={}){let r=await MW(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Ixe(e.uid),cacheTime:t});return BigInt(r)}function DW(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:o,onError:n,poll:i,pollingInterval:a=e.pollingInterval}){let s=(()=>{if(typeof i<"u")return i;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),c;return s?(()=>{let p=rr(["watchBlockNumber",e.uid,t,r,a]);return il(p,{onBlockNumber:o,onError:n},(m)=>FS(async()=>{try{let h=await Le(e,BW,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(h===c)return;if(h-c>1&&r)for(let y=c+1n;y<h;y++)m.onBlockNumber(y,c),c=y}if(c===void 0||h>c)m.onBlockNumber(h,c),c=h}catch(h){m.onError?.(h)}},{emitOnBegin:t,interval:a}))})():(()=>{let p=rr(["watchBlockNumber",e.uid,t,r]);return il(p,{onBlockNumber:o,onError:n},(m)=>{let h=!0,y=()=>h=!1;return(async()=>{try{let x=(()=>{if(e.transport.type==="fallback"){let v=e.transport.transports.find((E)=>E.config.type==="webSocket"||E.config.type==="ipc");if(!v)return e.transport;return v.value}return e.transport})(),{unsubscribe:S}=await x.subscribe({params:["newHeads"],onData(v){if(!h)return;let E=Rr(v.result?.number);m.onBlockNumber(E,c),c=E},onError(v){m.onError?.(v)}});if(y=S,!h)y()}catch(x){n?.(x)}})(),()=>y()})})()}async function UW(e,t){let{checkReplacement:r=!0,confirmations:o=1,hash:n,onReplaced:i,retryCount:a=6,retryDelay:s=({count:T})=>~~(1<<T)*200,timeout:c=180000}=t,u=rr(["waitForTransactionReceipt",e.uid,n]),d=(()=>{if(t.pollingInterval)return t.pollingInterval;if(e.chain?.experimental_preconfirmationTime)return e.chain.experimental_preconfirmationTime;return e.pollingInterval})(),p,m,h,y=!1,x,S,{promise:v,resolve:E,reject:w}=$f(),_=c?setTimeout(()=>{S?.(),x?.(),w(new _C({hash:n}))},c):void 0;return x=il(u,{onReplaced:i,resolve:E,reject:w},async(T)=>{if(h=await Le(e,GS,"getTransactionReceipt")({hash:n}).catch(()=>{return}),h&&o<=1){clearTimeout(_),T.resolve(h),x?.();return}S=Le(e,DW,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:d,async onBlockNumber(k){let O=(L)=>{clearTimeout(_),S?.(),L(),x?.()},z=k;if(y)return;try{if(h){if(o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;O(()=>T.resolve(h));return}if(r&&!p)y=!0,await al(async()=>{if(p=await Le(e,zW,"getTransaction")({hash:n}),p.blockNumber)z=p.blockNumber},{delay:s,retryCount:a}),y=!1;if(h=await Le(e,GS,"getTransactionReceipt")({hash:n}),o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;O(()=>T.resolve(h))}catch(L){if(L instanceof ky||L instanceof Ay){if(!p){y=!1;return}try{m=p,y=!0;let P=await al(()=>Le(e,si,"getBlock")({blockNumber:z,includeTransactions:!0}),{delay:s,retryCount:a,shouldRetry:({error:ue})=>ue instanceof Ry});y=!1;let F=P.transactions.find(({from:ue,nonce:W})=>ue===m.from&&W===m.nonce);if(!F)return;if(h=await Le(e,GS,"getTransactionReceipt")({hash:F.hash}),o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;let G="replaced";if(F.to===m.to&&F.value===m.value&&F.input===m.input)G="repriced";else if(F.from===F.to&&F.value===0n)G="cancelled";O(()=>{T.onReplaced?.({reason:G,replacedTransaction:m,transaction:F,transactionReceipt:h}),T.resolve(h)})}catch(P){O(()=>T.reject(P))}}else O(()=>T.reject(L))}}})}),v}var d5=new Xn(128);async function VS(e,t){let{account:r=e.account,assertChainId:o=!0,chain:n=e.chain,accessList:i,authorizationList:a,blobs:s,data:c,dataSuffix:u=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,pollingInterval:S,throwOnReceiptRevert:v,type:E,value:w,..._}=t,T=t.timeout??Math.max((n?.blockTime??0)*3,5000);if(typeof r>"u")throw new Jr({docsPath:"/docs/actions/wallet/sendTransactionSync"});let k=r?wt(r):null,O;try{Eo(t);let z=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(a&&a.length>0)return await Ef({authorization:a[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`.")});return})();if(k?.type==="json-rpc"||k===null){let L;if(n!==null){if(L=await Le(e,rn,"getChainId")({}),o)Pf({currentChainId:L,chain:n})}let P=e.chain?.formatters?.transactionRequest?.format,G=(P||ji)({...bc(_,{format:P}),accessList:i,account:k,authorizationList:a,blobs:s,chainId:L,data:u?gr([c??"0x",u]):c,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,to:z,type:E,value:w},"sendTransaction"),ue=d5.get(e.uid),W=ue?"wallet_sendTransaction":"eth_sendTransaction",H=await(async()=>{try{return await e.request({method:W,params:[G]},{retryCount:0})}catch(Te){if(ue===!1)throw Te;let C=Te;if(C.name==="InvalidInputRpcError"||C.name==="InvalidParamsRpcError"||C.name==="MethodNotFoundRpcError"||C.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[G]},{retryCount:0}).then((B)=>(d5.set(e.uid,!0),B)).catch((B)=>{let Z=B;if(Z.name==="MethodNotFoundRpcError"||Z.name==="MethodNotSupportedRpcError")throw d5.set(e.uid,!1),C;throw Z});throw C}})(),fe=await Le(e,UW,"waitForTransactionReceipt")({checkReplacement:!1,hash:H,pollingInterval:S,timeout:T});if(v&&fe.status==="reverted")throw new ef({receipt:fe});return fe}if(k?.type==="local"){if(k.nonceManager&&typeof x>"u"){let G=_.chainId,ue=await(async()=>{if(typeof G==="number")return G;if(n)return n.id;return Le(e,rn,"getChainId")({})})();O={address:k.address,chainId:ue}}let L=await Le(e,_c,"prepareTransactionRequest")({account:k,accessList:i,authorizationList:a,blobs:s,chain:n,data:u?gr([c??"0x",u]):c,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,nonceManager:k.nonceManager,parameters:[...Cy,"sidecars"],type:E,value:w,..._,to:z}),P=n?.serializers?.transaction,F=await k.signTransaction(L,{serializer:P});return await Le(e,HS,"sendRawTransactionSync")({serializedTransaction:F,throwOnReceiptRevert:v,timeout:t.timeout})}if(k?.type==="smart")throw new ci({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new ci({docsPath:"/docs/actions/wallet/sendTransactionSync",type:k?.type})}catch(z){if(z instanceof ci)throw z;if(O&&!(z instanceof ef))k?.nonceManager?.reset(O);throw yc(z,{...t,account:k,chain:t.chain||void 0})}}async function LW(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]});return}async function jW(e,t){let{account:r=e.account}=t;if(!r)throw new Jr({docsPath:"/docs/eip7702/signAuthorization"});let o=wt(r);if(!o.signAuthorization)throw new ci({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:o.type});let n=await LS(e,t);return o.signAuthorization(n)}async function FW(e,{account:t=e.account,message:r}){if(!t)throw new Jr({docsPath:"/docs/actions/wallet/signMessage"});let o=wt(t);if(o.signMessage)return o.signMessage({message:r});let n=(()=>{if(typeof r==="string")return vc(r);if(r.raw instanceof Uint8Array)return Kr(r.raw);return r.raw})();return e.request({method:"personal_sign",params:[n,o.address]},{retryCount:0})}async function qW(e,t){let{account:r=e.account,chain:o=e.chain,...n}=t;if(!r)throw new Jr({docsPath:"/docs/actions/wallet/signTransaction"});let i=wt(r);Eo({account:i,...t});let a=await Le(e,rn,"getChainId")({});if(o!==null)Pf({currentChainId:a,chain:o});let c=(o?.formatters||e.chain?.formatters)?.transactionRequest?.format||ji;if(i.signTransaction)return i.signTransaction({...n,account:i,chainId:a},{serializer:e.chain?.serializers?.transaction});return await e.request({method:"eth_signTransaction",params:[{...c({...n,account:i},"signTransaction"),chainId:ae(a),from:i.address}]},{retryCount:0})}class p5 extends q{constructor({domain:e}){super(`Invalid domain "${rr(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class f5 extends q{constructor({primaryType:e,types:t}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(t))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class m5 extends q{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function HW(e){let{domain:t={},message:r,primaryType:o}=e,n={EIP712Domain:WS({domain:t}),...e.types};ZS({domain:t,message:r,primaryType:o,types:n});let i=["0x1901"];if(t)i.push(Pxe({domain:t,types:n}));if(o!=="EIP712Domain")i.push(GW({data:r,primaryType:o,types:n}));return hr(gr(i))}function Pxe({domain:e,types:t}){return GW({data:e,primaryType:"EIP712Domain",types:t})}function GW({data:e,primaryType:t,types:r}){let o=VW({data:e,primaryType:t,types:r});return hr(o)}function VW({data:e,primaryType:t,types:r}){let o=[{type:"bytes32"}],n=[kxe({primaryType:t,types:r})];for(let i of r[t]){let[a,s]=WW({types:r,name:i.name,type:i.type,value:e[i.name]});o.push(a),n.push(s)}return ol(o,n)}function kxe({primaryType:e,types:t}){let r=Kr(Axe({primaryType:e,types:t}));return hr(r)}function Axe({primaryType:e,types:t}){let r="",o=ZW({primaryType:e,types:t});o.delete(e);let n=[e,...Array.from(o).sort()];for(let i of n)r+=`${i}(${t[i].map(({name:a,type:s})=>`${s} ${a}`).join(",")})`;return r}function ZW({primaryType:e,types:t},r=new Set){let n=e.match(/^\w*/u)?.[0];if(r.has(n)||t[n]===void 0)return r;r.add(n);for(let i of t[n])ZW({primaryType:i.type,types:t},r);return r}function WW({types:e,name:t,type:r,value:o}){if(e[r]!==void 0)return[{type:"bytes32"},hr(VW({data:o,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},hr(o)];if(r==="string")return[{type:"bytes32"},hr(Kr(o))];if(r.lastIndexOf("]")===r.length-1){let n=r.slice(0,r.lastIndexOf("[")),i=o.map((a)=>WW({name:t,type:n,types:e,value:a}));return[{type:"bytes32"},hr(ol(i.map(([a])=>a),i.map(([,a])=>a)))]}return[{type:r},o]}function KW(e){let{domain:t,message:r,primaryType:o,types:n}=e,i=(c,u)=>{let d={...u};for(let p of c){let{name:m,type:h}=p;if(h==="address")d[m]=d[m].toLowerCase()}return d},a=(()=>{if(!n.EIP712Domain)return{};if(!t)return{};return i(n.EIP712Domain,t)})(),s=(()=>{if(o==="EIP712Domain")return;return i(n[o],r)})();return rr({domain:a,message:s,primaryType:o,types:n})}function ZS(e){let{domain:t,message:r,primaryType:o,types:n}=e,i=(a,s)=>{for(let c of a){let{name:u,type:d}=c,p=s[u],m=d.match(wS);if(m&&(typeof p==="number"||typeof p==="bigint")){let[x,S,v]=m;ae(p,{signed:S==="int",size:Number.parseInt(v,10)/8})}if(d==="address"&&typeof p==="string"&&!Nt(p))throw new Wt({address:p});let h=d.match(YZ);if(h){let[x,S]=h;if(S&&St(p)!==Number.parseInt(S,10))throw new BC({expectedSize:Number.parseInt(S,10),givenSize:St(p)})}let y=n[d];if(y)Rxe(d),i(y,p)}};if(n.EIP712Domain&&t){if(typeof t!=="object")throw new p5({domain:t});i(n.EIP712Domain,t)}if(o!=="EIP712Domain")if(n[o])i(n[o],r);else throw new f5({primaryType:o,types:n})}function WS({domain:e}){return[typeof e?.name==="string"&&{name:"name",type:"string"},e?.version&&{name:"version",type:"string"},(typeof e?.chainId==="number"||typeof e?.chainId==="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function Rxe(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new m5({type:e})}async function JW(e,t){let{account:r=e.account,domain:o,message:n,primaryType:i}=t;if(!r)throw new Jr({docsPath:"/docs/actions/wallet/signTypedData"});let a=wt(r),s={EIP712Domain:WS({domain:o}),...t.types};if(ZS({domain:o,message:n,primaryType:i,types:s}),a.signTypedData)return a.signTypedData({domain:o,message:n,primaryType:i,types:s});let c=KW({domain:o,message:n,primaryType:i,types:s});return e.request({method:"eth_signTypedData_v4",params:[a.address,c]},{retryCount:0})}async function YW(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:ae(t)}]},{retryCount:0})}async function QW(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}var XW={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."},eK={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},tK={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};function rK(e,t={}){if(typeof t.size<"u")Qn(e,{size:t.size});let r=Ht(e,t);return Rr(r,t)}function nK(e,t={}){let r=e;if(typeof t.size<"u")Qn(r,{size:t.size}),r=To(r);if(r.length>1||r[0]>1)throw new SC(r);return Boolean(r[0])}function qi(e,t={}){if(typeof t.size<"u")Qn(e,{size:t.size});let r=Ht(e,t);return $r(r,t)}function oK(e,t={}){let r=e;if(typeof t.size<"u")Qn(r,{size:t.size}),r=To(r,{dir:"right"});return new TextDecoder().decode(r)}function aK(e,t){let r=typeof t==="string"?vr(t):t,o=Tf(r);if(St(r)===0&&e.length>0)throw new nl;if(St(t)&&St(t)<32)throw new OC({data:typeof t==="string"?t:Ht(t),params:e,size:St(t)});let n=0,i=[];for(let a=0;a<e.length;++a){let s=e[a];o.setPosition(n);let[c,u]=Of(o,s,{staticPosition:0});n+=u,i.push(c)}return i}function Of(e,t,{staticPosition:r}){let o=SS(t.type);if(o){let[n,i]=o;return Oxe(e,{...t,type:i},{length:n,staticPosition:r})}if(t.type==="tuple")return Mxe(e,t,{staticPosition:r});if(t.type==="address")return $xe(e);if(t.type==="bool")return Cxe(e);if(t.type.startsWith("bytes"))return zxe(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return Nxe(e,t);if(t.type==="string")return Bxe(e,{staticPosition:r});throw new UC(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}var iK=32,h5=32;function $xe(e){let t=e.readBytes(32);return[Wa(Ht(jC(t,-20))),32]}function Oxe(e,t,{length:r,staticPosition:o}){if(!r){let a=qi(e.readBytes(h5)),s=o+a,c=s+iK;e.setPosition(s);let u=qi(e.readBytes(iK)),d=Ny(t),p=0,m=[];for(let h=0;h<u;++h){e.setPosition(c+(d?h*32:p));let[y,x]=Of(e,t,{staticPosition:c});p+=x,m.push(y)}return e.setPosition(o+32),[m,32]}if(Ny(t)){let a=qi(e.readBytes(h5)),s=o+a,c=[];for(let u=0;u<r;++u){e.setPosition(s+u*32);let[d]=Of(e,t,{staticPosition:s});c.push(d)}return e.setPosition(o+32),[c,32]}let n=0,i=[];for(let a=0;a<r;++a){let[s,c]=Of(e,t,{staticPosition:o+n});n+=c,i.push(s)}return[i,n]}function Cxe(e){return[nK(e.readBytes(32),{size:32}),32]}function zxe(e,t,{staticPosition:r}){let[o,n]=t.type.split("bytes");if(!n){let a=qi(e.readBytes(32));e.setPosition(r+a);let s=qi(e.readBytes(32));if(s===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(s);return e.setPosition(r+32),[Ht(c),32]}return[Ht(e.readBytes(Number.parseInt(n,10),32)),32]}function Nxe(e,t){let r=t.type.startsWith("int"),o=Number.parseInt(t.type.split("int")[1]||"256",10),n=e.readBytes(32);return[o>48?rK(n,{signed:r}):qi(n,{signed:r}),32]}function Mxe(e,t,{staticPosition:r}){let o=t.components.length===0||t.components.some(({name:a})=>!a),n=o?[]:{},i=0;if(Ny(t)){let a=qi(e.readBytes(h5)),s=r+a;for(let c=0;c<t.components.length;++c){let u=t.components[c];e.setPosition(s+i);let[d,p]=Of(e,u,{staticPosition:s});i+=p,n[o?c:u?.name]=d}return e.setPosition(r+32),[n,32]}for(let a=0;a<t.components.length;++a){let s=t.components[a],[c,u]=Of(e,s,{staticPosition:r});n[o?a:s?.name]=c,i+=u}return[n,i]}function Bxe(e,{staticPosition:t}){let r=qi(e.readBytes(32)),o=t+r;e.setPosition(o);let n=qi(e.readBytes(32));if(n===0)return e.setPosition(t+32),["",32];let i=e.readBytes(n,32),a=oK(To(i));return e.setPosition(t+32),[a,32]}function Ny(e){let{type:t}=e;if(t==="string")return!0;if(t==="bytes")return!0;if(t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(Ny);let r=SS(e.type);if(r&&Ny({...e,type:r[1]}))return!0;return!1}function sK(e){let{abi:t,data:r,cause:o}=e,n=Ka(r,0,4);if(n==="0x")throw new nl({cause:o});let a=[...t||[],eK,tK].find((s)=>s.type==="error"&&n===Rf(Fi(s)));if(!a)throw new $y(n,{docsPath:"/docs/contract/decodeErrorResult",cause:o});return{abiItem:a,args:"inputs"in a&&a.inputs&&a.inputs.length>0?aK(a.inputs,Ka(r,4)):void 0,errorName:a.name}}function g5({abiItem:e,args:t,includeFunctionName:r=!0,includeName:o=!1}){if(!("name"in e))return;if(!("inputs"in e))return;if(!e.inputs)return;return`${r?e.name:""}(${e.inputs.map((n,i)=>`${o&&n.name?`${n.name}: `:""}${typeof t[i]==="object"?rr(t[i]):t[i]}`).join(", ")})`}class y5 extends q{constructor(e,{abi:t,args:r,contractAddress:o,docsPath:n,functionName:i,sender:a}){let s=MS({abi:t,args:r,name:i}),c=s?g5({abiItem:s,args:r,includeFunctionName:!1,includeName:!1}):void 0,u=s?Fi(s,{includeName:!0}):void 0,d=Xp({address:o&&HZ(o),function:u,args:c&&c!=="()"&&`${[...Array(i?.length??0).keys()].map(()=>" ").join("")}${c}`,sender:a});super(e.shortMessage||`An unknown error occurred while executing the contract function "${i}".`,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],d&&"Contract Call:",d].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=t,this.args=r,this.cause=e,this.contractAddress=o,this.functionName=i,this.sender=a}}class b5 extends q{constructor({abi:e,data:t,functionName:r,message:o,cause:n}){let i,a,s,c;if(t&&t!=="0x")try{a=sK({abi:e,data:t,cause:n});let{abiItem:d,errorName:p,args:m}=a;if(p==="Error")c=m[0];else if(p==="Panic"){let[h]=m;c=XW[h]}else{let h=d?Fi(d,{includeName:!0}):void 0,y=d&&m?g5({abiItem:d,args:m,includeFunctionName:!1,includeName:!1}):void 0;s=[h?`Error: ${h}`:"",y&&y!=="()"?` ${[...Array(p?.length??0).keys()].map(()=>" ").join("")}${y}`:""]}}catch(d){i=d}else if(o)c=o;let u;if(i instanceof $y)u=i.signature,s=[`Unable to decode signature "${u}" 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=${u}.`];super(c&&c!=="execution reverted"||u?[`The contract function "${r}" reverted with the following ${u?"signature":"reason"}:`,c||u].join(`
167
167
  `):`The contract function "${r}" reverted.`,{cause:i??n,metaMessages:s,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=a,this.raw=t,this.reason=c,this.signature=u}}class x5 extends q{constructor({functionName:e,cause:t}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:t})}}class v5 extends q{constructor({data:e,message:t}){super(t||"",{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=e}}var Dxe=3;function cK(e,{abi:t,address:r,args:o,docsPath:n,functionName:i,sender:a}){let s=e instanceof v5?e:e instanceof q?e.walk((y)=>("data"in y))||e.walk():{},{code:c,data:u,details:d,message:p,shortMessage:m}=s,h=(()=>{if(e instanceof nl)return new x5({functionName:i,cause:e});if([Dxe,Ga.code].includes(c)&&(u||d||p||m)||c===fc.code&&d==="execution reverted"&&u)return new b5({abi:t,data:typeof u==="object"?u.data:u,functionName:i,message:s instanceof Xu?d:m??p,cause:e});return e})();return new y5(h,{abi:t,args:o,contractAddress:r,docsPath:n,functionName:i,sender:a})}async function sl(e,t){return sl.internal(e,wc,"sendTransaction",t)}(function(e){async function t(r,o,n,i){let{abi:a,account:s=r.account,address:c,args:u,functionName:d,...p}=i;if(typeof s>"u")throw new Jr({docsPath:"/docs/contract/writeContract"});let m=s?wt(s):null,h=BS({abi:a,args:u,functionName:d});try{return await Le(r,o,n)({data:h,to:c,account:m,...p})}catch(y){throw cK(y,{abi:a,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:d,sender:m?.address})}}e.internal=t})(sl||(sl={}));async function uK(e,t){return sl.internal(e,VS,"sendTransactionSync",t)}function lK(e){return{addChain:(t)=>WZ(e,t),deployContract:(t)=>yW(e,t),fillTransaction:(t)=>yS(e,t),getAddresses:()=>bW(e),getCallsStatus:(t)=>US(e,t),getCapabilities:(t)=>PW(e,t),getChainId:()=>rn(e),getPermissions:()=>kW(e),prepareAuthorization:(t)=>LS(e,t),prepareTransactionRequest:(t)=>_c(e,t),requestAddresses:()=>RW(e),requestPermissions:(t)=>$W(e,t),sendCalls:(t)=>DS(e,t),sendCallsSync:(t)=>CW(e,t),sendRawTransaction:(t)=>CS(e,t),sendRawTransactionSync:(t)=>HS(e,t),sendTransaction:(t)=>wc(e,t),sendTransactionSync:(t)=>VS(e,t),showCallsStatus:(t)=>LW(e,t),signAuthorization:(t)=>jW(e,t),signMessage:(t)=>FW(e,t),signTransaction:(t)=>qW(e,t),signTypedData:(t)=>JW(e,t),switchChain:(t)=>YW(e,t),waitForCallsStatus:(t)=>qS(e,t),watchAsset:(t)=>QW(e,t),writeContract:(t)=>sl(e,t),writeContractSync:(t)=>uK(e,t)}}function _5(e){let{key:t="wallet",name:r="Wallet Client",transport:o}=e;return LZ({...e,key:t,name:r,transport:o,type:"walletClient"}).extend(lK)}class w5 extends q{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 S5=new Map;function dK({fn:e,id:t,shouldSplitBatch:r,wait:o=0,sort:n}){let i=async()=>{let d=c();a();let p=d.map(({args:m})=>m);if(p.length===0)return;e(p).then((m)=>{if(n&&Array.isArray(m))m.sort(n);for(let h=0;h<d.length;h++){let{resolve:y}=d[h];y?.([m[h],m])}}).catch((m)=>{for(let h=0;h<d.length;h++){let{reject:y}=d[h];y?.(m)}})},a=()=>S5.delete(t),s=()=>c().map(({args:d})=>d),c=()=>S5.get(t)||[],u=(d)=>S5.set(t,[...c(),d]);return{flush:a,async schedule(d){let{promise:p,resolve:m,reject:h}=$f();if(r?.([...s(),d]))i();if(c().length>0)return u({args:d,resolve:m,reject:h}),p;return u({args:d,resolve:m,reject:h}),setTimeout(i,o),p}}}function pK(e,{errorInstance:t=Error("timed out"),timeout:r,signal:o}){return new Promise((n,i)=>{(async()=>{let a,s=new AbortController;try{if(r>0)a=setTimeout(()=>{if(o)s.abort();else i(t)},r);n(await e({signal:s?.signal||null}))}catch(c){if(s?.signal.aborted&&Ha(c)){i(t);return}i(c)}finally{clearTimeout(a)}})()})}function Uxe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var T5=Uxe();function fK(e,t={}){let{url:r,headers:o}=Lxe(e);return{async request(n){let{body:i,fetchFn:a=t.fetchFn??fetch,onRequest:s=t.onRequest,onResponse:c=t.onResponse,timeout:u=t.timeout??1e4}=n,d={...t.fetchOptions??{},...n.fetchOptions??{}},{headers:p,method:m,signal:h}=d;try{let y=await pK(async({signal:S})=>{let v={...d,body:Array.isArray(i)?rr(i.map((T)=>({jsonrpc:"2.0",id:T.id??T5.take(),...T}))):rr({jsonrpc:"2.0",id:i.id??T5.take(),...i}),headers:{...o,"Content-Type":"application/json",...p},method:m||"POST",signal:h||(u>0?S:null)},E=new Request(r,v),w=await s?.(E,v)??{...v,url:r};return await a(w.url??r,w)},{errorInstance:new pS({body:i,url:r}),timeout:u,signal:!0});if(c)await c(y);let x;if(y.headers.get("Content-Type")?.startsWith("application/json"))x=await y.json();else{x=await y.text();try{x=JSON.parse(x||"{}")}catch(S){if(y.ok)throw S;x={error:x}}}if(!y.ok){if(typeof x.error?.code==="number"&&typeof x.error?.message==="string")return x;throw new pc({body:i,details:rr(x.error)||y.statusText,headers:y.headers,status:y.status,url:r})}return x}catch(y){if(h?.aborted)throw ai(h);if(Ha(y))throw y;if(y instanceof pc)throw y;if(y instanceof pS)throw y;throw new pc({body:i,cause:y,url:r})}}}}function Lxe(e){try{let t=new URL(e),r=(()=>{if(t.username){let o=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(o)}`}}}return})();return{url:t.toString(),...r}}catch{return{url:e}}}var KS=new Xn(8192);function mK(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(KS.get(r))return KS.get(r);let o=e().finally(()=>KS.delete(r));return KS.set(r,o),o}function hK(e,t={}){return async(r,o={})=>{let{dedupe:n=!1,methods:i,retryDelay:a=150,retryCount:s=3,signal:c,uid:u}={...t,...o},{method:d}=r;if(i?.exclude?.includes(d))throw new mc(Error("method not supported"),{method:d});if(i?.include&&!i.include.includes(d))throw new mc(Error("method not supported"),{method:d});if(c?.aborted)throw ai(c);let p=n?Fxe(`${u}.${rr(r)}`):void 0;return mK(()=>al(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(m){if(c?.aborted)throw ai(c);if(Ha(m))throw m;let h=m;switch(h.code){case tf.code:throw new tf(h);case rf.code:throw new rf(h);case nf.code:throw new nf(h,{method:r.method});case of.code:throw new of(h);case Ga.code:throw new Ga(h);case fc.code:throw new fc(h);case af.code:throw new af(h);case sf.code:throw new sf(h);case cf.code:throw new cf(h);case mc.code:throw new mc(h,{method:r.method});case el.code:throw new el(h);case uf.code:throw new uf(h);case tl.code:throw new tl(h);case lf.code:throw new lf(h);case df.code:throw new df(h);case pf.code:throw new pf(h);case ff.code:throw new ff(h);case mf.code:throw new mf(h);case hc.code:throw new hc(h);case hf.code:throw new hf(h);case gf.code:throw new gf(h);case yf.code:throw new yf(h);case bf.code:throw new bf(h);case xf.code:throw new xf(h);case gc.code:throw new gc(h);case 5000:throw new tl(h);case vf.code:throw new vf(h);default:if(m instanceof q)throw m;throw new wC(h)}}},{delay:({count:m,error:h})=>{if(h&&h instanceof pc){let y=h?.headers?.get("Retry-After");if(y?.match(/\d/))return Number.parseInt(y,10)*1000}return~~(1<<m)*a},retryCount:s,signal:c,shouldRetry:({error:m})=>jxe(m)}),{enabled:n,id:p})}}function jxe(e){if(Ha(e))return!1;if("code"in e&&typeof e.code==="number"){if(e.code===-1)return!0;if(e.code===el.code)return!0;if(e.code===Ga.code)return!0;if(e.code===429)return!0;return!1}if(e instanceof pc&&e.status){if(e.status===403)return!0;if(e.status===408)return!0;if(e.status===413)return!0;if(e.status===429)return!0;if(e.status===500)return!0;if(e.status===502)return!0;if(e.status===503)return!0;if(e.status===504)return!0;return!1}return!0}function Fxe(e,t=0){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);r=Math.imul(r^i,2654435761),o=Math.imul(o^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>16,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&o)+(r>>>0)).toString(36)}function gK({key:e,methods:t,name:r,request:o,retryCount:n=3,retryDelay:i=150,timeout:a,type:s},c){let u=cS();return{config:{key:e,methods:t,name:r,request:o,retryCount:n,retryDelay:i,timeout:a,type:s},request:hK(o,{methods:t,retryCount:n,retryDelay:i,uid:u}),value:c}}var qxe=0,yK=new WeakMap;function Hxe(e){if(!e)return"default";let t=yK.get(e);if(t!==void 0)return t;let r=qxe++;return yK.set(e,r),r}function E5(e,t={}){let{batch:r,fetchFn:o,fetchOptions:n,key:i="http",methods:a,name:s="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:d,raw:p}=t;return({chain:m,retryCount:h,timeout:y})=>{let{batchSize:x=1000,wait:S=0}=typeof r==="object"?r:{},v=t.retryCount??h,E=y??t.timeout??1e4,w=e||m?.rpcUrls.default.http[0];if(!w)throw new w5;let _=fK(w,{fetchFn:o,fetchOptions:n,onRequest:c,onResponse:u,timeout:E});return gK({key:i,methods:a,name:s,async request({method:T,params:k},O){let z={method:T,params:k},L=O?.signal?{signal:O.signal}:void 0,{schedule:P}=dK({id:`${w}.${Hxe(O?.signal)}`,wait:S,shouldSplitBatch(W){return W.length>x},fn:(W)=>_.request({body:W,fetchOptions:L}),sort:(W,H)=>W.id-H.id}),F=async(W)=>r?P(W):[await _.request({body:W,fetchOptions:L})],[{error:G,result:ue}]=await F(z);if(p)return{error:G,result:ue};if(G)throw new Xu({body:z,error:G,url:w});return ue},retryCount:v,retryDelay:d,timeout:E,type:"http"},{fetchOptions:n,url:w})}}ic();function bK(e){if(typeof e==="string"){if(!Nt(e,{strict:!1}))throw new Wt({address:e});return{address:e,type:"json-rpc"}}if(!Nt(e.address,{strict:!1}))throw new Wt({address:e.address});return{address:e.address,nonceManager:e.nonceManager,sign:e.sign,signAuthorization:e.signAuthorization,signMessage:e.signMessage,signTransaction:e.signTransaction,signTypedData:e.signTypedData,source:"custom",type:"local"}}ic();ic();function xK({r:e,s:t,to:r="hex",v:o,yParity:n}){let i=(()=>{if(n===0||n===1)return n;if(o&&(o===27n||o===28n||o>=35n))return o%2n===0n?1:0;throw Error("Invalid `v` or `yParity` value")})(),a=`0x${new Sn.Signature(Rr(e),Rr(t)).toCompactHex()}${i===0?"1b":"1c"}`;if(r==="hex")return a;return vr(a)}var I5=!1;async function Hi({hash:e,privateKey:t,to:r="object"}){let{r:o,s:n,recovery:i}=Sn.sign(e.slice(2),t.slice(2),{lowS:!0,extraEntropy:Wr(I5,{strict:!1})?vr(I5):I5}),a={r:ae(o,{size:32}),s:ae(n,{size:32}),v:i?28n:27n,yParity:i};return(()=>{if(r==="bytes"||r==="hex")return xK({...a,to:r});return a})()}async function vK(e){let{chainId:t,nonce:r,privateKey:o,to:n="object"}=e,i=e.contractAddress??e.address,a=await Hi({hash:IS({address:i,chainId:t,nonce:r}),privateKey:o,to:n});if(n==="object")return{address:i,chainId:t,nonce:r,...a};return a}var _K=`\x19Ethereum Signed Message:
168
168
  `;function wK(e){let t=(()=>{if(typeof e==="string")return vc(e);if(typeof e.raw==="string")return e.raw;return Ht(e.raw)})(),r=vc(`${_K}${St(t)}`);return gr([r,t])}function SK(e,t){return hr(wK(e),t)}async function TK({message:e,privateKey:t}){return await Hi({hash:SK(e),privateKey:t,to:"hex"})}function EK(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:o,nonce:n,...i}=r,a=r.address;t.push([o?Kr(o):"0x",a,n?Kr(n):"0x",...Cf({},i)])}return t}function IK(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:o}=r,n=r.address;if(!Nt(n))throw new Wt({address:n});if(o<0)throw new If({chainId:o})}JS(e)}function PK(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new Oy;for(let r of t){let o=St(r),n=$r(Ka(r,0,1));if(o!==32)throw new t5({hash:r,size:o});if(n!==RS)throw new r5({hash:r,version:n})}}JS(e)}function JS(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:o,to:n}=e;if(t<=0)throw new If({chainId:t});if(n&&!Nt(n))throw new Wt({address:n});if(o&&o>Sf)throw new ii({maxFeePerGas:o});if(r&&o&&r>o)throw new qa({maxFeePerGas:o,maxPriorityFeePerGas:r})}function kK(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:o,maxFeePerGas:n,to:i}=e;if(t<=0)throw new If({chainId:t});if(i&&!Nt(i))throw new Wt({address:i});if(r||n)throw new q("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(o&&o>Sf)throw new ii({maxFeePerGas:o})}function AK(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:o,maxFeePerGas:n,to:i}=e;if(i&&!Nt(i))throw new Wt({address:i});if(typeof t<"u"&&t<=0)throw new If({chainId:t});if(r||n)throw new q("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(o&&o>Sf)throw new ii({maxFeePerGas:o})}function My(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:o,storageKeys:n}=e[r];for(let i=0;i<n.length;i++)if(n[i].length-2!==64)throw new xC({storageKey:n[i]});if(!Nt(o,{strict:!1}))throw new Wt({address:o});t.push([o,n])}return t}function RK(e,t){let r=OS(e);if(r==="eip1559")return Zxe(e,t);if(r==="eip2930")return Wxe(e,t);if(r==="eip4844")return Vxe(e,t);if(r==="eip7702")return Gxe(e,t);return Kxe(e,t)}function Gxe(e,t){let{authorizationList:r,chainId:o,gas:n,nonce:i,to:a,value:s,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:p}=e;IK(e);let m=My(d),h=EK(r);return Io(["0x04",Ja([ae(o),i?ae(i):"0x",u?ae(u):"0x",c?ae(c):"0x",n?ae(n):"0x",a??"0x",s?ae(s):"0x",p??"0x",m,h,...Cf(e,t)])])}function Vxe(e,t){let{chainId:r,gas:o,nonce:n,to:i,value:a,maxFeePerBlobGas:s,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:p}=e;PK(e);let{blobVersionedHashes:m,sidecars:h}=e;if(e.blobs&&(typeof m>"u"||typeof h>"u")){let w=typeof e.blobs[0]==="string"?e.blobs:e.blobs.map((k)=>Ht(k)),_=e.kzg,T=kf({blobs:w,kzg:_});if(typeof m>"u")m=AS({commitments:T});if(typeof h>"u"){let k=Af({blobs:w,commitments:T,kzg:_});h=$S({blobs:w,commitments:T,proofs:k})}}let y=My(d),x=[ae(r),n?ae(n):"0x",u?ae(u):"0x",c?ae(c):"0x",o?ae(o):"0x",i??"0x",a?ae(a):"0x",p??"0x",y,s?ae(s):"0x",m??[],...Cf(e,t)],S=[],v=[],E=[];if(h)for(let w=0;w<h.length;w++){let{blob:_,commitment:T,proof:k}=h[w];S.push(_),v.push(T),E.push(k)}return Io(["0x03",h?Ja([x,S,v,E]):Ja(x)])}function Zxe(e,t){let{chainId:r,gas:o,nonce:n,to:i,value:a,maxFeePerGas:s,maxPriorityFeePerGas:c,accessList:u,data:d}=e;JS(e);let p=My(u),m=[ae(r),n?ae(n):"0x",c?ae(c):"0x",s?ae(s):"0x",o?ae(o):"0x",i??"0x",a?ae(a):"0x",d??"0x",p,...Cf(e,t)];return Io(["0x02",Ja(m)])}function Wxe(e,t){let{chainId:r,gas:o,data:n,nonce:i,to:a,value:s,accessList:c,gasPrice:u}=e;kK(e);let d=My(c),p=[ae(r),i?ae(i):"0x",u?ae(u):"0x",o?ae(o):"0x",a??"0x",s?ae(s):"0x",n??"0x",d,...Cf(e,t)];return Io(["0x01",Ja(p)])}function Kxe(e,t){let{chainId:r=0,gas:o,data:n,nonce:i,to:a,value:s,gasPrice:c}=e;AK(e);let u=[i?ae(i):"0x",c?ae(c):"0x",o?ae(o):"0x",a??"0x",s?ae(s):"0x",n??"0x"];if(t){let d=(()=>{if(t.v>=35n){if((t.v-35n)/2n>0)return t.v;return 27n+(t.v===35n?0n:1n)}if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let h=27n+(t.v===27n?0n:1n);if(t.v!==h)throw new yC({v:t.v});return h})(),p=To(t.r),m=To(t.s);u=[...u,ae(d),p==="0x00"?"0x":p,m==="0x00"?"0x":m]}else if(r>0)u=[...u,ae(r),"0x","0x"];return Ja(u)}function Cf(e,t){let r=t??e,{v:o,yParity:n}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof o>"u"&&typeof n>"u")return[];let i=To(r.r),a=To(r.s);return[(()=>{if(typeof n==="number")return n?ae(1):"0x";if(o===0n)return"0x";if(o===1n)return ae(1);return o===27n?"0x":ae(1)})(),i==="0x00"?"0x":i,a==="0x00"?"0x":a]}async function $K(e){let{privateKey:t,transaction:r,serializer:o=RK}=e,n=(()=>{if(r.type==="eip4844")return{...r,sidecars:!1};return r})(),i=await Hi({hash:hr(await o(n)),privateKey:t});return await o(r,i)}async function OK(e){let{privateKey:t,...r}=e;return await Hi({hash:HW(r),privateKey:t,to:"hex"})}function P5(e,t={}){let{nonceManager:r}=t,o=Kr(Sn.getPublicKey(e.slice(2),!1)),n=TS(o);return{...bK({address:n,nonceManager:r,async sign({hash:a}){return Hi({hash:a,privateKey:e,to:"hex"})},async signAuthorization(a){return vK({...a,privateKey:e})},async signMessage({message:a}){return TK({message:a,privateKey:e})},async signTransaction(a,{serializer:s}={}){return $K({privateKey:e,transaction:a,serializer:s})},async signTypedData(a){return OK({...a,privateKey:e})}}),publicKey:o,source:"privateKey"}}function YS(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(o){return(n)=>{let i=typeof n==="function"?n(o):n,a={...o,...i};return Object.assign(a,{extend:r(a)})}}return Object.assign(t,{extend:r(t)})}var k5=YS({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 A5=YS({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 R5=null;var Jxe={privateKeyToAccount:P5,createWalletClient:_5,http:E5,createMonacoSDK:fC,sei:k5,seiTestnet:A5};function Yxe(e,t=Jxe){let r=e.network==="mainnet"?t.sei:t.seiTestnet,o;if(e.privateKey){let n=t.privateKeyToAccount(e.privateKey);o=t.createWalletClient({account:n,chain:r,transport:t.http(e.seiRpcUrl)})}return t.createMonacoSDK({walletClient:o,network:e.network,seiRpcUrl:e.seiRpcUrl})}function We(e){if(!R5){let t=e??su();R5=Yxe(t)}return R5}var Qxe=60,QS=null;function Xxe(){return Math.floor(Date.now()/1000)}function CK(e){return e-Qxe<=Xxe()}function eve(e){for(let t=e,r=0;t instanceof Error&&r<5;r++){if(t instanceof cr&&t.statusCode===401)return!0;t=t.cause}return!1}function $5(e){if(!QS)QS=e().finally(()=>{QS=null});return QS}async function zK(e,t){if(await e.login(t.clientId),t.delegatedOwnerUserId){try{let r=await e.loginAsDelegatedOwner(t.delegatedOwnerUserId);console.error(`Adopted delegated owner ${r.user.id} (session expires at ${new Date(r.expiresAt*1000).toISOString()})`)}catch(r){throw await e.logout().catch(()=>{}),r}return}console.error(`Authenticated as ${e.getAccountAddress()}`)}async function NK(e,t){try{await e.refreshAuth()}catch{await zK(e,t)}}async function X(e){let t=We(e),r=e??su(),o=t.getAuthState(),n=r.delegatedOwnerUserId!=null&&o?.user?.id!==r.delegatedOwnerUserId;if(!o||n)return await $5(()=>zK(t,r)),t;if(CK(o.expiresAt))await $5(()=>NK(t,r));return t}async function tve(e){let t=e??su();if(!t.privateKey)return!1;let r=We(e);return await $5(()=>NK(r,t)),!0}function MK(e,t){async function r(...o){let n=We(t).getAuthState(),i=n!==void 0&&!CK(n.expiresAt);try{return await e(...o)}catch(a){if(!eve(a))throw a;if(!(i&&We(t).getAuthState()!==n)){if(!await tve(t))throw a}return await e(...o)}}return r}function U(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function XS(e){return{content:[{type:"text",text:e}]}}function BK(e,t){if(t.network==="mainnet")return;e.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 o=await(await X()).faucet.getInfo();return U(o)})}function DK(e,t){if(t.network==="mainnet")return;e.registerTool("request_faucet",{description:"Request test funds from the faucet for all active trading pairs. Requires a Cloudflare Turnstile token (the faucet rejects requests without one). Only available on non-mainnet networks (development, staging, local).",inputSchema:f.object({turnstileToken:f.string().describe("Cloudflare Turnstile token proving the request came from a real client (required by the faucet).")})},async({turnstileToken:r})=>{let n=await(await X()).faucet.mint({turnstileToken:r});return U(n)})}function UK(e,t){DK(e,t),BK(e,t)}function LK(e){e.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:f.object({tradingPairId:f.string().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:t})=>{let o=await(await X()).fees.getMyFeeTier({tradingPairId:t});return U(o)})}function jK(e){e.registerTool("simulate_fees",{description:"Simulate the fees for an order before placing it. Returns Monaco protocol fees, application fees, and total amounts.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),price:f.string().describe("Price per unit as a decimal string"),quantity:f.string().describe("Quantity to trade as a decimal string")})},async({tradingPairId:t,side:r,price:o,quantity:n})=>{let a=await(await X()).fees.simulateFees({tradingPairId:t,side:r,price:o,quantity:n});return U(a)})}function FK(e){jK(e),LK(e)}function qK(e){e.registerTool("get_available_collateral",{description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",inputSchema:f.object({asset:f.string().optional().describe("Optional collateral asset symbol or ID to scope the query")})},async({asset:t})=>{let o=await(await X()).marginAccounts.getAvailableCollateral({asset:t});return U(o)})}function HK(e){e.registerTool("get_margin_accounts",{description:"List your margin accounts with optional filters (state, trading pair).",inputSchema:f.object({page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),state:f.string().optional().describe("Filter by margin account state"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID")})},async({page:t,pageSize:r,state:o,tradingPairId:n})=>{let a=await(await X()).marginAccounts.listMarginAccounts({page:t,pageSize:r,state:o,tradingPairId:n});return U(a)})}function GK(e){e.registerTool("get_parent_margin_account_movements",{description:"List collateral movements for your parent (cross) margin account.",inputSchema:f.object({movementType:f.string().optional().describe("Filter by movement type"),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({movementType:t,page:r,pageSize:o})=>{let i=await(await X()).marginAccounts.getParentMarginAccountMovements({movementType:t,page:r,pageSize:o});return U(i)})}function VK(e){e.registerTool("get_parent_margin_account_summary",{description:"Get your parent (cross) margin account summary.",inputSchema:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to scope the summary")})},async({tradingPairId:t})=>{let o=await(await X()).marginAccounts.getParentMarginAccountSummary({tradingPairId:t});return U(o)})}function ZK(e){e.registerTool("simulate_parent_margin_order_risk",{description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:f.enum(["LIMIT","MARKET"]).describe("Order type"),quantity:f.string().describe("Order quantity as a decimal string"),price:f.string().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:f.string().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce exposure")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]})},async({tradingPairId:t,side:r,orderType:o,quantity:n,price:i,leverage:a,reduceOnly:s})=>{let u=await(await X()).marginAccounts.simulateParentMarginOrderRisk({tradingPairId:t,side:r,orderType:o,quantity:n,price:i,leverage:a,reduceOnly:s});return U(u)})}function WK(e){e.registerTool("simulate_risk_bucket_order_risk",{description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:f.enum(["LIMIT","MARKET"]).describe("Order type"),quantity:f.string().describe("Order quantity as a decimal string"),price:f.string().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:f.string().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce exposure"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),strategyKey:f.string().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),selectedTradingPairIds:f.array(f.string()).optional().describe("Cross risk bucket trading pair UUIDs (CROSS only; must include tradingPairId)")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.marginMode!=="CROSS"||t.selectedTradingPairIds!==void 0&&t.selectedTradingPairIds.length>0,{message:"selectedTradingPairIds is required for CROSS risk buckets",path:["selectedTradingPairIds"]}).refine((t)=>t.marginMode!=="CROSS"||t.selectedTradingPairIds?.includes(t.tradingPairId),{message:"selectedTradingPairIds must include tradingPairId for CROSS risk buckets",path:["selectedTradingPairIds"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode==="CROSS"||t.selectedTradingPairIds===void 0,{message:"selectedTradingPairIds is only allowed for CROSS risk buckets",path:["selectedTradingPairIds"]})},async({tradingPairId:t,side:r,orderType:o,quantity:n,price:i,leverage:a,reduceOnly:s,marginMode:c,strategyKey:u,selectedTradingPairIds:d})=>{let p=await X(),m={tradingPairId:t,side:r,orderType:o,quantity:n,price:i,leverage:a,reduceOnly:s},h=c==="CROSS"?await p.marginAccounts.simulateRiskBucketOrderRisk({...m,marginMode:c,selectedTradingPairIds:d??[]}):await p.marginAccounts.simulateRiskBucketOrderRisk({...m,marginMode:c,strategyKey:u});return U(h)})}function KK(e){e.registerTool("transfer_collateral_from_parent_margin_account",{description:"Move collateral out of your parent (cross) margin account back to spot.",inputSchema:f.object({asset:f.string().describe("Collateral asset symbol or ID"),amount:f.string().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let n=await(await X()).marginAccounts.transferCollateralFromParentMarginAccount({asset:t,amount:r});return U(n)})}function JK(e){e.registerTool("transfer_collateral_to_parent_margin_account",{description:"Move collateral from spot into your parent (cross) margin account.",inputSchema:f.object({asset:f.string().describe("Collateral asset symbol or ID"),amount:f.string().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let n=await(await X()).marginAccounts.transferCollateralToParentMarginAccount({asset:t,amount:r});return U(n)})}function YK(e){e.registerTool("transfer_collateral_to_risk_bucket",{description:"Allocate collateral into an isolated or cross risk bucket.",inputSchema:f.object({asset:f.string().describe("Collateral asset symbol or ID"),amount:f.string().describe("Amount to transfer as a decimal string"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),tradingPairId:f.string().optional().describe("Trading pair UUID (required for ISOLATED; not allowed for CROSS)"),strategyKey:f.string().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),selectedTradingPairIds:f.array(f.string()).optional().describe("Trading pair UUIDs (required for CROSS; not allowed for ISOLATED)")}).refine((t)=>t.marginMode==="CROSS"||t.tradingPairId!==void 0,{message:"tradingPairId is required for ISOLATED risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.selectedTradingPairIds!==void 0&&t.selectedTradingPairIds.length>0,{message:"selectedTradingPairIds is required for CROSS risk buckets",path:["selectedTradingPairIds"]}).refine((t)=>t.marginMode!=="CROSS"||t.tradingPairId===void 0,{message:"tradingPairId is not allowed for CROSS risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode==="CROSS"||t.selectedTradingPairIds===void 0,{message:"selectedTradingPairIds is only allowed for CROSS risk buckets",path:["selectedTradingPairIds"]})},async({asset:t,amount:r,marginMode:o,tradingPairId:n,strategyKey:i,selectedTradingPairIds:a})=>{let s=await X(),c=o==="CROSS"?await s.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:o,selectedTradingPairIds:a??[]}):await s.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:o,tradingPairId:n??"",strategyKey:i});return U(c)})}function QK(e){HK(e),VK(e),qK(e),GK(e),ZK(e),WK(e),JK(e),KK(e),YK(e)}function XK(e){e.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),interval:f.enum(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:f.number().optional().describe("Start time as Unix timestamp (seconds)"),endTime:f.number().optional().describe("End time as Unix timestamp (seconds)"),limit:f.number().optional().describe("Max number of candlesticks to return")})},async({tradingPairId:t,interval:r,startTime:o,endTime:n,limit:i})=>{let s=await We().market.getCandlesticks(t,r,{startTime:o,endTime:n,limit:i});return U(s)})}function eJ(e){e.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await We().market.getMarketMetadata(t);return U(o)})}function tJ(e){e.registerTool("get_market_stats",{description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets."},async()=>{let r=await We().market.getMarketStats();return U(r)})}function rJ(e){e.registerTool("get_screener",{description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",inputSchema:f.object({page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),marketType:f.enum(["SPOT","MARGIN"]).optional().describe("Filter by market type"),isActive:f.boolean().optional().describe("Filter by active status"),category:f.string().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async({page:t,pageSize:r,marketType:o,isActive:n,category:i})=>{let s=await We().market.getScreener({page:t,pageSize:r,marketType:o,isActive:n,category:i});return U(s)})}function nJ(e){e.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:f.object({symbol:f.string().describe("Trading pair symbol (e.g. 'BTC/USDC')")})},async({symbol:t})=>{let o=await We().market.getTradingPairBySymbol(t);if(!o)return XS(`Trading pair '${t}' not found.`);return U(o)})}function oJ(e){e.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:f.object({page:f.number().optional().describe("Page number (starts from 1)"),pageSize:f.number().optional().describe("Number of items per page (max 100)"),marketType:f.enum(["SPOT","MARGIN"]).optional().describe("Filter by market type"),baseToken:f.string().optional().describe("Filter by base token"),quoteToken:f.string().optional().describe("Filter by quote token"),isActive:f.boolean().optional().describe("Filter by active status"),category:f.string().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async(t)=>{let o=await We().market.getPaginatedTradingPairs(t);return U(o)})}function iJ(e){oJ(e),nJ(e),XK(e),eJ(e),rJ(e),tJ(e)}function aJ(e){e.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),depth:f.number().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:f.enum(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:f.number().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:f.enum(["BASE","QUOTE"]).optional().describe("Quantity denomination: BASE or QUOTE")})},async({tradingPairId:t,depth:r,tradingMode:o,magnitude:n,denomination:i})=>{let s=await We().orderbook.getOrderbook(t,{depth:r,tradingMode:o,magnitude:n,denomination:i});return U(s)})}function sJ(e){aJ(e)}function cJ(e){e.registerTool("get_all_funding_history",{description:"List historical funding-rate records across all perpetual markets.",inputSchema:f.object({startTime:f.string().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:f.string().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),orderBy:f.enum(["ASC","DESC"]).optional().describe("Sort order by time")})},async({startTime:t,endTime:r,page:o,pageSize:n,orderBy:i})=>{let s=await We().market.listAllFundingHistory({startTime:t,endTime:r,page:o,pageSize:n,orderBy:i});return U(s)})}function uJ(e){e.registerTool("get_funding_history",{description:"List historical funding-rate records for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),startTime:f.string().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:f.string().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),orderBy:f.enum(["ASC","DESC"]).optional().describe("Sort order by time")})},async({tradingPairId:t,startTime:r,endTime:o,page:n,pageSize:i,orderBy:a})=>{let c=await We().market.listFundingHistory(t,{startTime:r,endTime:o,page:n,pageSize:i,orderBy:a});return U(c)})}function lJ(e){e.registerTool("get_funding_state",{description:"Get the current funding rate and next funding time for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await We().market.getFundingState(t);return U(o)})}function dJ(e){e.registerTool("get_index_price",{description:"Get the current index (oracle) price for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await We().market.getIndexPrice(t);return U(o)})}function pJ(e){e.registerTool("get_mark_price",{description:"Get the current mark price for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await We().market.getMarkPrice(t);return U(o)})}function fJ(e){e.registerTool("get_open_interest",{description:"Get the current open interest for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await We().market.getOpenInterest(t);return U(o)})}function mJ(e){e.registerTool("get_perp_market_config",{description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await We().market.getPerpMarketConfig(t);return U(o)})}function hJ(e){e.registerTool("get_perp_market_summary",{description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await We().market.getPerpMarketSummary(t);return U(o)})}function gJ(e){mJ(e),hJ(e),pJ(e),dJ(e),lJ(e),fJ(e),uJ(e),cJ(e)}function yJ(e){e.registerTool("check_trader_code_availability",{description:"Public advisory check of whether a custom PitPass TraderCode handle is available. Returns `available` and, when unavailable, a `reason` (one of taken, too_short, too_long, reserved, invalid_char, looks_like_address). Advisory only — the authoritative gate is the atomic claim in set_trader_code, so a positive result is not a reservation.",inputSchema:f.object({code:f.string().describe("The custom handle to check for availability.")})},async({code:t})=>{let o=await We().pitpass.checkTraderCodeAvailability(t);return U(o)})}function bJ(e){e.registerTool("clear_trader_code",{description:"Clear the authenticated caller's custom PitPass TraderCode handle, reverting to the wallet-derived default. The freed handle enters a cooldown before anyone else can claim it. Returns the caller's TraderCode identity after the revert.",inputSchema:f.object({})},async()=>{let r=await(await X()).pitpass.clearTraderCode();return U(r)})}function xJ(e){e.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:f.object({})},async()=>{let r=await(await X()).pitpass.getMyTraderCode();return U(r)})}function vJ(e){e.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:f.object({})},async()=>{let r=await(await X()).pitpass.getRewardsBalance();return U(r)})}function _J(e){e.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:f.object({code:f.string().describe("The TraderCode to look up — a wallet address (0x-prefixed) or the 'Monaco - <address>' display form.")})},async({code:t})=>{let o=await We().pitpass.getTraderCodeInfo(t);return U(o)})}function wJ(e){e.registerTool("set_trader_code",{description:"Claim or edit the authenticated caller's custom (vanity) PitPass TraderCode handle. Stored exactly as entered (case preserved); uniqueness is case-insensitive. Must start with a letter and be 5–20 characters of letters, digits, or underscores. The server is the authoritative gate: 409 if the handle is taken, 422 on validation failure, 429 when the per-hour edit limit is hit, 403 when the feature is disabled.",inputSchema:f.object({code:f.string().describe("The custom handle to claim or edit to — letter-first [A-Za-z0-9_], 5–20 characters. Case is preserved.")})},async({code:t})=>{let o=await(await X()).pitpass.setTraderCode(t);return U(o)})}function SJ(e){e.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:f.object({token:f.string().describe("Reward token contract address (0x-prefixed EVM address) to transfer."),amount:f.string().describe("Amount to transfer in RAW atomic units of the token (positive integer string).")})},async({token:t,amount:r})=>{let n=await(await X()).pitpass.transferRewards({token:t,amount:r});return U(n)})}function TJ(e){_J(e),yJ(e)}function EJ(e){xJ(e),vJ(e),SJ(e),wJ(e),bJ(e)}function IJ(e){e.registerTool("get_portfolio_assets",{description:"Get your per-asset portfolio allocation and balances over a period.",inputSchema:f.object({period:f.enum(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let o=await(await X()).portfolio.getAssets({period:t});return U(o)})}function PJ(e){e.registerTool("get_portfolio_margin",{description:"Get your portfolio margin overview (collateral, maintenance margin, health)."},async()=>{let r=await(await X()).portfolio.getMargin();return U(r)})}function kJ(e){e.registerTool("get_portfolio_performance",{description:"Get your portfolio performance time series over a period.",inputSchema:f.object({period:f.enum(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let o=await(await X()).portfolio.getPerformance({period:t});return U(o)})}function AJ(e){e.registerTool("get_portfolio_realized_pnl",{description:"Get your realized PnL breakdown over a period.",inputSchema:f.object({period:f.enum(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let o=await(await X()).portfolio.getRealizedPnl({period:t});return U(o)})}function RJ(e){e.registerTool("get_portfolio_summary",{description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",inputSchema:f.object({period:f.enum(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let o=await(await X()).portfolio.getSummary({period:t});return U(o)})}function $J(e){RJ(e),kJ(e),AJ(e),IJ(e),PJ(e)}function OJ(e){e.registerTool("close_position",{description:"Close a perpetual position with a market, limit, or IOC reduce order.",inputSchema:f.object({positionId:f.string().describe("Position UUID"),closeType:f.enum(["MARKET","LIMIT","IOC"]).describe("Close order type"),limitPrice:f.string().optional().describe("Limit price as a decimal string — required for LIMIT and IOC, not allowed for MARKET"),slippageToleranceBps:f.number().optional().describe("Slippage tolerance in basis points (MARKET/IOC)"),quantity:f.string().optional().describe("Quantity to close as a decimal string (defaults to full position)")}).refine((t)=>t.closeType==="MARKET"||t.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["limitPrice"]}).refine((t)=>t.closeType!=="MARKET"||t.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["limitPrice"]})},async({positionId:t,closeType:r,limitPrice:o,slippageToleranceBps:n,quantity:i})=>{let s=await(await X()).positions.closePosition(t,{closeType:r,limitPrice:o,slippageToleranceBps:n,quantity:i});return U(s)})}function CJ(e){e.registerTool("get_position",{description:"Get details for a specific perpetual position by ID.",inputSchema:f.object({positionId:f.string().describe("Position UUID")})},async({positionId:t})=>{let o=await(await X()).positions.getPosition(t);return U(o)})}function zJ(e){e.registerTool("get_position_history",{description:"List historical (closed/reduced) perpetual position records with optional filters.",inputSchema:f.object({positionId:f.string().optional().describe("Filter by position UUID"),marginAccountId:f.string().optional().describe("Filter by margin account UUID"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),reductionOnly:f.boolean().optional().describe("Only include reduction events")})},async({positionId:t,marginAccountId:r,tradingPairId:o,page:n,pageSize:i,reductionOnly:a})=>{let c=await(await X()).positions.listPositionHistory({positionId:t,marginAccountId:r,tradingPairId:o,page:n,pageSize:i,reductionOnly:a});return U(c)})}function NJ(e){e.registerTool("get_position_pnl_history",{description:"Get the PnL history time series for a perpetual position over an interval.",inputSchema:f.object({positionId:f.string().describe("Position UUID"),interval:f.enum(["1m","5m","15m","1h","4h","1d"]).describe("Sampling interval"),startTime:f.number().int().min(0).optional().describe("Start time as a Unix timestamp in milliseconds"),endTime:f.number().int().min(0).optional().describe("End time as a Unix timestamp in milliseconds")}).refine((t)=>t.startTime===void 0||t.endTime===void 0||t.startTime<t.endTime,{message:"startTime must be less than endTime",path:["startTime"]})},async({positionId:t,interval:r,startTime:o,endTime:n})=>{let a=await(await X()).positions.getPositionPnlHistory(t,{interval:r,startTime:o,endTime:n});return U(a)})}function MJ(e){e.registerTool("get_position_risk",{description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",inputSchema:f.object({positionId:f.string().describe("Position UUID")})},async({positionId:t})=>{let o=await(await X()).positions.getPositionRisk(t);return U(o)})}function BJ(e){e.registerTool("get_positions",{description:"List your perpetual positions with optional filters (margin account, trading pair, status).",inputSchema:f.object({marginAccountId:f.string().optional().describe("Filter by margin account UUID"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),status:f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"]).optional().describe("Filter by position status"),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({marginAccountId:t,tradingPairId:r,status:o,page:n,pageSize:i})=>{let s=await(await X()).positions.listPositions({marginAccountId:t,tradingPairId:r,status:o,page:n,pageSize:i});return U(s)})}function DJ(e){BJ(e),CJ(e),MJ(e),zJ(e),NJ(e),OJ(e)}function UJ(e){e.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:f.object({assetId:f.string().describe("The asset UUID")})},async({assetId:t})=>{let o=await(await X()).profile.getUserBalanceByAssetId(t);return U(o)})}function LJ(e){e.registerTool("get_balances",{description:"Get the authenticated user's token balances with pagination.",inputSchema:f.object({page:f.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:f.number().optional().describe("Number of items per page (default: 20, max: 100)")})},async({page:t,pageSize:r})=>{let n=await(await X()).profile.getUserBalances({page:t,pageSize:r});return U(n)})}function jJ(e){e.registerTool("get_funding_payments",{description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",inputSchema:f.object({tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),positionId:f.string().optional().describe("Filter by position UUID"),marginAccountId:f.string().optional().describe("Filter by margin account UUID"),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({tradingPairId:t,positionId:r,marginAccountId:o,page:n,pageSize:i})=>{let s=await(await X()).profile.listFundingPayments({tradingPairId:t,positionId:r,marginAccountId:o,page:n,pageSize:i});return U(s)})}function FJ(e){e.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history) with pagination.",inputSchema:f.object({page:f.number().int().min(1).optional().describe("Page number (starts from 1, default: 1)"),pageSize:f.number().int().min(1).max(100).optional().describe("Items per page (default: 20, max: 100)"),entryType:f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:f.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:f.string().uuid().optional().describe("Filter by asset ID (UUID)")})},async({page:t,pageSize:r,entryType:o,transactionType:n,assetId:i})=>{let s=await(await X()).profile.getPaginatedUserMovements({page:t,pageSize:r,entryType:o,transactionType:n,assetId:i});return U(s)})}function qJ(e){e.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 r=await(await X()).profile.getProfile();return U(r)})}function HJ(e){e.registerTool("get_user_trades",{description:"List your own trade fills with optional filters and cursor pagination.",inputSchema:f.object({tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),pageSize:f.number().optional().describe("Items per page"),pageToken:f.string().optional().describe("Cursor for the next page"),page:f.number().optional().describe("Page number (legacy offset mode; prefer pageToken)")})},async({tradingPairId:t,pageSize:r,pageToken:o,page:n})=>{let a=await(await X()).profile.getUserTrades({tradingPairId:t,pageSize:r,pageToken:o,page:n});return U(a)})}function GJ(e){qJ(e),LJ(e),UJ(e),FJ(e),HJ(e),jJ(e)}function VJ(e){e.registerTool("get_pulse",{description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags."},async()=>{let r=await We().pulse.getPulse();return U(r)})}function ZJ(e){VJ(e)}var rve="https://docs.0xmonaco.com/mcp",nve="SearchMonacoDocs",eT=null;async function WJ(e,t,r){let o=await fetch(rve,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...eT?{"Mcp-Session-Id":eT}:{}},body:JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t})});if(!o.ok)throw Error(`Mintlify MCP error: ${o.status}`);let n=o.headers.get("mcp-session-id");if(n)eT=n;let a=(await o.text()).split(`
169
- `).find((s)=>s.startsWith("data: "));if(!a)throw Error("No data in Mintlify MCP response");return JSON.parse(a.slice(6))}async function ove(){if(eT)return;await WJ("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:N_.version}},0)}async function ive(e){return await ove(),(await WJ("tools/call",{name:nve,arguments:{query:e}},1))?.result}function KJ(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:f.object({query:f.string().describe("The search query")})},async({query:t})=>{try{let r=await ive(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return U(r)}catch(r){return XS(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function JJ(e){KJ(e)}function YJ(e){e.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),page:f.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:f.number().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:t,page:r,pageSize:o})=>{let i=await We().trades.getTrades(t,{page:r,pageSize:o});return U(i)})}function QJ(e){YJ(e)}function XJ(e){e.registerTool("batch_cancel_all_orders",{description:"Cancel EVERY one of your open orders in one call. Destructive and unfiltered by default — with no tradingPairId it cancels your entire open-order book across all pairs; pass a tradingPairId to limit it to that pair.",inputSchema:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let o=await(await X()).trading.batchCancelAll(t);return U(o)})}function eY(e){e.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request. Non-atomic and best-effort: each order is cancelled independently, so a failed leg does not stop the others. Inspect the per-order results and reconcile (retry or re-check) any that did not cancel.",inputSchema:f.object({orderIds:f.array(f.string()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let o=await(await X()).trading.batchCancel(t);return U(o)})}function tY(e){e.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:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:f.number().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:t,slippageToleranceBps:r})=>{let n=await(await X()).positions.batchCloseAllPositions({tradingPairId:t,slippageToleranceBps:r});return U(n)})}function rY(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:f.object({orderId:f.string().describe("The order ID to cancel")})},async({orderId:t})=>{let o=await(await X()).trading.cancelOrder(t);return U(o)})}function nY(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:f.object({orderId:f.string().describe("The order ID to look up")})},async({orderId:t})=>{let o=await(await X()).trading.getOrder(t);return U(o)})}var ave=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:f.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:f.string().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:f.string().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:f.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:f.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((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:f.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),sve=f.object({applicationName:f.string().nullable().optional(),applicationTakerFee:f.string(),applicationTakerFeeBps:f.number(),buyOrderLockAmount:f.string().nullable().optional(),makerTotalReceipt:f.string(),monacoMakerRebate:f.string(),monacoMakerRebateBps:f.number(),monacoMakerRebateBpsExact:f.string(),monacoTakerFee:f.string(),monacoTakerFeeBps:f.number(),monacoTakerFeeBpsExact:f.string(),notional:f.string(),takerTotalPayment:f.string(),totalTakerFees:f.string(),maxQuantity:f.string().nullable(),maxQuantityRaw:f.string().nullable(),slippageToleranceBps:f.number().nullable()}),cve=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),oY=f.object({tierLevel:f.number().int(),minVolumeThreshold:f.string(),makerFeeBps:f.string(),takerFeeBps:f.string()}),uve=f.object({currentTierLevel:f.number().int(),weightedVolume14d:f.string(),spotVolume14d:f.string(),perpVolume14d:f.string(),volumeToNextTier:f.string().nullable().optional(),nextTierLevel:f.number().int().nullable().optional(),feeSchedule:f.array(oY)});var iY=f.object({token:f.string(),available:f.string()}),lve=f.object({balances:f.array(iY)}),dve=f.object({code:f.string(),createdAt:f.string(),customCode:f.string(),isCustom:f.boolean(),display:f.string()}),aY=f.enum(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),pve=f.object({available:f.boolean(),reason:f.preprocess((e)=>e===""||e===null?void 0:e,aY.optional())}),fve=f.object({code:f.string().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),mve=f.object({code:f.string()}),hve=f.object({token:f.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:f.string().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),gve=f.object({rewardsBalance:f.string(),tradingBalance:f.string()});var zf=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Nf=f.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),By=f.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),oT=f.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Dy=f.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),sY=f.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),O5=f.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Mf=f.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),yt=f.string().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),Re=f.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),cl=f.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),cY=f.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Uy=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),yve=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),tT=f.object({triggerPrice:yt,orderType:Mf,limitPrice:yt.optional(),quantity:yt.optional(),closePosition:f.boolean().optional(),timeInForce:O5.optional(),slippageToleranceBps:Uy.optional(),expiresAt:cl.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),rT=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,C5=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),x$r=f.object({tradingPairId:Re,side:Nf,quantity:yt,price:yt,options:f.object({tradingMode:By.optional(),useMasterBalance:f.boolean().optional(),expirationDate:cl.optional(),timeInForce:sY.optional(),marginAccountId:Re.optional(),marginMode:oT.optional(),riskBucketId:Re.optional(),riskBucketCollateral:yt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Dy.optional(),leverage:yt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional(),takeProfit:tT.optional(),stopLoss:tT.optional()}).optional()}).refine((e)=>C5(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!rT(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!rT(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),v$r=f.object({tradingPairId:Re,side:Nf,quantity:yt,options:f.object({tradingMode:By.optional(),slippageTolerance:cY,marginAccountId:Re.optional(),marginMode:oT.optional(),riskBucketId:Re.optional(),riskBucketCollateral:yt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Dy.optional(),leverage:yt.optional(),reduceOnly:f.boolean().optional(),takeProfit:tT.optional(),stopLoss:tT.optional()}).optional()}).refine((e)=>C5(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!rT(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!rT(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),_$r=f.object({orderId:Re,remainingQuantityTarget:yt.optional()}),w$r=f.object({orderId:Re,newOrder:f.object({price:yt.optional(),quantity:yt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()})}),S$r=f.object({status:f.union([f.enum(zf),f.array(f.enum(zf)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Re.optional(),tradingMode:By.optional(),marginAccountId:Re.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),T$r=f.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),E$r=f.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),bve=f.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),I$r=f.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),P$r=f.object({conditionalOrderId:Re}),k$r=f.object({marginAccountId:Re.optional(),tradingPairId:Re.optional(),state:bve.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),xve=f.enum(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),vve=f.union([f.number().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),f.string().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),A$r=f.object({tradingPairId:Re,side:Nf,quantity:yt,options:f.object({durationSeconds:vve.optional(),startTime:cl.optional(),endTime:cl.optional(),limitPrice:yt.optional(),slippageToleranceBps:yve.optional(),randomize:f.boolean().optional(),reduceOnly:f.boolean().optional(),tradingMode:By.optional(),marginAccountId:Re.optional(),riskBucketId:Re.optional(),marginMode:oT.optional(),leverage:yt.optional(),strategyKey:f.string().min(1).max(128).optional(),useMasterBalance:f.boolean().optional(),clientTwapId:f.string().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}),R$r=f.object({twapOrderId:Re}),$$r=f.object({state:xve.optional(),tradingPairId:Re.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),_ve=f.object({tradingPairId:Re,orderType:Mf,side:Nf,price:yt.optional(),quantity:yt,tradingMode:By.optional(),slippageTolerance:cY,useMasterBalance:f.boolean().optional(),expirationDate:cl.optional(),timeInForce:sY.optional(),marginAccountId:Re.optional(),marginMode:oT.optional(),riskBucketId:Re.optional(),riskBucketCollateral:yt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Dy.optional(),leverage:yt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>C5(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),nT=100,O$r=f.object({orders:f.array(_ve).min(1,"At least one order is required").max(nT,`At most ${nT} orders per batch request`)}),wve=f.object({orderId:Re,price:yt.optional(),quantity:yt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),C$r=f.object({orders:f.array(wve).min(1,"At least one order is required").max(nT,`At most ${nT} orders per batch request`)});var z5=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),B$r=z5.extend({state:f.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:Re.optional()}),D$r=f.object({marginAccountId:Re,tradingPairId:Re.optional()}),U$r=f.object({tradingPairId:Re.optional()}).optional(),L$r=f.object({asset:f.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),Sve=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:yt,tradingPairId:Re.optional(),strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:f.enum(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),iT=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:yt}),Tve=f.object({tradingPairId:Re,strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional()}),Eve=f.array(Re).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),uY=Tve.extend({marginMode:f.literal("ISOLATED").optional(),selectedTradingPairIds:f.never().optional()}),lY=f.object({marginMode:f.literal("CROSS"),selectedTradingPairIds:Eve,strategyKey:f.never().optional()}),Ive=lY.extend({tradingPairId:f.never().optional()}),j$r=f.object({marginAccountId:Re,request:Sve}),F$r=f.object({request:iT}),q$r=f.object({request:f.union([iT.merge(uY).strict(),iT.merge(Ive).strict()])}),H$r=f.object({request:iT}),G$r=z5.extend({marginAccountId:Re,movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}),V$r=z5.extend({movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),N5=f.object({tradingPairId:Re,side:Nf,positionSide:Dy.optional(),orderType:Mf,price:yt.optional(),quantity:yt,leverage:yt.optional(),reduceOnly:f.boolean().optional()}),M5=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:f.ZodIssueCode.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:f.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},dY=N5.strict().superRefine(M5),Pve=N5.merge(uY).strict().superRefine(M5),kve=N5.merge(lY).strict().superRefine(M5).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),Ave=f.union([Pve,kve]),Z$r=f.object({marginAccountId:Re,request:dY}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),W$r=f.object({request:dY}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),K$r=f.object({request:Ave}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var pY=f.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"'}),Rve=31536000000,$ve=946684800000,aT=f.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min($ve,{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((e)=>e<=Date.now()+Rve,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),X$r=f.object({tradingPairId:Re,interval:pY,startTime:aT,endTime:aT}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),e2r=f.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")'}),Ove=f.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),t2r=f.object({tradingPairId:Re,interval:pY,startTime:aT.optional(),endTime:aT.optional(),limit:Ove,priceType:f.enum(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var r2r=f.object({tradingPairId:Re}),n2r=f.object({query:f.string().min(1,"Search query cannot be empty").optional(),pageSize:f.number().int().min(1).max(100).optional(),page:f.number().int().min(1).optional()}),o2r=f.object({tradingPairId:Re});var mY=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Cve=f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),zve=f.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),B5=f.object({positionId:Re}),c2r=mY.extend({marginAccountId:Re.optional(),tradingPairId:Re.optional(),status:Cve.optional()});var u2r=B5.extend({request:f.object({closeType:zve,limitPrice:yt.optional(),slippageToleranceBps:Uy.optional(),quantity:yt.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),l2r=f.object({tradingPairId:Re.optional(),slippageToleranceBps:Uy.optional()});var fY=f.object({triggerPrice:yt,orderType:Mf,limitPrice:yt.optional(),quantity:yt.optional(),closePosition:f.boolean().optional(),timeInForce:O5.optional(),slippageToleranceBps:Uy.optional(),expiresAt:cl.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),d2r=B5.extend({request:f.object({takeProfit:fY.optional(),stopLoss:fY.optional(),oco:f.boolean().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),p2r=mY.extend({positionId:Re.optional(),marginAccountId:Re.optional(),tradingPairId:Re.optional(),reductionOnly:f.boolean().optional()}),Nve=f.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),f2r=B5.extend({params:f.object({interval:Nve,startTime:f.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:f.number().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var Mve=f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),Bve=f.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),y2r=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.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:Mve.optional(),transactionType:Bve.optional(),assetId:Re.optional()}),b2r=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:Re.optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),x2r=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.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:Re.optional(),positionId:Re.optional(),marginAccountId:Re.optional()});var S2r=f.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),D5=f.union([f.string().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),f.bigint().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),T2r=f.object({assetId:Re,amount:D5,autoWait:f.boolean().optional()}),E2r=f.object({assetId:Re,amount:D5,autoWait:f.boolean().optional(),target:f.enum(["spot","margin"]).optional(),options:f.object({asErc20:f.boolean().optional()}).optional()}),I2r=f.object({assetId:Re,amount:D5,destination:f.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:f.boolean().optional(),source:f.enum(["spot","margin"]).optional()}),P2r=f.object({assetId:Re});function hY(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit both page and pageToken for the newest orders; pass the previous response's nextPageToken to fetch the next page. A response with zero orders and an empty nextPageToken means the walk is exhausted. Cursor responses have no exact totals (total/totalPages are 0).",inputSchema:f.object({status:f.enum(zf).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),page:f.number().optional().describe("Deprecated: page number for legacy offset pagination, which only sees recent history. Use pageToken instead."),pageSize:f.number().optional().describe("Orders per page (default: 10; max 100 in legacy page mode, up to 1000 with pageToken)"),pageToken:f.string().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it (and page) to start from the newest orders.")})},async({status:t,tradingPairId:r,page:o,pageSize:n,pageToken:i})=>{let s=await(await X()).trading.getPaginatedOrders({status:t,tradingPairId:r,page:o,pageSize:n,pageToken:i});return U(s)})}function gY(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. Limit orders execute only when the market reaches the specified price. "+"Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — the order may already be live. First reconcile with get_orders (match the order's pair/side/price/quantity among your recent orders, including filled ones) or get_order, then resubmit only if it did not land.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),quantity:f.string().describe("Order quantity as a decimal string"),price:f.string().describe("Limit price as a decimal string"),tradingMode:f.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:f.enum(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:f.string().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:f.string().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:f.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:f.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:f.string().optional().describe("Optional client strategy key"),positionSide:f.enum(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:f.string().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce existing exposure"),postOnly:f.boolean().optional().describe("Maker-only: rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if this order would cross the book. GTC time in force only; rejected with IOC/FOK."),clientOrderId:f.string().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: not de-duplicated and not unique — reconcile a lost response via get_orders before resubmitting.")})},async({tradingPairId:t,side:r,quantity:o,price:n,tradingMode:i,timeInForce:a,expirationDate:s,marginAccountId:c,marginMode:u,riskBucketId:d,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:S,clientOrderId:v})=>{let w=await(await X()).trading.placeLimitOrder(t,r,o,n,{tradingMode:i,timeInForce:a,expirationDate:s,marginAccountId:c,marginMode:u,riskBucketId:d,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:S,clientOrderId:v});return U(w)})}function yY(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. It executes immediately against resting liquidity, but only inside a mandatory 1,000 bps (10%) server-side protective price band anchored to the mark/last-trade reference price. Fills stop at the edge of the band, so a market order may partially fill and cancel the remainder, be rejected when no liquidity sits inside the band, or be rejected when the market has no trustworthy price anchor. Optional slippageTolerance is merged tighter-wins with this band: it can only TIGHTEN execution, never widen past the mandatory band; omitting it applies the full 1,000 bps band. Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — the order may already be live. First reconcile with get_orders (match the order's pair/side/quantity among your recent orders, including filled ones) or get_order, then resubmit only if it did not land.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),quantity:f.string().describe("Order quantity as a decimal string"),tradingMode:f.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:f.number().optional().describe("Tightens the mandatory 1,000 bps band, as a decimal (e.g. 0.01 for 1%; 0 for best price only). Can only tighten, never widen; omit to apply the full band."),marginAccountId:f.string().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:f.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:f.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:f.string().optional().describe("Optional client strategy key"),positionSide:f.enum(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:f.string().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce existing exposure"),clientOrderId:f.string().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: not de-duplicated and not unique — reconcile a lost response via get_orders before resubmitting.")})},async({tradingPairId:t,side:r,quantity:o,tradingMode:n,slippageTolerance:i,marginAccountId:a,marginMode:s,riskBucketId:c,riskBucketCollateral:u,strategyKey:d,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y})=>{let S=await(await X()).trading.placeMarketOrder(t,r,o,{tradingMode:n,slippageTolerance:i,marginAccountId:a,marginMode:s,riskBucketId:c,riskBucketCollateral:u,strategyKey:d,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y});return U(S)})}function bY(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — read the order back with get_order and compare its price/quantity before replacing again.",inputSchema:f.object({orderId:f.string().describe("The order ID to replace"),price:f.string().optional().describe("New price as a decimal string"),quantity:f.string().optional().describe("New quantity as a decimal string"),postOnly:f.boolean().optional().describe("Re-states maker-only intent for the replacement (nothing is inherited from the original order): rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if it would cross the book."),clientOrderId:f.string().optional().describe("Client-assigned correlation handle for the replacement order, echoed back on order reads and order WebSocket events. Nothing is inherited from the original order — re-state it here to keep the handle across a requote. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: not de-duplicated and not unique.")})},async({orderId:t,price:r,quantity:o,postOnly:n,clientOrderId:i})=>{let s=await(await X()).trading.replaceOrder(t,{price:r,quantity:o,postOnly:n,clientOrderId:i});return U(s)})}function xY(e){gY(e),yY(e),rY(e),eY(e),XJ(e),tY(e),bY(e),hY(e),nY(e)}function vY(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let o=await(await X()).vault.getAllowance(t);return U({assetId:t,allowance:o.toString()})})}function _Y(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to approve"),amount:f.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:t,amount:r})=>{let n=await(await X()).vault.approve(t,BigInt(r));return U({hash:n.hash,status:n.status})})}function wY(e){e.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:f.object({assetId:f.string().describe("The asset UUID to deposit"),amount:f.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:f.enum(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:o})=>{let i=await(await X()).vault.deposit(t,BigInt(r),void 0,o);return U({hash:i.hash,status:i.status})})}function SY(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:f.object({page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({page:t,pageSize:r})=>{let n=await(await X()).withdrawals.listPendingWithdrawals({page:t,pageSize:r});return U(n)})}function TY(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to check"),amount:f.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let n=await(await X()).vault.needsApproval(t,BigInt(r));return U({assetId:t,amount:r,needs_approval:n})})}function EY(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to withdraw"),amount:f.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:t,amount:r})=>{let n=await(await X()).vault.withdraw(t,BigInt(r));return U({withdrawalIndex:n.withdrawalIndex,status:n.status,hash:n.hash})})}function IY(e){_Y(e),wY(e),EY(e),vY(e),TY(e),SY(e)}function Dve(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let o=MK(r);return[...e.slice(0,t),o]}function Uve(e,t){let[r,...o]=t;if(!r||typeof r!=="object")return t;let n=q3(e);if(!n)return t;let i=r.annotations;return[{...r,annotations:{...n,...i}},...o]}function PY(e,t,r){return new Proxy(e,{get(o,n,i){if(n==="registerTool")return(s,...c)=>{if(!W3(s,t))return;let u=Uve(s,c);if(r&&Z3(s))u=Dve(u);return o.registerTool(s,...u)};let a=Reflect.get(o,n,i);return typeof a==="function"?a.bind(o):a}})}function kY(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},o=PY(e,r,!1);if(JJ(o),iJ(o),gJ(o),sJ(o),QJ(o),TJ(o),ZJ(o),t.authenticated){let n=PY(e,r,!0);xY(n),DJ(n),GJ(n),$J(n),QK(n),FK(n),IY(n),UK(n,{network:t.network}),EJ(n)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=Lve;if(!globalThis.fetch)globalThis.fetch=wb,globalThis.Headers=an,globalThis.Request=ea,globalThis.Response=Cr;if(!globalThis.WebSocket)globalThis.WebSocket=cE.default;async function jve(){let e=su(),t=e.privateKey!==null,r=new pR({name:"monaco-mcp-server",version:N_.version});kY(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let o=new mR;await r.connect(o),console.error(t?`Monaco MCP server running on stdio (network=${e.network}, capability=${e.capability}). Fund-movement and privilege tools require MONACO_CAPABILITY=full or an explicit MONACO_TOOL_ALLOWLIST entry.`:"Monaco MCP server running on stdio (public read-only mode — set MONACO_PRIVATE_KEY, MONACO_CLIENT_ID and MONACO_NETWORK to enable authenticated tools).")}jve().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});
169
+ `).find((s)=>s.startsWith("data: "));if(!a)throw Error("No data in Mintlify MCP response");return JSON.parse(a.slice(6))}async function ove(){if(eT)return;await WJ("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:N_.version}},0)}async function ive(e){return await ove(),(await WJ("tools/call",{name:nve,arguments:{query:e}},1))?.result}function KJ(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:f.object({query:f.string().describe("The search query")})},async({query:t})=>{try{let r=await ive(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return U(r)}catch(r){return XS(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function JJ(e){KJ(e)}function YJ(e){e.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),page:f.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:f.number().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:t,page:r,pageSize:o})=>{let i=await We().trades.getTrades(t,{page:r,pageSize:o});return U(i)})}function QJ(e){YJ(e)}function XJ(e){e.registerTool("batch_cancel_all_orders",{description:"Cancel EVERY one of your open orders in one call. Destructive and unfiltered by default — with no tradingPairId it cancels your entire open-order book across all pairs; pass a tradingPairId to limit it to that pair.",inputSchema:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let o=await(await X()).trading.batchCancelAll(t);return U(o)})}function eY(e){e.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request. Non-atomic and best-effort: each order is cancelled independently, so a failed leg does not stop the others. Inspect the per-order results and reconcile (retry or re-check) any that did not cancel.",inputSchema:f.object({orderIds:f.array(f.string()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let o=await(await X()).trading.batchCancel(t);return U(o)})}function tY(e){e.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:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:f.number().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:t,slippageToleranceBps:r})=>{let n=await(await X()).positions.batchCloseAllPositions({tradingPairId:t,slippageToleranceBps:r});return U(n)})}function rY(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:f.object({orderId:f.string().describe("The order ID to cancel")})},async({orderId:t})=>{let o=await(await X()).trading.cancelOrder(t);return U(o)})}function nY(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:f.object({orderId:f.string().describe("The order ID to look up")})},async({orderId:t})=>{let o=await(await X()).trading.getOrder(t);return U(o)})}var ave=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:f.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:f.string().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:f.string().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:f.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:f.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((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:f.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),sve=f.object({applicationName:f.string().nullable().optional(),applicationTakerFee:f.string(),applicationTakerFeeBps:f.number(),buyOrderLockAmount:f.string().nullable().optional(),makerTotalReceipt:f.string(),monacoMakerRebate:f.string(),monacoMakerRebateBps:f.number(),monacoMakerRebateBpsExact:f.string(),monacoTakerFee:f.string(),monacoTakerFeeBps:f.number(),monacoTakerFeeBpsExact:f.string(),notional:f.string(),takerTotalPayment:f.string(),totalTakerFees:f.string(),maxQuantity:f.string().nullable(),maxQuantityRaw:f.string().nullable(),slippageToleranceBps:f.number().nullable()}),cve=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),oY=f.object({tierLevel:f.number().int(),minVolumeThreshold:f.string(),makerFeeBps:f.string(),takerFeeBps:f.string()}),uve=f.object({currentTierLevel:f.number().int(),weightedVolume14d:f.string(),spotVolume14d:f.string(),perpVolume14d:f.string(),volumeToNextTier:f.string().nullable().optional(),nextTierLevel:f.number().int().nullable().optional(),feeSchedule:f.array(oY)});var iY=f.object({token:f.string(),available:f.string()}),lve=f.object({balances:f.array(iY)}),dve=f.object({code:f.string(),createdAt:f.string(),customCode:f.string(),isCustom:f.boolean(),display:f.string()}),aY=f.enum(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),pve=f.object({available:f.boolean(),reason:f.preprocess((e)=>e===""||e===null?void 0:e,aY.optional())}),fve=f.object({code:f.string().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),mve=f.object({code:f.string()}),hve=f.object({token:f.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:f.string().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),gve=f.object({rewardsBalance:f.string(),tradingBalance:f.string()});var zf=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Nf=f.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),By=f.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),oT=f.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Dy=f.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),sY=f.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),O5=f.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Mf=f.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),yt=f.string().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),Re=f.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),cl=f.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),cY=f.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Uy=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),yve=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),tT=f.object({triggerPrice:yt,orderType:Mf,limitPrice:yt.optional(),quantity:yt.optional(),closePosition:f.boolean().optional(),timeInForce:O5.optional(),slippageToleranceBps:Uy.optional(),expiresAt:cl.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),rT=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,C5=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),v$r=f.object({tradingPairId:Re,side:Nf,quantity:yt,price:yt,options:f.object({tradingMode:By.optional(),useMasterBalance:f.boolean().optional(),expirationDate:cl.optional(),timeInForce:sY.optional(),marginAccountId:Re.optional(),marginMode:oT.optional(),riskBucketId:Re.optional(),riskBucketCollateral:yt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Dy.optional(),leverage:yt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional(),takeProfit:tT.optional(),stopLoss:tT.optional()}).optional()}).refine((e)=>C5(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!rT(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!rT(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),_$r=f.object({tradingPairId:Re,side:Nf,quantity:yt,options:f.object({tradingMode:By.optional(),slippageTolerance:cY,marginAccountId:Re.optional(),marginMode:oT.optional(),riskBucketId:Re.optional(),riskBucketCollateral:yt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Dy.optional(),leverage:yt.optional(),reduceOnly:f.boolean().optional(),takeProfit:tT.optional(),stopLoss:tT.optional()}).optional()}).refine((e)=>C5(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!rT(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!rT(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),w$r=f.object({orderId:Re,remainingQuantityTarget:yt.optional()}),S$r=f.object({orderId:Re,newOrder:f.object({price:yt.optional(),quantity:yt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()})}),T$r=f.object({status:f.union([f.enum(zf),f.array(f.enum(zf)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Re.optional(),tradingMode:By.optional(),marginAccountId:Re.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),E$r=f.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),I$r=f.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),bve=f.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),P$r=f.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),k$r=f.object({conditionalOrderId:Re}),A$r=f.object({marginAccountId:Re.optional(),tradingPairId:Re.optional(),state:bve.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),xve=f.enum(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),vve=f.union([f.number().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),f.string().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),R$r=f.object({tradingPairId:Re,side:Nf,quantity:yt,options:f.object({durationSeconds:vve.optional(),startTime:cl.optional(),endTime:cl.optional(),limitPrice:yt.optional(),slippageToleranceBps:yve.optional(),randomize:f.boolean().optional(),reduceOnly:f.boolean().optional(),tradingMode:By.optional(),marginAccountId:Re.optional(),riskBucketId:Re.optional(),marginMode:oT.optional(),leverage:yt.optional(),strategyKey:f.string().min(1).max(128).optional(),useMasterBalance:f.boolean().optional(),clientTwapId:f.string().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}),$$r=f.object({twapOrderId:Re}),O$r=f.object({state:xve.optional(),tradingPairId:Re.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),_ve=f.object({tradingPairId:Re,orderType:Mf,side:Nf,price:yt.optional(),quantity:yt,tradingMode:By.optional(),slippageTolerance:cY,useMasterBalance:f.boolean().optional(),expirationDate:cl.optional(),timeInForce:sY.optional(),marginAccountId:Re.optional(),marginMode:oT.optional(),riskBucketId:Re.optional(),riskBucketCollateral:yt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Dy.optional(),leverage:yt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>C5(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),nT=100,C$r=f.object({orders:f.array(_ve).min(1,"At least one order is required").max(nT,`At most ${nT} orders per batch request`)}),wve=f.object({orderId:Re,price:yt.optional(),quantity:yt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),z$r=f.object({orders:f.array(wve).min(1,"At least one order is required").max(nT,`At most ${nT} orders per batch request`)});var z5=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),D$r=z5.extend({state:f.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:Re.optional()}),U$r=f.object({marginAccountId:Re,tradingPairId:Re.optional()}),L$r=f.object({tradingPairId:Re.optional()}).optional(),j$r=f.object({asset:f.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),Sve=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:yt,tradingPairId:Re.optional(),strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:f.enum(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),iT=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:yt}),Tve=f.object({tradingPairId:Re,strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional()}),Eve=f.array(Re).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),uY=Tve.extend({marginMode:f.literal("ISOLATED").optional(),selectedTradingPairIds:f.never().optional()}),lY=f.object({marginMode:f.literal("CROSS"),selectedTradingPairIds:Eve,strategyKey:f.never().optional()}),Ive=lY.extend({tradingPairId:f.never().optional()}),F$r=f.object({marginAccountId:Re,request:Sve}),q$r=f.object({request:iT}),H$r=f.object({request:f.union([iT.merge(uY).strict(),iT.merge(Ive).strict()])}),G$r=f.object({request:iT}),V$r=z5.extend({marginAccountId:Re,movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}),Z$r=z5.extend({movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),N5=f.object({tradingPairId:Re,side:Nf,positionSide:Dy.optional(),orderType:Mf,price:yt.optional(),quantity:yt,leverage:yt.optional(),reduceOnly:f.boolean().optional()}),M5=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:f.ZodIssueCode.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:f.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},dY=N5.strict().superRefine(M5),Pve=N5.merge(uY).strict().superRefine(M5),kve=N5.merge(lY).strict().superRefine(M5).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),Ave=f.union([Pve,kve]),W$r=f.object({marginAccountId:Re,request:dY}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),K$r=f.object({request:dY}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),J$r=f.object({request:Ave}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var pY=f.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"'}),Rve=31536000000,$ve=946684800000,aT=f.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min($ve,{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((e)=>e<=Date.now()+Rve,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),e2r=f.object({tradingPairId:Re,interval:pY,startTime:aT,endTime:aT}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),t2r=f.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")'}),Ove=f.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),r2r=f.object({tradingPairId:Re,interval:pY,startTime:aT.optional(),endTime:aT.optional(),limit:Ove,priceType:f.enum(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var n2r=f.object({tradingPairId:Re}),o2r=f.object({query:f.string().min(1,"Search query cannot be empty").optional(),pageSize:f.number().int().min(1).max(100).optional(),page:f.number().int().min(1).optional()}),i2r=f.object({tradingPairId:Re});var mY=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Cve=f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),zve=f.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),B5=f.object({positionId:Re}),u2r=mY.extend({marginAccountId:Re.optional(),tradingPairId:Re.optional(),status:Cve.optional()});var l2r=B5.extend({request:f.object({closeType:zve,limitPrice:yt.optional(),slippageToleranceBps:Uy.optional(),quantity:yt.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),d2r=f.object({tradingPairId:Re.optional(),slippageToleranceBps:Uy.optional()});var fY=f.object({triggerPrice:yt,orderType:Mf,limitPrice:yt.optional(),quantity:yt.optional(),closePosition:f.boolean().optional(),timeInForce:O5.optional(),slippageToleranceBps:Uy.optional(),expiresAt:cl.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),p2r=B5.extend({request:f.object({takeProfit:fY.optional(),stopLoss:fY.optional(),oco:f.boolean().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),f2r=mY.extend({positionId:Re.optional(),marginAccountId:Re.optional(),tradingPairId:Re.optional(),reductionOnly:f.boolean().optional()}),Nve=f.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),m2r=B5.extend({params:f.object({interval:Nve,startTime:f.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:f.number().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var Mve=f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),Bve=f.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),b2r=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.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:Mve.optional(),transactionType:Bve.optional(),assetId:Re.optional()}),x2r=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:Re.optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),v2r=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.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:Re.optional(),positionId:Re.optional(),marginAccountId:Re.optional()});var T2r=f.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),D5=f.union([f.string().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),f.bigint().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),E2r=f.object({assetId:Re,amount:D5,autoWait:f.boolean().optional()}),I2r=f.object({assetId:Re,amount:D5,autoWait:f.boolean().optional(),target:f.enum(["spot","margin"]).optional(),options:f.object({asErc20:f.boolean().optional()}).optional()}),P2r=f.object({assetId:Re,amount:D5,destination:f.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:f.boolean().optional(),source:f.enum(["spot","margin"]).optional()}),k2r=f.object({assetId:Re});function hY(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit both page and pageToken for the newest orders; pass the previous response's nextPageToken to fetch the next page. A response with zero orders and an empty nextPageToken means the walk is exhausted. Cursor responses have no exact totals (total/totalPages are 0).",inputSchema:f.object({status:f.enum(zf).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),page:f.number().optional().describe("Deprecated: page number for legacy offset pagination, which only sees recent history. Use pageToken instead."),pageSize:f.number().optional().describe("Orders per page (default: 10; max 100 in legacy page mode, up to 1000 with pageToken)"),pageToken:f.string().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it (and page) to start from the newest orders.")})},async({status:t,tradingPairId:r,page:o,pageSize:n,pageToken:i})=>{let s=await(await X()).trading.getPaginatedOrders({status:t,tradingPairId:r,page:o,pageSize:n,pageToken:i});return U(s)})}function gY(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. Limit orders execute only when the market reaches the specified price. "+"Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — the order may already be live. First reconcile with get_orders (match the order's pair/side/price/quantity among your recent orders, including filled ones) or get_order, then resubmit only if it did not land.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),quantity:f.string().describe("Order quantity as a decimal string"),price:f.string().describe("Limit price as a decimal string"),tradingMode:f.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:f.enum(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:f.string().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:f.string().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:f.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:f.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:f.string().optional().describe("Optional client strategy key"),positionSide:f.enum(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:f.string().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce existing exposure"),postOnly:f.boolean().optional().describe("Maker-only: rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if this order would cross the book. GTC time in force only; rejected with IOC/FOK."),clientOrderId:f.string().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: not de-duplicated and not unique — reconcile a lost response via get_orders before resubmitting.")})},async({tradingPairId:t,side:r,quantity:o,price:n,tradingMode:i,timeInForce:a,expirationDate:s,marginAccountId:c,marginMode:u,riskBucketId:d,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:S,clientOrderId:v})=>{let w=await(await X()).trading.placeLimitOrder(t,r,o,n,{tradingMode:i,timeInForce:a,expirationDate:s,marginAccountId:c,marginMode:u,riskBucketId:d,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:S,clientOrderId:v});return U(w)})}function yY(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. It executes immediately against resting liquidity, but only inside a mandatory 1,000 bps (10%) server-side protective price band anchored to the mark/last-trade reference price. Fills stop at the edge of the band, so a market order may partially fill and cancel the remainder, be rejected when no liquidity sits inside the band, or be rejected when the market has no trustworthy price anchor. Optional slippageTolerance is merged tighter-wins with this band: it can only TIGHTEN execution, never widen past the mandatory band; omitting it applies the full 1,000 bps band. Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — the order may already be live. First reconcile with get_orders (match the order's pair/side/quantity among your recent orders, including filled ones) or get_order, then resubmit only if it did not land.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),quantity:f.string().describe("Order quantity as a decimal string"),tradingMode:f.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:f.number().optional().describe("Tightens the mandatory 1,000 bps band, as a decimal (e.g. 0.01 for 1%; 0 for best price only). Can only tighten, never widen; omit to apply the full band."),marginAccountId:f.string().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:f.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:f.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:f.string().optional().describe("Optional client strategy key"),positionSide:f.enum(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:f.string().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce existing exposure"),clientOrderId:f.string().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: not de-duplicated and not unique — reconcile a lost response via get_orders before resubmitting.")})},async({tradingPairId:t,side:r,quantity:o,tradingMode:n,slippageTolerance:i,marginAccountId:a,marginMode:s,riskBucketId:c,riskBucketCollateral:u,strategyKey:d,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y})=>{let S=await(await X()).trading.placeMarketOrder(t,r,o,{tradingMode:n,slippageTolerance:i,marginAccountId:a,marginMode:s,riskBucketId:c,riskBucketCollateral:u,strategyKey:d,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y});return U(S)})}function bY(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — read the order back with get_order and compare its price/quantity before replacing again.",inputSchema:f.object({orderId:f.string().describe("The order ID to replace"),price:f.string().optional().describe("New price as a decimal string"),quantity:f.string().optional().describe("New quantity as a decimal string"),postOnly:f.boolean().optional().describe("Re-states maker-only intent for the replacement (nothing is inherited from the original order): rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if it would cross the book."),clientOrderId:f.string().optional().describe("Client-assigned correlation handle for the replacement order, echoed back on order reads and order WebSocket events. Nothing is inherited from the original order — re-state it here to keep the handle across a requote. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: not de-duplicated and not unique.")})},async({orderId:t,price:r,quantity:o,postOnly:n,clientOrderId:i})=>{let s=await(await X()).trading.replaceOrder(t,{price:r,quantity:o,postOnly:n,clientOrderId:i});return U(s)})}function xY(e){gY(e),yY(e),rY(e),eY(e),XJ(e),tY(e),bY(e),hY(e),nY(e)}function vY(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let o=await(await X()).vault.getAllowance(t);return U({assetId:t,allowance:o.toString()})})}function _Y(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to approve"),amount:f.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:t,amount:r})=>{let n=await(await X()).vault.approve(t,BigInt(r));return U({hash:n.hash,status:n.status})})}function wY(e){e.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:f.object({assetId:f.string().describe("The asset UUID to deposit"),amount:f.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:f.enum(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:o})=>{let i=await(await X()).vault.deposit(t,BigInt(r),void 0,o);return U({hash:i.hash,status:i.status})})}function SY(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:f.object({page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({page:t,pageSize:r})=>{let n=await(await X()).withdrawals.listPendingWithdrawals({page:t,pageSize:r});return U(n)})}function TY(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to check"),amount:f.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let n=await(await X()).vault.needsApproval(t,BigInt(r));return U({assetId:t,amount:r,needs_approval:n})})}function EY(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to withdraw"),amount:f.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:t,amount:r})=>{let n=await(await X()).vault.withdraw(t,BigInt(r));return U({withdrawalIndex:n.withdrawalIndex,status:n.status,hash:n.hash})})}function IY(e){_Y(e),wY(e),EY(e),vY(e),TY(e),SY(e)}function Dve(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let o=MK(r);return[...e.slice(0,t),o]}function Uve(e,t){let[r,...o]=t;if(!r||typeof r!=="object")return t;let n=q3(e);if(!n)return t;let i=r.annotations;return[{...r,annotations:{...n,...i}},...o]}function PY(e,t,r){return new Proxy(e,{get(o,n,i){if(n==="registerTool")return(s,...c)=>{if(!W3(s,t))return;let u=Uve(s,c);if(r&&Z3(s))u=Dve(u);return o.registerTool(s,...u)};let a=Reflect.get(o,n,i);return typeof a==="function"?a.bind(o):a}})}function kY(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},o=PY(e,r,!1);if(JJ(o),iJ(o),gJ(o),sJ(o),QJ(o),TJ(o),ZJ(o),t.authenticated){let n=PY(e,r,!0);xY(n),DJ(n),GJ(n),$J(n),QK(n),FK(n),IY(n),UK(n,{network:t.network}),EJ(n)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=Lve;if(!globalThis.fetch)globalThis.fetch=wb,globalThis.Headers=an,globalThis.Request=ea,globalThis.Response=Cr;if(!globalThis.WebSocket)globalThis.WebSocket=cE.default;async function jve(){let e=su(),t=e.privateKey!==null,r=new pR({name:"monaco-mcp-server",version:N_.version});kY(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let o=new mR;await r.connect(o),console.error(t?`Monaco MCP server running on stdio (network=${e.network}, capability=${e.capability}). Fund-movement and privilege tools require MONACO_CAPABILITY=full or an explicit MONACO_TOOL_ALLOWLIST entry.`:"Monaco MCP server running on stdio (public read-only mode — set MONACO_PRIVATE_KEY, MONACO_CLIENT_ID and MONACO_NETWORK to enable authenticated tools).")}jve().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});