@0xmonaco/mcp-server 1.1.21 → 1.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- package/package.json +3 -3
package/dist/bin.js
CHANGED
|
@@ -127,7 +127,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
127
127
|
`:`[${n[c]}\r
|
|
128
128
|
]`;continue}if(o+=n[c],n[c]==="\\")i=!0;else if(s&&n[c]==="]")s=!1;else if(!s&&n[c]==="[")s=!0}try{new RegExp(o)}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 o}function Tx(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===ge.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:Ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Xt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ge.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Sx(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===ge.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===ge.ZodBranded&&e.keyType._def.type._def.typeName===ge.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=wx(e.keyType._def,t);return{...r,propertyNames:o}}return r}function C$(e,t){if(t.mapStrategy==="record")return Tx(e,t);let r=Ke(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Xt(t),n=Ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Xt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function O$(e){let t=e.values,n=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),o=Array.from(new Set(n.map((i)=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function M$(e){return e.target==="openAi"?void 0:{not:Xt({...e,currentPath:[...e.currentPath,"not"]})}}function B$(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ug={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function N$(e,t){if(t.target==="openApi3")return L$(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in ug)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=ug[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((i)=>!n.includes(i))],[])};return L$(e,t)}var L$=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ke(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function $$(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:ug[e.innerType._def.typeName],nullable:!0};return{type:[ug[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=Ke(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=Ke(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function z$(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",eR(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)Tt(r,"minimum",n.value,n.message,t);else Tt(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;Tt(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)Tt(r,"maximum",n.value,n.message,t);else Tt(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;Tt(r,"maximum",n.value,n.message,t)}break;case"multipleOf":Tt(r,"multipleOf",n.value,n.message,t);break}return r}function D$(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];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=Ke(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(d===void 0)continue;if(n.properties[a]=d,!u)o.push(a)}if(o.length)n.required=o;let s=Rae(e,t);if(s!==void 0)n.additionalProperties=s;return n}function Rae(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ke(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 F$=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ke(e.innerType._def,t);let r=Ke(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Xt(t)},r]}:Xt(t)};var q$=(e,t)=>{if(t.pipeStrategy==="input")return Ke(e.in._def,t);else if(t.pipeStrategy==="output")return Ke(e.out._def,t);let r=Ke(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ke(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function U$(e,t){return Ke(e.type._def,t)}function j$(e,t){let n={type:"array",uniqueItems:!0,items:Ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)Tt(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)Tt(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function H$(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ke(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ke(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,n)=>Ke(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function G$(e){return{not:Xt(e)}}function V$(e){return Xt(e)}var W$=(e,t)=>Ke(e.innerType._def,t);var Z$=(e,t,r)=>{switch(t){case ge.ZodString:return Sx(e,r);case ge.ZodNumber:return z$(e,r);case ge.ZodObject:return D$(e,r);case ge.ZodBigInt:return T$(e,r);case ge.ZodBoolean:return v$();case ge.ZodDate:return tR(e,r);case ge.ZodUndefined:return G$(r);case ge.ZodNull:return B$(r);case ge.ZodArray:return S$(e,r);case ge.ZodUnion:case ge.ZodDiscriminatedUnion:return N$(e,r);case ge.ZodIntersection:return A$(e,r);case ge.ZodTuple:return H$(e,r);case ge.ZodRecord:return Tx(e,r);case ge.ZodLiteral:return k$(e,r);case ge.ZodEnum:return R$(e);case ge.ZodNativeEnum:return O$(e);case ge.ZodNullable:return $$(e,r);case ge.ZodOptional:return F$(e,r);case ge.ZodMap:return C$(e,r);case ge.ZodSet:return j$(e,r);case ge.ZodLazy:return()=>e.getter()._def;case ge.ZodPromise:return U$(e,r);case ge.ZodNaN:case ge.ZodNever:return M$(r);case ge.ZodEffects:return P$(e,r);case ge.ZodAny:return Xt(r);case ge.ZodUnknown:return V$(r);case ge.ZodDefault:return E$(e,r);case ge.ZodBranded:return wx(e,r);case ge.ZodReadonly:return W$(e,r);case ge.ZodCatch:return _$(e,r);case ge.ZodPipeline:return q$(e,r);case ge.ZodFunction:case ge.ZodVoid:case ge.ZodSymbol:return;default:return((n)=>{return})(t)}};function Ke(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==b$)return a}if(n&&!r){let a=kae(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=Z$(e,e.typeName,t),s=typeof i==="function"?Ke(i(),t):i;if(s)Iae(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var kae=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:xx(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Xt(t);return t.$refStrategy==="seen"?Xt(t):void 0}}},Iae=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var oR=(e,t)=>{let r=w$(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,d])=>({...c,[u]:Ke(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Xt(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Ke(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Xt(r),s=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(s!==void 0)i.title=s;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};function Cae(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 iR(e,t){if(Qi(e))return BP(e,{target:Cae(t?.target),io:t?.pipeStrategy??"input"});return oR(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function sR(e){let r=vc(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=pp(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function aR(e,t){let r=Tc(e,t);if(!r.success)throw r.error;return r.data}var Oae=60000;class cR{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(rx,(t)=>{this._oncancel(t)}),this.setNotificationHandler(ox,(t)=>{this._onprogress(t)}),this.setRequestHandler(nx,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(ix,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ie(Me.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(ax,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new Ie(Me.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),s.type==="response")u(a);else{let d=a,f=new Ie(d.error.code,d.error.message,d.error.data);u(f)}else{let d=s.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Ie(Me.InvalidParams,`Task not found: ${o}`);if(!Pc(i.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await n();if(Pc(i.status)){let s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...s,_meta:{...s._meta,[Ec]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(cx,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Ie(Me.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(lx,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ie(Me.InvalidParams,`Task not found: ${t.params.taskId}`);if(Pc(n.status))throw new Ie(Me.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ie(Me.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof Ie)throw n;throw new Ie(Me.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_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(Me.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=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{if(n?.(o,i),eg(o)||i$(o))this._onresponse(o);else if(FP(o))this._onrequest(o,i);else if(o$(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},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(Me.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,n=this._transport,o=e.params?._meta?.[Ec]?.taskId,i=n?.sessionId,s=this._taskStore,a=!0,c;if(o&&s&&this._taskMessageQueue&&i!==void 0)a=!1,c=(async()=>{if(!await s.getTask(o,i))throw new Ie(Me.InvalidParams,`Task not found: ${o}`);a=!0})();if(r===void 0){let g={jsonrpc:"2.0",id:e.id,error:{code:Me.MethodNotFound,message:"Method not found"}};if(o&&c){let y={type:"error",message:g,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,y,i),()=>n?.send(g)).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))}else if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:g,timestamp:Date.now()},n?.sessionId).catch((y)=>this._onerror(Error(`Failed to enqueue error response: ${y}`)));else n?.send(g).catch((y)=>this._onerror(Error(`Failed to send an error response: ${y}`)));return}let u=new AbortController;this._requestHandlerAbortControllers.set(e.id,u);let d=t$(e.params)?e.params.task:void 0,f=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,m={signal:u.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(g)=>{if(u.signal.aborted)return;let y={relatedRequestId:e.id};if(o)y.relatedTask={taskId:o};await this.notification(g,y)},sendRequest:async(g,y,x)=>{if(u.signal.aborted)throw new Ie(Me.ConnectionClosed,"Request was cancelled");let S={...x,relatedRequestId:e.id};if(o&&!S.relatedTask)S.relatedTask={taskId:o};let T=S.relatedTask?.taskId??o;if(T&&f)await f.updateTaskStatus(T,"input_required");return await this.request(g,y,S)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:f,taskRequestedTtl:d?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&u.signal.aborted)throw new Ie(Me.ConnectionClosed,"Request was cancelled");if(d)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,m)).then(async(g)=>{if(u.signal.aborted)return;let y={result:g,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:y,timestamp:Date.now()},n?.sessionId);else await n?.send(y)},async(g)=>{if(u.signal.aborted)return;let y={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(g.code)?g.code:Me.InternalError,message:g.message??"Internal error",...g.data!==void 0&&{data:g.data}}};if(o&&this._taskMessageQueue&&a)await this._enqueueTaskMessage(o,{type:"error",message:y,timestamp:Date.now()},n?.sessionId);else await n?.send(y)}).catch((g)=>this._onerror(Error(`Failed to send response: ${g}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===u)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),eg(e))r(e);else{let i=new Ie(e.error.code,e.error.message,e.error.data);r(i)}return}let n=this._responseHandlers.get(t);if(n===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 o=!1;if(eg(e)&&e.result&&typeof e.result==="object"){let i=e.result;if(i.task&&typeof i.task==="object"){let s=i.task;if(typeof s.taskId==="string")o=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(eg(e))n(e);else{let i=Ie.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ie?i:new Ie(Me.InternalError,String(i))}}return}let o;try{let i=await this.request(e,mp,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ie(Me.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},Pc(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(s.status==="failed")yield{type:"error",error:new Ie(Me.InternalError,`Task ${o} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Ie(Me.InternalError,`Task ${o} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=s.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ie?i:new Ie(Me.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,u)=>{let d=(T)=>{u(T)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(T){d(T);return}r?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};if(r?.onprogress)this._progressHandlers.set(f,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}};if(s)m.params={...m.params,task:s};if(a)m.params={...m.params,_meta:{...m.params?._meta||{},[Ec]:a}};let g=(T)=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(T)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((v)=>this._onerror(Error(`Failed to send cancellation: ${v}`)));let E=T instanceof Ie?T:new Ie(Me.RequestTimeout,String(T));u(E)};this._responseHandlers.set(f,(T)=>{if(r?.signal?.aborted)return;if(T instanceof Error)return u(T);try{let E=Tc(t,T.result);if(!E.success)u(E.error);else c(E.data)}catch(E){u(E)}}),r?.signal?.addEventListener("abort",()=>{g(r?.signal?.reason)});let y=r?.timeout??Oae,x=()=>g(Ie.fromError(Me.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(f,y,r?.maxTotalTimeout,x,r?.resetTimeoutOnProgress??!1);let S=a?.taskId;if(S){let T=(E)=>{let v=this._responseHandlers.get(f);if(v)v(E);else this._onerror(Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,T),this._enqueueTaskMessage(S,{type:"request",message:m,timestamp:Date.now()}).catch((E)=>{this._cleanupTimeout(f),u(E)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((T)=>{this._cleanupTimeout(f),u(T)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},sx,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},ux,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},c$,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ec]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,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 s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Ec]:t.relatedTask}}};this._transport?.send(s,t).catch((a)=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ec]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=sR(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let i=aR(e,n);return Promise.resolve(t(i,o))})}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=sR(e);this._notificationHandlers.set(r,(n)=>{let o=aR(e,n);return Promise.resolve(t(o))})}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 n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&FP(n.message)){let o=n.message.id,i=this._requestResolvers.get(o);if(i)i(new Ie(Me.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e,r);if(o?.pollInterval)n=o.pollInterval}catch{}return new Promise((o,i)=>{if(t.aborted){i(new Ie(Me.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),i(new Ie(Me.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new Ie(Me.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);let s=await r.getTask(n,t);if(s){let a=ig.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),Pc(s.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{let s=await r.getTask(n,t);if(!s)throw new Ie(Me.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Pc(s.status))throw new Ie(Me.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);let a=await r.getTask(n,t);if(a){let c=ig.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Pc(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function K$(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Q$(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];if(K$(s)&&K$(i))r[o]={...s,...i};else r[o]=i}return r}var u8=Tn(YR(),1),l8=Tn(c8(),1);function Phe(){let e=new u8.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return l8.default(e),e}class sA{constructor(e){this._ajv=e??Phe()}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 aA{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 n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some((u)=>u.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some((u)=>u.type==="tool_use");if(i){if(o.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(a.filter((f)=>f.type==="tool_use").map((f)=>f.id)),d=new Set(o.filter((f)=>f.type==="tool_result").map((f)=>f.toolUseId));if(u.size!==d.size||![...u].every((f)=>d.has(f)))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},cg,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){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 o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},yp,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 d8(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 p8(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 cA extends cR{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ag.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new sA,this.setRequestHandler(jP,(r)=>this._oninitialize(r)),this.setNotificationHandler(HP,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(YP,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=ag.safeParse(i);if(s.success)this._loggingLevels.set(o,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new aA(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Q$(this._capabilities,e)}setRequestHandler(e,t){let n=vc(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=pp(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(a,c)=>{let u=Tc(gp,a);if(!u.success){let g=u.error instanceof Error?u.error.message:String(u.error);throw new Ie(Me.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:d}=u.data,f=await Promise.resolve(t(a,c));if(d.task){let g=Tc(mp,f);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new Ie(Me.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}let m=Tc(yx,f);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new Ie(Me.InvalidParams,`Invalid tools/call result: ${g}`)}return m.data};return super.setRequestHandler(e,s)}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){p8(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;d8(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:JN.includes(t)?t:zP,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"},tx)}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],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=i?Array.isArray(i.content)?i.content:[i.content]:[],a=s.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(s.filter((d)=>d.type==="tool_use").map((d)=>d.id)),u=new Set(n.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},JP,t);return this.request({method:"sampling/createMessage",params:e},cg,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 n=e;return this.request({method:"elicitation/create",params:n},yp,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},yp,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new Ie(Me.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Ie)throw i;throw new Ie(Me.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}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},XP,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 m8=Symbol.for("mcp.completable");function uA(e){return!!e&&typeof e==="object"&&m8 in e}function h8(e){return e[m8]?.complete}var f8;(function(e){e.Completable="McpCompletable"})(f8||(f8={}));var Rhe=/^[A-Za-z0-9._-]{1,128}$/;function Ahe(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(!Rhe.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function khe(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 lA(e){let t=Ahe(e);return khe(e,t.warnings),t.isValid}class dA{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.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,n,t._meta,r)}}function Ihe(e,t){let r=0,n=[e];while(n.length>0){let o=n.pop();if(o===null||typeof o!=="object")continue;if(Array.isArray(o))for(let i of o){if(++r>t)return r;if(i!==null&&typeof i==="object")n.push(i)}else for(let i in o){if(!Object.prototype.hasOwnProperty.call(o,i))continue;if(++r>t)return r;let s=o[i];if(s!==null&&typeof s==="object")n.push(s)}}return r}function Che(e){if(e===void 0||e===1/0)return;if(typeof e!=="number"||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}class fA{constructor(e,t){if(this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new cA(e,t),this._maxToolInputElements=Che(t?.maxToolInputElements),t?.capabilities?.tools)this.setToolRequestHandlers();if(t?.capabilities?.resources)this.setResourceRequestHandlers();if(t?.capabilities?.prompts)this.setPromptRequestHandlers()}get experimental(){if(!this._experimental)this._experimental={tasks:new dA(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(Vc(gx)),this.server.assertCanSetRequestHandler(Vc(gp)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(gx,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=dp(t.inputSchema);return n?iR(n,{strictUnions:!0,pipeStrategy:"input"}):Ohe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=dp(t.outputSchema);if(n)r.outputSchema=iR(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(gp,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Ie(Me.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Ie(Me.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new Ie(Me.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new Ie(Me.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&i)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,s,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof Ie){if(r.code===Me.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(this._maxToolInputElements!==void 0&&Ihe(t,this._maxToolInputElements)>this._maxToolInputElements)throw new Ie(Me.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let o=dp(e.inputSchema)??e.inputSchema,i=await Vb(o,t??{});if(!i.success){let s="error"in i?i.error:"Unknown error",a=Wb(s);throw new Ie(Me.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}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(Me.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=dp(e.outputSchema),o=await Vb(n,t.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",s=Wb(i);throw new Ie(Me.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,i));else return await Promise.resolve(n.createTask(i))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,i={...r,taskStore:r.taskStore},s=n?await Promise.resolve(o.createTask(n,i)):await Promise.resolve(o.createTask(i)),a=s.task.taskId,c=s.task,u=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((f)=>setTimeout(f,u));let d=await r.taskStore.getTask(a);if(!d)throw new Ie(Me.InternalError,`Task ${a} not found during polling`);c=d}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(Vc(bx)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(bx,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return m$(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return h$(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ie(Me.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(Me.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Ie(Me.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return vg;let o=vc(r.argsSchema)?.[e.params.argument.name];if(!uA(o))return vg;let i=h8(o);if(!i)return vg;let s=await i(e.params.argument.value,e.params.context);return y8(s)}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 vg;throw new Ie(Me.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return vg;let o=await n(e.params.argument.value,e.params.context);return y8(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(Vc(dx)),this.server.assertCanSetRequestHandler(Vc(px)),this.server.assertCanSetRequestHandler(Vc(fx)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(dx,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(t);for(let s of i.resources)n.push({...o.metadata,...s})}return{resources:[...r,...n]}}),this.server.setRequestHandler(px,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(fx,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new Ie(Me.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,t)}throw new Ie(Me.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(Vc(mx)),this.server.assertCanSetRequestHandler(Vc(hx)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(mx,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Mhe(t.argsSchema):void 0}))})),this.server.setRequestHandler(hx,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Ie(Me.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Ie(Me.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=dp(r.argsSchema),o=await Vb(n,e.params.arguments??{});if(!o.success){let a="error"in o?o.error:"Unknown error",c=Wb(a);throw new Ie(Me.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=o.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=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,n,o);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,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let i={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:(s)=>{if(typeof s.uri<"u"&&s.uri!==r){if(delete this._registeredResources[r],s.uri)this._registeredResources[s.uri]=i}if(typeof s.name<"u")i.name=s.name;if(typeof s.title<"u")i.title=s.title;if(typeof s.metadata<"u")i.metadata=s.metadata;if(typeof s.callback<"u")i.readCallback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,o){let i={resourceTemplate:r,title:t,metadata:n,readCallback:o,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 s=r.uriTemplate.variableNames;if(Array.isArray(s)&&s.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return i}_createRegisteredPrompt(e,t,r,n,o){let i={title:t,description:r,argsSchema:n===void 0?void 0:ul(n),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(s)=>{if(typeof s.name<"u"&&s.name!==e){if(delete this._registeredPrompts[e],s.name)this._registeredPrompts[s.name]=i}if(typeof s.title<"u")i.title=s.title;if(typeof s.description<"u")i.description=s.description;if(typeof s.argsSchema<"u")i.argsSchema=ul(s.argsSchema);if(typeof s.callback<"u")i.callback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=i,n){if(Object.values(n).some((a)=>{let c=a instanceof Yb?a._def?.innerType:a;return uA(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,n,o,i,s,a,c){lA(e);let u={title:t,description:r,inputSchema:g8(n),outputSchema:g8(o),annotations:i,execution:s,_meta:a,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")lA(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=ul(d.paramsSchema);if(typeof d.outputSchema<"u")u.outputSchema=ul(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,n,o,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(pA(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!pA(t[0]))i=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).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 s=t[0];return this._createRegisteredTool(e,void 0,r,n,o,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,i,s,a,{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 n;if(t.length>1)n=t.shift();let o=t[0],i=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:i}=t,s=this._createRegisteredPrompt(e,n,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}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 Ohe={type:"object",properties:{}};function b8(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function x8(e){return"_def"in e||"_zod"in e||b8(e)}function pA(e){if(typeof e!=="object"||e===null)return!1;if(x8(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(b8)}function g8(e){if(!e)return;if(pA(e))return ul(e);if(!x8(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Mhe(e){let t=vc(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=bN(n),i=xN(n);return{name:r,description:o,required:!i}})}function Vc(e){let r=vc(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=pp(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function y8(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var vg={completion:{values:[],hasMore:!1}};import S8 from"node:process";var Bhe=10485760;class mA{constructor(e){this._maxBufferSize=e?.maxBufferSize??Bhe}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
129
129
|
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Lhe(t)}clear(){this._buffer=void 0}}function Lhe(e){return s$.parse(JSON.parse(e))}function w8(e){return JSON.stringify(e)+`
|
|
130
|
-
`}class hA{constructor(e=S8.stdin,t=S8.stdout,r){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=(n)=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=(n)=>{this.onerror?.(n)},this._readBuffer=new mA({maxBufferSize:r?.maxBufferSize})}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=w8(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var fw={name:"@0xmonaco/mcp-server",version:"1.1.21",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.1.21","@0xmonaco/types":"1.1.21","@modelcontextprotocol/sdk":"^1.32.2","node-fetch":"^3.3.2",viem:"^2.57.20",ws:"^8.23.0",zod:"^4.6.7"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.2"}};var mw=["read","market-maker","full"],us=[{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_trader_metrics",description:"Get public current long/short account counts, account shares and ratio, plus active-trader counts for a margin pair. Accounts are classified by net position across open risk buckets. Small cohorts are suppressed; activity counts include system user IDs on liquidation and ADL fills.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trade_flow",description:"Get UTC-aligned 1m, 5m, 1h, 4h or 1d taker buy/sell quote-notional buckets and cumulative volume delta for a margin pair over up to 90 days, including liquidation and ADL fills.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"list_liquidation_events",description:"List paginated public per-fill liquidation events, including public wallets and quote-asset notional using each event's captured mark.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_liquidation_metrics",description:"Get UTC-aligned 1m, 5m, 1h, 4h or 1d long/short liquidation totals over up to 90 days; event counts represent persisted rows and notionals use each row's event-time mark.",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 one-sided LONG open interest (each contract counted once) 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. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 15 minutes of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",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. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 15 minutes of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",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:"cancel_all_after",description:"Arm, refresh or disarm a dead man's switch that cancels your resting orders unless you call again before the timeout (0 disarms).",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-set and side filters).",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:"transfer_collateral_to_sub_account",description:"Move collateral from your default (parent) margin account into one of your margin sub-accounts.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_sub_account",description:"Move collateral from one of your margin sub-accounts back to your default (parent) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_fee_schedule",description:"Get a trading pair's fee tier schedule: volume thresholds and maker/taker bps per tier (no credentials required).",category:"fees",authMode:"public",sideEffect:"read-only"},{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, why your rate applies (`rateSource`) and which kind of rate it is (`rateScope`), your effective maker and taker rates on a pair, rolling 14-day volumes and when they were last computed (`updatedAt`), and the fee schedule that applies to you on the pair.",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 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) TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your TraderCodes rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned TraderCodes rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"list_lead_traders",description:"Public copy trading leaderboard: lead traders ranked by ROI, PnL, followers, allocated AUM, marked AUM or win rate over a stats window (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only",hiddenFromDocs:!0},{name:"get_lead_trader",description:"Public profile, follow summary and stats of one lead trader, by custom TraderCode handle (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_lead_trader_closed_trades",description:"Public list of a lead trader's closed trades, newest first (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_lead_trader_open_positions",description:"Open positions of a lead trader you currently follow (followers only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"get_my_lead_trader",description:"Fetch your own lead trader profile, follow summary and stats.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_my_followers",description:"List your followers, as a lead trader.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_my_follows",description:"List your copy trading follows and their settings.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"get_follow",description:"Fetch one of your follows with its most recent skipped mirrors and its copy account's marked equity.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"preview_follow",description:"Preview what following a lead trader with copyExisting would open: estimated margin and fees and how many positions would be copied (read-only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_follow_leader_positions",description:"Open positions of the lead trader one of your follows copies (live follows only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"upsert_lead_trader",description:"Register as a lead trader, or edit your lead profile (profit share, bio, status, minimum allocation).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",hiddenFromDocs:!0},{name:"upsert_follow",description:"Follow a lead trader (moves the allocation into a new copy account) or edit one of your follows.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement",hiddenFromDocs:!0},{name:"stop_follow",description:"Stop one of your follows: the leader's fills stop being mirrored.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",hiddenFromDocs:!0},{name:"close_follow_positions",description:"Close one follow's copy positions at market and keep the follow (it keeps mirroring).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",hiddenFromDocs:!0},{name:"close_all_copy_positions",description:"Close the copy positions of all your follows at market and keep the follows.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",hiddenFromDocs:!0},{name:"add_follow_position_margin",description:"Add margin to one of your copy positions from the follow's copy account (lowers its leverage; your margin account is never touched; no reduction). Not idempotent — after a timeout, read the follow before retrying, or the amount may be added twice.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement",hiddenFromDocs:!0},{name:"get_rfq_capabilities",description:"RFQ (block trading): your RFQ limits and the markets RFQ is offered on.",category:"rfq",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_rfq",description:"RFQ: an RFQ's status — the taker's view and outcome, or the maker's own quote and last-look selection.",category:"rfq",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_rfqs",description:"RFQ: your RFQs as the taker, newest first, with each one's state and outcome.",category:"rfq",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"create_rfq",description:"RFQ: request quotes for a size on a market (two-way unless a side is given). The SDK supplies an idempotency key if omitted.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"accept_rfq",description:"RFQ: accept one side of the taker view you last saw. Binding: it executes after the makers' last look. The SDK supplies an idempotency key if omitted.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_rfq",description:"RFQ: cancel an RFQ you have not accepted, before its deadline.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"upsert_rfq_quote",description:"RFQ: as maker, place or replace your quote (a bid, an ask or both), naming your current version. The SDK supplies an idempotency key if omitted.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"withdraw_rfq_quote",description:"RFQ: as maker, withdraw your current quote, naming your current version.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"respond_rfq_last_look",description:"RFQ: as a selected maker, reject or improve your frozen terms before the last-look deadline. Silence executes.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{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"}],m6e=us.map((e)=>e.name),T8=us.filter((e)=>e.authMode==="public").map((e)=>e.name),h6e=us.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),g6e=us.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),y6e=us.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),b6e=us.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),v8=us.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var $he=new Map(us.map((e)=>[e.name,e.sideEffect]));function _8(e){let t=$he.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var E8={read:0,"market-maker":1,full:2},gA=T8,yA=Object.fromEntries(us.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),P8=Object.fromEntries(Object.entries(yA).map(([e,t])=>[e,t.capability])),S6e=new Set(v8);function R8(e){let t=yA[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function A8(e){return R8(e)==="read"}function k8(e,t){if(t.network==="mainnet"&&yA[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(gA.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return E8[t.capability]>=E8[R8(e)]}var zhe=new Set([...gA,...Object.keys(P8)]),Dhe={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 I8(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function yl(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 n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!mw.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${mw.join(", ")}.`);let c=a||"read",u=I8(e.MONACO_TOOL_ALLOWLIST),d=I8(e.MONACO_TOOL_DENYLIST),f=[...u,...d].filter((y)=>!zhe.has(y)).length;if(f>0)throw Error(`${f} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||Dhe[s],g=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).");g=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:u,deny:d,delegatedOwnerUserId:g}}var hw=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var zp=D(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),bl=D(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),xl=D(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),_g=D(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),M8=D(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),bA=D(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),wl=D(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Dp=D(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),De=p().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"}),ye=zN({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),pa=ll.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),B8=_().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Fp=_().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),L8=_().int().min(0,"Slippage tolerance must be at least 0 bps").max(1000,"Slippage tolerance cannot exceed 1000 bps"),Fhe=_().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),gw=b({triggerPrice:De,orderType:Dp,limitPrice:De.optional(),quantity:De.optional(),closePosition:Z().optional(),timeInForce:bA.optional(),slippageToleranceBps:Fp.optional(),expiresAt:pa.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"]}),qhe=_().int("trailBps must be an integer number of basis points").min(10,"trailBps must be at least 10 bps").max(2000,"trailBps cannot exceed 2000 bps"),xA=b({trailBps:qhe,activationPrice:De.optional(),quantity:De.optional(),closePosition:Z().optional(),slippageToleranceBps:Fp.optional(),expiresAt:pa.optional()}).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"]}),N8=xA,yw=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0||e?.trailingStop!==void 0,wA=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),Eg=p().trim().min(1,"strategyKey cannot be empty").max(64,"strategyKey must be a sub-account key: letters, digits, _ - . :, up to 64 characters").regex(/^[A-Za-z0-9_.:-]+$/,"strategyKey must be a sub-account key: letters, digits, _ - . :, up to 64 characters"),Pg=Eg.refine((e)=>!e.toLowerCase().startsWith("copy:"),"strategy keys starting with copy: are reserved"),ls=p().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),$8=b({tradingPairId:ye,side:zp,quantity:De,price:De,options:b({idempotencyKey:ls.optional(),tradingMode:bl.optional(),useMasterBalance:Z().optional(),expirationDate:pa.optional(),timeInForce:M8.optional(),marginAccountId:ye.optional(),marginMode:xl.optional(),riskBucketId:ye.optional(),riskBucketCollateral:De.optional(),strategyKey:Eg.optional(),positionSide:_g.optional(),leverage:De.optional(),reduceOnly:Z().optional(),postOnly:Z().optional(),selfTradePreventionMode:wl.optional(),takeProfit:gw.optional(),stopLoss:gw.optional(),trailingStop:N8.optional()}).optional()}).refine((e)=>wA(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)=>!yw(e.options)||e.options?.tradingMode!=="SPOT",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!yw(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode!=="SPOT",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode!=="SPOT",{message:"marginMode 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?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).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"]}),z8=b({tradingPairId:ye,side:zp,quantity:De,options:b({idempotencyKey:ls.optional(),tradingMode:bl.optional(),slippageTolerance:B8,marginAccountId:ye.optional(),marginMode:xl.optional(),riskBucketId:ye.optional(),riskBucketCollateral:De.optional(),strategyKey:Eg.optional(),positionSide:_g.optional(),leverage:De.optional(),reduceOnly:Z().optional(),selfTradePreventionMode:wl.optional(),takeProfit:gw.optional(),stopLoss:gw.optional(),trailingStop:N8.optional()}).optional()}).refine((e)=>wA(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)=>!yw(e.options)||e.options?.tradingMode!=="SPOT",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!yw(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode!=="SPOT",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode!=="SPOT",{message:"marginMode 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?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).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"]}),D8=b({orderId:ye,remainingQuantityTarget:De.optional()}),F8=b({orderId:ye,newOrder:b({price:De.optional(),quantity:De.optional(),useMasterBalance:Z().optional(),postOnly:Z().optional(),selfTradePreventionMode:wl.optional()})}),q8=b({page:ut().optional(),status:bt([D(hw),Q(D(hw)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:ye.optional(),tradingMode:bl.optional(),marginAccountId:ye.optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),C6e=D(["STOP_LOSS","TAKE_PROFIT","TRAILING_STOP"],{message:'conditionType must be "STOP_LOSS", "TAKE_PROFIT", or "TRAILING_STOP"'}),O6e=D(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),Uhe=D(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),U8=D(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),SA=b({conditionalOrderId:ye}),j8=b({page:ut().optional(),marginAccountId:ye.optional(),tradingPairId:ye.optional(),state:Uhe.optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),jhe=D(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),Hhe=bt([_().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),p().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Ghe=2592000000,H8=b({tradingPairId:ye,side:zp,quantity:De,options:b({durationSeconds:Hhe.optional(),startTime:pa.optional(),endTime:pa.optional(),limitPrice:De.optional(),slippageToleranceBps:Fhe.optional(),randomize:Z().optional(),executionStyle:D(["TAKER","PASSIVE"]).optional(),reduceOnly:Z().optional(),tradingMode:bl.optional(),marginAccountId:ye.optional(),riskBucketId:ye.optional(),marginMode:xl.optional(),leverage:De.optional(),strategyKey:Eg.optional(),useMasterBalance:Z().optional(),clientTwapId:p().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:De.optional(),triggerDirection:D(["ABOVE","BELOW"]).optional(),conditionalExpiry:pa.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!=="SPOT",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode!=="SPOT",{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.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).refine((e)=>e.options.triggerPrice!==void 0===(e.options.triggerDirection!==void 0),{message:"triggerPrice and triggerDirection are both-or-neither",path:["options","triggerDirection"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.durationSeconds!==void 0,{message:"conditional TWAP (triggerPrice) requires durationSeconds — the window floats from the trigger instant",path:["options","durationSeconds"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.startTime===void 0&&e.options.endTime===void 0,{message:"triggerPrice is incompatible with startTime/endTime",path:["options","triggerPrice"]}).refine((e)=>e.options.conditionalExpiry===void 0||e.options.triggerPrice!==void 0,{message:"conditionalExpiry is only valid together with triggerPrice",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r>Date.now()},{message:"conditionalExpiry must be in the future",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r-Date.now()<=Ghe},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),C8=5000,O8=900000,G8=b({timeoutMs:_().int().refine((e)=>e===0||e>=C8&&e<=O8,{message:`timeoutMs must be 0 or between ${C8} and ${O8}`}),options:b({tradingPairId:ye.optional()}).strict().optional()}).strict(),xw=b({twapOrderId:ye}),V8=b({page:ut().optional(),state:jhe.optional(),tradingPairId:ye.optional(),marginAccountId:ye.optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),W8=b({page:ut().optional(),twapOrderId:ye,orderBy:D(["ASC","DESC"]).optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Vhe=b({tradingPairId:ye,orderType:Dp,side:zp,price:De.optional(),quantity:De,idempotencyKey:ls.optional(),tradingMode:bl.optional(),slippageTolerance:B8,useMasterBalance:Z().optional(),expirationDate:pa.optional(),timeInForce:M8.optional(),marginAccountId:ye.optional(),marginMode:xl.optional(),riskBucketId:ye.optional(),riskBucketCollateral:De.optional(),strategyKey:Eg.optional(),positionSide:_g.optional(),leverage:De.optional(),reduceOnly:Z().optional(),postOnly:Z().optional(),selfTradePreventionMode:wl.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!=="SPOT",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode!=="SPOT",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).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.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)=>wA(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"]}),bw=100,Z8=b({orders:Q(Vhe).min(1,"At least one order is required").max(bw,`At most ${bw} orders per batch request`)}),Whe=b({orderId:ye,price:De.optional(),quantity:De.optional(),useMasterBalance:Z().optional(),postOnly:Z().optional(),selfTradePreventionMode:wl.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),K8=b({orders:Q(Whe).min(1,"At least one order is required").max(bw,`At most ${bw} orders per batch request`)});var Zhe=b({applicationId:p().uuid(),enrolled:Z(),payoutAddress:p().nullable().optional(),buildercodesEnabled:Z(),buildercodesBudgetBps:_().int().min(0).max(1e4),builderFeeEnabled:Z(),builderFeeBps:_().int().min(0).max(100),builderFeeCapBps:_().int().min(0).max(100),changesRemaining:_().int().min(0).max(500),nextChangeAllowedAt:p().nullable().optional(),builderMakerFeeBps:_().int().min(0).max(100).optional(),builderFeeRulesPerSave:_().int().min(0).optional(),builderFeeRulesPerApplication:_().int().min(0).optional(),builderFeeRuleCount:_().int().min(0).optional(),builderFeeRulesEnabled:Z().optional()}),vA=b({bps:_().int().min(0).max(100),makerBps:_().int().min(0).max(100).optional()}),Khe=b({builderFeeBps:_().int().min(0).max(100),previousBuilderFeeBps:_().int().min(0).max(100),changesRemaining:_().int().min(0).max(500),nextChangeAllowedAt:p().nullable().optional(),builderMakerFeeBps:_().int().min(0).max(100).optional(),previousBuilderMakerFeeBps:_().int().min(0).max(100).optional()}),Q8=D(["BUILDER","ADMIN"]),Y8=b({actorType:Q8,actor:p(),oldBps:_().int().min(0).max(100),newBps:_().int().min(0).max(100),createdAt:p(),oldMakerBps:_().int().min(0).max(100).optional(),newMakerBps:_().int().min(0).max(100).optional()}),_A=b({pageSize:_().int().min(1).max(100).optional(),pageToken:p().optional()}),Qhe=b({changes:Q(Y8),nextPageToken:p()}),Sw=D(["REVENUE_SHARE","BUILDER_FEE","BUILDER_MAKER_FEE"]),EA=b({page:ut().optional(),pageSize:_().int().min(1).max(1000).optional(),pageToken:p().optional(),kind:Sw.optional()}),J8=b({tradeId:p().uuid(),payoutAddress:p(),token:p(),amount:p(),appliedBps:_().int(),appliedCbps:_().int().optional(),createdAt:p(),kind:Sw.optional()}),Yhe=b({payouts:Q(J8),total:_().int().nonnegative(),pageSize:_().int().positive(),totalPages:_().int().nonnegative(),nextPageToken:p()}),TA=b({token:p(),totalAmount:p(),payoutCount:_().int().nonnegative(),lastCreditedAt:p()}),X8=b({token:p(),kind:Sw,totalAmount:p(),payoutCount:_().int().nonnegative(),lastCreditedAt:p()}),Jhe=b({totalPayouts:_().int().nonnegative(),lastCreditedAt:p().nullable().optional(),byToken:Q(TA),byTokenAndKind:Q(X8).optional(),builderFeeByToken:Q(TA).optional()}),e3=b({token:p(),available:p()}),Xhe=b({balances:Q(e3)}),PA=b({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string"),idempotencyKey:ls.optional()}),ege=b({payoutBalance:p(),tradingBalance:p()}),RA=D(["CLOB","RFQ","BOTH"]),t3=D(["CLOB","RFQ"]),AA=D(["SPOT","MARGIN"]),r3=D(["BUILDER","OVERRIDE"]),kA=p().regex(/^0x[0-9a-fA-F]{40}$/,"walletAddress must be a 0x-prefixed EVM address"),Wc=_().int().min(0).max(1e4),fa=b({walletAddress:kA.nullable().optional(),tradingPairId:p().uuid().nullable().optional(),marketType:AA.nullable().optional(),track:RA}).refine((e)=>!(e.tradingPairId&&e.marketType),{message:"set at most one of tradingPairId and marketType"}),ww=b({id:p().uuid(),scope:fa,source:r3,makerCbps:Wc,takerCbps:Wc,makerClamped:Z(),takerClamped:Z(),editable:Z(),note:p().nullable().optional(),updatedAt:p()}),IA=b({id:p().uuid(),scope:fa,forAllApplications:Z(),capCbps:Wc,updatedAt:p()}),CA=b({id:p().uuid(),scope:fa,forAllApplications:Z(),revshareBps:_().int().min(0).max(1e4),updatedAt:p()}),OA=b({pageSize:_().int().min(1).max(100).optional(),pageToken:p().optional(),walletAddress:kA.optional(),tradingPairId:p().uuid().optional(),marketType:AA.optional(),track:RA.optional()}),tge=b({addOnRules:Q(ww),capRules:Q(IA),revshareRules:Q(CA),nextPageToken:p(),ruleCount:_().int().min(0),rulesPerApplication:_().int().min(0)}),MA=b({scope:fa,makerCbps:Wc,takerCbps:Wc}),BA=b({upserts:Q(MA).optional(),deletes:Q(fa).optional(),note:p().optional()}),LA=b({op:D(["SET","DELETE"]),scope:fa,makerCbpsBefore:_().int().nullable().optional(),takerCbpsBefore:_().int().nullable().optional(),makerCbpsAfter:_().int().nullable().optional(),takerCbpsAfter:_().int().nullable().optional()}),rge=b({changes:Q(LA),changesRemaining:_().int().min(0).max(500),nextChangeAllowedAt:p().nullable().optional()}),NA=b({upserts:Q(MA).optional(),deletes:Q(fa).optional()}),n3=b({change:LA,shadowedByOverride:Z(),narrowerRulesKept:Q(fa),makerClamped:Z(),takerClamped:Z(),walletHasAccount:Z().nullable().optional()}),nge=b({entries:Q(n3),changesRemaining:_().int().min(0).max(500),refusal:p().nullable().optional()}),$A=b({walletAddress:kA,tradingPairId:p().uuid(),track:t3}),oge=b({makerCbps:Wc,takerCbps:Wc,makerClamped:Z(),takerClamped:Z(),builderFeeEnabled:Z(),capCbps:Wc,revshareBps:_().int().min(0).max(1e4),winningRule:ww.nullable().optional(),matchingRules:Q(ww),winningCap:IA.nullable().optional(),winningRevshare:CA.nullable().optional()});function mi(){return p()}var zA=b({walletAddress:p(),handle:p().nullish(),display:p()}),DA=b({leader:zA,status:mi(),shareBps:_(),bio:p(),minAllocation:p().nullish(),registeredAt:p()}),FA=b({followerCount:_(),allocated:p(),aumEquity:p().nullish()}),qA=b({window:mi(),pnl:p(),roiPct:p().nullish(),maxDrawdownPct:p().nullish(),winRatePct:p().nullish(),closedTrades:_()}),ige=b({profile:DA,followSummary:FA,stats:Q(qA)}),o3=b({profile:DA,followSummary:FA,stats:qA}),sge=b({leaders:Q(o3),nextPageToken:p(),asOf:p()}),age=b({created:Z(),status:mi(),shareBps:_()}),i3=b({walletAddress:p(),display:p(),status:mi(),allocation:p(),startedAt:p()}),cge=b({followers:Q(i3),nextPageToken:p()}),s3=b({tradingPairId:p(),positionSide:p(),action:mi(),size:p().nullish(),exitPrice:p().nullish(),entryPrice:p().nullish(),realizedPnl:p().nullish(),netRealizedPnl:p().nullish(),realizedRoe:p().nullish(),closedAt:p()}),uge=b({closedTrades:Q(s3),nextPageToken:p()}),UA=b({tradingPairId:p(),side:p(),size:p(),entryPrice:p(),markPrice:p().nullish(),unrealizedPnl:p().nullish(),leverage:p().nullish(),marginMode:p()}),lge=b({positions:Q(UA)}),jA=b({followId:p(),leader:zA,status:mi(),marginModePolicy:mi(),sizingMode:mi(),sizingParam:p().nullish(),leverageMode:mi(),fixedLeverage:p().nullish(),allocation:p(),slPct:p().nullish(),copyExisting:Z(),tradingPairIds:Q(p()),consecutiveSkips:_(),copyRiskBucketId:p(),startedAt:p(),stoppedAt:p().nullish(),stopReason:mi().nullish()}),dge=b({follows:Q(jA),nextPageToken:p()}),a3=b({tradingPairId:p(),reason:mi(),requestedQuantity:p(),skippedAt:p()}),pge=b({follow:jA,recentSkips:Q(a3),copyAccountEquity:p().nullish()}),fge=b({positions:Q(UA)}),mge=b({followId:p(),copyRiskBucketId:p(),created:Z()}),hge=b({estimatedMargin:p(),estimatedFee:p(),copiedPositions:_(),skippedPositions:_(),truncated:Z()}),gge=b({followId:p()}),c3=b({followId:p(),closeOrdersPlaced:_(),positionsNotClosed:_()}),u3=b({followId:p(),reason:p()}),yge=b({follows:Q(c3),stoppingFollowIds:Q(p()),failedFollows:Q(u3)}),bge=b({followId:p(),tradingPairId:p(),riskBucketId:p(),positionId:p(),positionMargin:p(),copyAccountAvailable:p()});var HA=b({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty"),side:D(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:p().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:p().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:D(["LIMIT","MARKET"]).optional(),slippageToleranceBps:_().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:_c.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),xge=b({applicationName:p().nullable().optional(),applicationTakerFee:p(),applicationTakerFeeBps:_(),applicationTakerFeeCbps:_().optional(),buyOrderLockAmount:p().nullable().optional(),makerTotalReceipt:p(),applicationMakerFee:p().optional(),applicationMakerFeeBps:_().optional(),applicationMakerFeeCbps:_().optional(),builderFeeClamped:Z().optional(),builderMakerFeeClamped:Z().optional(),monacoMakerRebate:p(),monacoMakerRebateBpsExact:p(),monacoTakerFee:p(),monacoTakerFeeBpsExact:p(),notional:p(),takerTotalPayment:p(),totalTakerFees:p(),maxQuantity:p().nullable(),maxQuantityRaw:p().nullable(),slippageToleranceBps:_().nullable()}),GA=b({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty")}),VA=b({tierLevel:_().int(),minVolumeThreshold:p(),makerFeeBps:p(),takerFeeBps:p()}),wge=b({currentTierLevel:_().int(),weightedVolume14d:p(),spotVolume14d:p(),perpVolume14d:p(),volumeToNextTier:p().nullable().optional(),nextTierLevel:_().int().nullable().optional(),feeSchedule:Q(VA),rateSource:D(["volume","tier_override","custom"]),makerFeeBps:p(),takerFeeBps:p(),rateScope:D(["wallet_application","wallet","application","pair","market_type"]),updatedAt:ll.datetime().nullable().optional()}),WA=b({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty")}),Sge=b({tradingPairId:p(),feeSchedule:Q(VA)});function ma(){return p()}var ZA=b({price:p(),capacity:p()}),Tge=b({rfqId:p(),tradingPairId:p(),product:ma().nullish(),quantity:p(),createdAtMs:_(),deadlineAtMs:_(),side:ma().nullish(),quoteSide:ma().nullish(),leverage:p().nullish(),marginMode:p().nullish()}),KA=b({vwap:p(),grossVwap:p(),asOfMs:_(),levels:_()}),l3=b({vwap:p(),availableQuantity:p(),grossVwap:p().nullish(),estimatedMonacoFee:p().nullish(),estimatedBuilderFee:p().nullish(),estimatedTotalFee:p().nullish(),book:KA.nullish()}),vge=b({viewVersion:_(),bid:l3.nullish(),ask:l3.nullish(),asOfMs:_(),monacoFeeCbps:_().nullish(),builderFeeCbps:_().nullish()}),_ge=b({executionId:p(),price:p(),quantity:p(),fee:p(),monacoFee:p().nullish(),builderFee:p().nullish()}),Ege=b({executedQuantity:p(),unfilledQuantity:p(),vwap:p(),fills:Q(_ge),allInVwap:p().nullish(),bookAtFill:KA.nullish(),bookAtFillFullSize:Z().nullish()}),Pge=b({executionId:p(),price:p(),quantity:p(),fee:p().nullish(),monacoFee:p().nullish(),builderFee:p().nullish()}),Rge=b({viewVersion:_(),acceptedAtMs:_(),vwap:p().nullish(),grossVwap:p().nullish(),availableQuantity:p().nullish(),monacoFeeCbps:_(),builderFeeCbps:_().nullish(),book:KA.nullish(),bookFullSize:Z().nullish()}),Age=b({side:ma(),code:p(),reason:p()}),kge=b({rfqId:p(),quoteId:p(),version:_(),bid:ZA.nullish(),ask:ZA.nullish(),issuedAtMs:_(),validUntilMs:_(),leverage:p().nullish(),marginMode:p().nullish(),refusedSides:Q(Age).nullish()}),Ige=b({acceptanceId:p(),takerSide:ma().nullish(),quoteId:p(),quoteVersion:_(),quantity:p(),frozenTerms:ZA.nullish(),lastLookDeadlineAtMs:_(),monacoFeeCbps:_().nullish(),maxBuilderFeeCbps:_().nullish(),estimatedNet:p().nullish()}),Cge=b({terms:Tge.nullish(),state:ma(),stateVersion:_(),acceptedSide:ma().nullish(),lastLookDeadlineAtMs:_().nullish(),view:vge.nullish(),ownQuote:kge.nullish(),ownSelection:Ige.nullish(),ownLatestVersion:_(),ownQuoteWithdrawn:Z(),outcome:Ege.nullish(),durableSequence:_(),ownFills:Q(Pge).nullish(),acceptance:Rge.nullish()}),Z6e=b({rfqs:Q(Cge),nextPageToken:p()}),Oge=b({tradingPairId:p(),product:ma().nullish(),minQuantity:p(),maxQuantity:p()}),K6e=b({protocolVersion:_(),enabled:Z(),markets:Q(Oge),requestWindowMs:_(),minQuoteValidityMs:_(),maxQuoteValidityMs:_(),lastLookMs:_(),maxNewRfqs:_(),quotaWindowMs:_(),quotaRemaining:_(),quotaRetryAfterMs:_()}),Q6e=b({rfqId:p(),version:_()}),Y6e=b({acceptanceId:p(),response:ma().nullish(),recordedAtMs:_()});var d3=b({token:p(),available:p()}),Mge=b({balances:Q(d3)}),Bge=b({code:p(),createdAt:p(),customCode:p(),isCustom:Z(),display:p()}),p3=D(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Lge=b({available:Z(),reason:Jh((e)=>e===""||e===null?void 0:e,p3.optional())}),QA=b({code:p().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")}),Nge=b({code:p()}),YA=b({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),$ge=b({rewardsBalance:p(),tradingBalance:p()}),f3=b({source:p(),sourceDisplay:p(),level:_(),amount:p(),token:p(),rateApplied:p(),createdAt:p()}),m3=b({wallet:p(),display:p(),level:_()}),zge=b({referrer:p(),referrerDisplay:p(),totalEarned:p(),rewards:Q(f3),upline:Q(m3)}),h3=b({source:p(),sourceDisplay:p(),level:_(),totalEarned:p(),token:p()}),g3=b({wallet:p(),display:p(),referredAt:p(),totalEarned:p()}),y3=b({level:_(),earned:p()}),b3=b({totalEarned:p(),level1Earned:p(),level2Earned:p(),level3Earned:p(),byLevel:Q(y3)}),JA=b({pageSize:_().int().min(1).max(500).optional(),pageToken:p().optional()}),Dge=b({earningsBySource:Q(h3),directReferees:Q(g3),summary:b3,nextPageToken:p()}),XA=b({parent:p().optional(),pageSize:_().int().min(1).max(200).optional(),pageToken:p().optional()}),x3=b({wallet:p(),display:p(),level:_(),parent:p(),referredAt:p(),refereeCount:_(),totalEarned:p()}),Fge=b({parent:p(),parentLevel:_(),nodes:Q(x3),nextPageToken:p()});var w3=p().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),ek=bt([p().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),FN().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),S3=b({assetId:ye,amount:ek,autoWait:Z().optional()}),T3=b({assetId:ye,amount:ek,autoWait:Z().optional(),target:D(["spot","margin","cross_risk_bucket"]).optional(),options:b({asErc20:Z().optional()}).optional()}),v3=b({assetId:ye,amount:ek,destination:p().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:Z().optional(),source:D(["spot","margin","cross_risk_bucket"]).optional()}),uMe=b({assetId:ye}),_3=b({page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var Rg=b({clientId:p().trim().min(1,"Client ID is required"),page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),E3=Rg.extend({status:p().trim().min(1,"Status cannot be empty").optional(),userId:ye.optional(),tradingPairId:ye.optional(),side:p().trim().min(1,"Side cannot be empty").optional(),orderType:p().trim().min(1,"Order type cannot be empty").optional()}),P3=Rg.extend({isActive:Z().optional(),accountType:p().trim().min(1,"Account type cannot be empty").optional(),address:p().trim().min(1,"Address filter cannot be empty").optional()}),R3=Rg.extend({userId:ye.optional(),transactionType:p().trim().min(1,"Transaction type cannot be empty").optional(),entryType:p().trim().min(1,"Entry type cannot be empty").optional(),assetId:ye.optional()}),A3=Rg.extend({userId:ye.optional(),assetId:ye.optional()}),k3=Rg.extend({address:w3.optional()});class I3 extends Error{issues;constructor(e){let t=e.issues.map((r)=>{let n=r.path.join(".");return`${n?`${n}: `:""}${r.message}`});super(`Validation failed:
|
|
130
|
+
`}class hA{constructor(e=S8.stdin,t=S8.stdout,r){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=(n)=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=(n)=>{this.onerror?.(n)},this._readBuffer=new mA({maxBufferSize:r?.maxBufferSize})}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=w8(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var fw={name:"@0xmonaco/mcp-server",version:"1.1.22",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.1.22","@0xmonaco/types":"1.1.22","@modelcontextprotocol/sdk":"^1.32.2","node-fetch":"^3.3.2",viem:"^2.57.20",ws:"^8.23.0",zod:"^4.6.7"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.2"}};var mw=["read","market-maker","full"],us=[{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_trader_metrics",description:"Get public current long/short account counts, account shares and ratio, plus active-trader counts for a margin pair. Accounts are classified by net position across open risk buckets. Small cohorts are suppressed; activity counts include system user IDs on liquidation and ADL fills.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trade_flow",description:"Get UTC-aligned 1m, 5m, 1h, 4h or 1d taker buy/sell quote-notional buckets and cumulative volume delta for a margin pair over up to 90 days, including liquidation and ADL fills.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"list_liquidation_events",description:"List paginated public per-fill liquidation events, including public wallets and quote-asset notional using each event's captured mark.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_liquidation_metrics",description:"Get UTC-aligned 1m, 5m, 1h, 4h or 1d long/short liquidation totals over up to 90 days; event counts represent persisted rows and notionals use each row's event-time mark.",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 one-sided LONG open interest (each contract counted once) 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. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 15 minutes of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",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. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 15 minutes of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",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:"cancel_all_after",description:"Arm, refresh or disarm a dead man's switch that cancels your resting orders unless you call again before the timeout (0 disarms).",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-set and side filters).",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:"transfer_collateral_to_sub_account",description:"Move collateral from your default (parent) margin account into one of your margin sub-accounts.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_sub_account",description:"Move collateral from one of your margin sub-accounts back to your default (parent) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_fee_schedule",description:"Get a trading pair's fee tier schedule: volume thresholds and maker/taker bps per tier (no credentials required).",category:"fees",authMode:"public",sideEffect:"read-only"},{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, why your rate applies (`rateSource`) and which kind of rate it is (`rateScope`), your effective maker and taker rates on a pair, rolling 14-day volumes and when they were last computed (`updatedAt`), and the fee schedule that applies to you on the pair.",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 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) TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your TraderCodes rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned TraderCodes rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"list_lead_traders",description:"Public copy trading leaderboard: lead traders ranked by ROI, PnL, followers, allocated AUM, marked AUM or win rate over a stats window (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only",hiddenFromDocs:!0},{name:"get_lead_trader",description:"Public profile, follow summary and stats of one lead trader, by custom TraderCode handle (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_lead_trader_closed_trades",description:"Public list of a lead trader's closed trades, newest first (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_lead_trader_open_positions",description:"Open positions of a lead trader you currently follow (followers only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"get_my_lead_trader",description:"Fetch your own lead trader profile, follow summary and stats.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_my_followers",description:"List your followers, as a lead trader.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_my_follows",description:"List your copy trading follows and their settings.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"get_follow",description:"Fetch one of your follows with its most recent skipped mirrors and its copy account's marked equity.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"preview_follow",description:"Preview what following a lead trader with copyExisting would open: estimated margin and fees and how many positions would be copied (read-only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"list_follow_leader_positions",description:"Open positions of the lead trader one of your follows copies (live follows only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only",hiddenFromDocs:!0},{name:"upsert_lead_trader",description:"Register as a lead trader, or edit your lead profile (profit share, bio, status, minimum allocation).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",hiddenFromDocs:!0},{name:"upsert_follow",description:"Follow a lead trader (moves the allocation into a new copy account) or edit one of your follows.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement",hiddenFromDocs:!0},{name:"stop_follow",description:"Stop one of your follows: the leader's fills stop being mirrored.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",hiddenFromDocs:!0},{name:"close_follow_positions",description:"Close one follow's copy positions at market and keep the follow (it keeps mirroring).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",hiddenFromDocs:!0},{name:"close_all_copy_positions",description:"Close the copy positions of all your follows at market and keep the follows.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",hiddenFromDocs:!0},{name:"add_follow_position_margin",description:"Add margin to one of your copy positions from the follow's copy account (lowers its leverage; your margin account is never touched; no reduction). Not idempotent — after a timeout, read the follow before retrying, or the amount may be added twice.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement",hiddenFromDocs:!0},{name:"get_rfq_capabilities",description:"RFQ (block trading): your RFQ limits and the markets RFQ is offered on.",category:"rfq",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_rfq",description:"RFQ: an RFQ's status — the taker's view and outcome, or the maker's own quote and last-look selection.",category:"rfq",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_rfqs",description:"RFQ: your RFQs as the taker, newest first, with each one's state and outcome.",category:"rfq",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"create_rfq",description:"RFQ: request quotes for a size on a market (two-way unless a side is given). The SDK supplies an idempotency key if omitted.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"accept_rfq",description:"RFQ: accept one side of the taker view you last saw. Binding: it executes after the makers' last look. The SDK supplies an idempotency key if omitted.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_rfq",description:"RFQ: cancel an RFQ you have not accepted, before its deadline.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"upsert_rfq_quote",description:"RFQ: as maker, place or replace your quote (a bid, an ask or both), naming your current version. The SDK supplies an idempotency key if omitted.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"withdraw_rfq_quote",description:"RFQ: as maker, withdraw your current quote, naming your current version.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"respond_rfq_last_look",description:"RFQ: as a selected maker, reject or improve your frozen terms before the last-look deadline. Silence executes.",category:"rfq",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{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"}],m6e=us.map((e)=>e.name),T8=us.filter((e)=>e.authMode==="public").map((e)=>e.name),h6e=us.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),g6e=us.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),y6e=us.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),b6e=us.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),v8=us.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var $he=new Map(us.map((e)=>[e.name,e.sideEffect]));function _8(e){let t=$he.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var E8={read:0,"market-maker":1,full:2},gA=T8,yA=Object.fromEntries(us.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),P8=Object.fromEntries(Object.entries(yA).map(([e,t])=>[e,t.capability])),S6e=new Set(v8);function R8(e){let t=yA[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function A8(e){return R8(e)==="read"}function k8(e,t){if(t.network==="mainnet"&&yA[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(gA.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return E8[t.capability]>=E8[R8(e)]}var zhe=new Set([...gA,...Object.keys(P8)]),Dhe={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 I8(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function yl(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 n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!mw.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${mw.join(", ")}.`);let c=a||"read",u=I8(e.MONACO_TOOL_ALLOWLIST),d=I8(e.MONACO_TOOL_DENYLIST),f=[...u,...d].filter((y)=>!zhe.has(y)).length;if(f>0)throw Error(`${f} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||Dhe[s],g=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).");g=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:u,deny:d,delegatedOwnerUserId:g}}var hw=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var zp=D(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),bl=D(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),xl=D(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),_g=D(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),M8=D(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),bA=D(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),wl=D(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Dp=D(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),De=p().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"}),ye=zN({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),pa=ll.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),B8=_().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Fp=_().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),L8=_().int().min(0,"Slippage tolerance must be at least 0 bps").max(1000,"Slippage tolerance cannot exceed 1000 bps"),Fhe=_().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),gw=b({triggerPrice:De,orderType:Dp,limitPrice:De.optional(),quantity:De.optional(),closePosition:Z().optional(),timeInForce:bA.optional(),slippageToleranceBps:Fp.optional(),expiresAt:pa.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"]}),qhe=_().int("trailBps must be an integer number of basis points").min(10,"trailBps must be at least 10 bps").max(2000,"trailBps cannot exceed 2000 bps"),xA=b({trailBps:qhe,activationPrice:De.optional(),quantity:De.optional(),closePosition:Z().optional(),slippageToleranceBps:Fp.optional(),expiresAt:pa.optional()}).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"]}),N8=xA,yw=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0||e?.trailingStop!==void 0,wA=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),Eg=p().trim().min(1,"strategyKey cannot be empty").max(64,"strategyKey must be a sub-account key: letters, digits, _ - . :, up to 64 characters").regex(/^[A-Za-z0-9_.:-]+$/,"strategyKey must be a sub-account key: letters, digits, _ - . :, up to 64 characters"),Pg=Eg.refine((e)=>!e.toLowerCase().startsWith("copy:"),"strategy keys starting with copy: are reserved"),ls=p().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),$8=b({tradingPairId:ye,side:zp,quantity:De,price:De,options:b({idempotencyKey:ls.optional(),tradingMode:bl.optional(),useMasterBalance:Z().optional(),expirationDate:pa.optional(),timeInForce:M8.optional(),marginAccountId:ye.optional(),marginMode:xl.optional(),riskBucketId:ye.optional(),riskBucketCollateral:De.optional(),strategyKey:Eg.optional(),positionSide:_g.optional(),leverage:De.optional(),reduceOnly:Z().optional(),postOnly:Z().optional(),selfTradePreventionMode:wl.optional(),takeProfit:gw.optional(),stopLoss:gw.optional(),trailingStop:N8.optional()}).optional()}).refine((e)=>wA(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)=>!yw(e.options)||e.options?.tradingMode!=="SPOT",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!yw(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode!=="SPOT",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode!=="SPOT",{message:"marginMode 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?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).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"]}),z8=b({tradingPairId:ye,side:zp,quantity:De,options:b({idempotencyKey:ls.optional(),tradingMode:bl.optional(),slippageTolerance:B8,marginAccountId:ye.optional(),marginMode:xl.optional(),riskBucketId:ye.optional(),riskBucketCollateral:De.optional(),strategyKey:Eg.optional(),positionSide:_g.optional(),leverage:De.optional(),reduceOnly:Z().optional(),selfTradePreventionMode:wl.optional(),takeProfit:gw.optional(),stopLoss:gw.optional(),trailingStop:N8.optional()}).optional()}).refine((e)=>wA(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)=>!yw(e.options)||e.options?.tradingMode!=="SPOT",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!yw(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode!=="SPOT",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode!=="SPOT",{message:"marginMode 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?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).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"]}),D8=b({orderId:ye,remainingQuantityTarget:De.optional()}),F8=b({orderId:ye,newOrder:b({price:De.optional(),quantity:De.optional(),useMasterBalance:Z().optional(),postOnly:Z().optional(),selfTradePreventionMode:wl.optional()})}),q8=b({page:ut().optional(),status:bt([D(hw),Q(D(hw)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:ye.optional(),tradingMode:bl.optional(),marginAccountId:ye.optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),C6e=D(["STOP_LOSS","TAKE_PROFIT","TRAILING_STOP"],{message:'conditionType must be "STOP_LOSS", "TAKE_PROFIT", or "TRAILING_STOP"'}),O6e=D(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),Uhe=D(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),U8=D(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),SA=b({conditionalOrderId:ye}),j8=b({page:ut().optional(),marginAccountId:ye.optional(),tradingPairId:ye.optional(),state:Uhe.optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),jhe=D(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),Hhe=bt([_().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),p().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Ghe=2592000000,H8=b({tradingPairId:ye,side:zp,quantity:De,options:b({durationSeconds:Hhe.optional(),startTime:pa.optional(),endTime:pa.optional(),limitPrice:De.optional(),slippageToleranceBps:Fhe.optional(),randomize:Z().optional(),executionStyle:D(["TAKER","PASSIVE"]).optional(),reduceOnly:Z().optional(),tradingMode:bl.optional(),marginAccountId:ye.optional(),riskBucketId:ye.optional(),marginMode:xl.optional(),leverage:De.optional(),strategyKey:Eg.optional(),useMasterBalance:Z().optional(),clientTwapId:p().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:De.optional(),triggerDirection:D(["ABOVE","BELOW"]).optional(),conditionalExpiry:pa.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!=="SPOT",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode!=="SPOT",{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.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).refine((e)=>e.options.triggerPrice!==void 0===(e.options.triggerDirection!==void 0),{message:"triggerPrice and triggerDirection are both-or-neither",path:["options","triggerDirection"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.durationSeconds!==void 0,{message:"conditional TWAP (triggerPrice) requires durationSeconds — the window floats from the trigger instant",path:["options","durationSeconds"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.startTime===void 0&&e.options.endTime===void 0,{message:"triggerPrice is incompatible with startTime/endTime",path:["options","triggerPrice"]}).refine((e)=>e.options.conditionalExpiry===void 0||e.options.triggerPrice!==void 0,{message:"conditionalExpiry is only valid together with triggerPrice",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r>Date.now()},{message:"conditionalExpiry must be in the future",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r-Date.now()<=Ghe},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),C8=5000,O8=900000,G8=b({timeoutMs:_().int().refine((e)=>e===0||e>=C8&&e<=O8,{message:`timeoutMs must be 0 or between ${C8} and ${O8}`}),options:b({tradingPairId:ye.optional()}).strict().optional()}).strict(),xw=b({twapOrderId:ye}),V8=b({page:ut().optional(),state:jhe.optional(),tradingPairId:ye.optional(),marginAccountId:ye.optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),W8=b({page:ut().optional(),twapOrderId:ye,orderBy:D(["ASC","DESC"]).optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Vhe=b({tradingPairId:ye,orderType:Dp,side:zp,price:De.optional(),quantity:De,idempotencyKey:ls.optional(),tradingMode:bl.optional(),slippageTolerance:B8,useMasterBalance:Z().optional(),expirationDate:pa.optional(),timeInForce:M8.optional(),marginAccountId:ye.optional(),marginMode:xl.optional(),riskBucketId:ye.optional(),riskBucketCollateral:De.optional(),strategyKey:Eg.optional(),positionSide:_g.optional(),leverage:De.optional(),reduceOnly:Z().optional(),postOnly:Z().optional(),selfTradePreventionMode:wl.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!=="SPOT",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode!=="SPOT",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).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.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)=>wA(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"]}),bw=100,Z8=b({orders:Q(Vhe).min(1,"At least one order is required").max(bw,`At most ${bw} orders per batch request`)}),Whe=b({orderId:ye,price:De.optional(),quantity:De.optional(),useMasterBalance:Z().optional(),postOnly:Z().optional(),selfTradePreventionMode:wl.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),K8=b({orders:Q(Whe).min(1,"At least one order is required").max(bw,`At most ${bw} orders per batch request`)});var Zhe=b({applicationId:p().uuid(),enrolled:Z(),payoutAddress:p().nullable().optional(),buildercodesEnabled:Z(),buildercodesBudgetBps:_().int().min(0).max(1e4),builderFeeEnabled:Z(),builderFeeBps:_().int().min(0).max(100),builderFeeCapBps:_().int().min(0).max(100),changesRemaining:_().int().min(0).max(500),nextChangeAllowedAt:p().nullable().optional(),builderMakerFeeBps:_().int().min(0).max(100).optional(),builderFeeRulesPerSave:_().int().min(0).optional(),builderFeeRulesPerApplication:_().int().min(0).optional(),builderFeeRuleCount:_().int().min(0).optional(),builderFeeRulesEnabled:Z().optional()}),vA=b({bps:_().int().min(0).max(100),makerBps:_().int().min(0).max(100).optional()}),Khe=b({builderFeeBps:_().int().min(0).max(100),previousBuilderFeeBps:_().int().min(0).max(100),changesRemaining:_().int().min(0).max(500),nextChangeAllowedAt:p().nullable().optional(),builderMakerFeeBps:_().int().min(0).max(100).optional(),previousBuilderMakerFeeBps:_().int().min(0).max(100).optional()}),Q8=D(["BUILDER","ADMIN"]),Y8=b({actorType:Q8,actor:p(),oldBps:_().int().min(0).max(100),newBps:_().int().min(0).max(100),createdAt:p(),oldMakerBps:_().int().min(0).max(100).optional(),newMakerBps:_().int().min(0).max(100).optional()}),_A=b({pageSize:_().int().min(1).max(100).optional(),pageToken:p().optional()}),Qhe=b({changes:Q(Y8),nextPageToken:p()}),Sw=D(["REVENUE_SHARE","BUILDER_FEE","BUILDER_MAKER_FEE"]),EA=b({page:ut().optional(),pageSize:_().int().min(1).max(1000).optional(),pageToken:p().optional(),kind:Sw.optional()}),J8=b({tradeId:p().uuid(),payoutAddress:p(),token:p(),amount:p(),appliedBps:_().int(),appliedCbps:_().int().optional(),createdAt:p(),kind:Sw.optional()}),Yhe=b({payouts:Q(J8),total:_().int().nonnegative(),pageSize:_().int().positive(),totalPages:_().int().nonnegative(),nextPageToken:p()}),TA=b({token:p(),totalAmount:p(),payoutCount:_().int().nonnegative(),lastCreditedAt:p()}),X8=b({token:p(),kind:Sw,totalAmount:p(),payoutCount:_().int().nonnegative(),lastCreditedAt:p()}),Jhe=b({totalPayouts:_().int().nonnegative(),lastCreditedAt:p().nullable().optional(),byToken:Q(TA),byTokenAndKind:Q(X8).optional(),builderFeeByToken:Q(TA).optional()}),e3=b({token:p(),available:p()}),Xhe=b({balances:Q(e3)}),PA=b({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string"),idempotencyKey:ls.optional()}),ege=b({payoutBalance:p(),tradingBalance:p()}),RA=D(["CLOB","RFQ","BOTH"]),t3=D(["CLOB","RFQ"]),AA=D(["SPOT","MARGIN"]),r3=D(["BUILDER","OVERRIDE"]),kA=p().regex(/^0x[0-9a-fA-F]{40}$/,"walletAddress must be a 0x-prefixed EVM address"),Wc=_().int().min(0).max(1e4),fa=b({walletAddress:kA.nullable().optional(),tradingPairId:p().uuid().nullable().optional(),marketType:AA.nullable().optional(),track:RA}).refine((e)=>!(e.tradingPairId&&e.marketType),{message:"set at most one of tradingPairId and marketType"}),ww=b({id:p().uuid(),scope:fa,source:r3,makerCbps:Wc,takerCbps:Wc,makerClamped:Z(),takerClamped:Z(),editable:Z(),note:p().nullable().optional(),updatedAt:p()}),IA=b({id:p().uuid(),scope:fa,forAllApplications:Z(),capCbps:Wc,updatedAt:p()}),CA=b({id:p().uuid(),scope:fa,forAllApplications:Z(),revshareBps:_().int().min(0).max(1e4),updatedAt:p()}),OA=b({pageSize:_().int().min(1).max(100).optional(),pageToken:p().optional(),walletAddress:kA.optional(),tradingPairId:p().uuid().optional(),marketType:AA.optional(),track:RA.optional()}),tge=b({addOnRules:Q(ww),capRules:Q(IA),revshareRules:Q(CA),nextPageToken:p(),ruleCount:_().int().min(0),rulesPerApplication:_().int().min(0)}),MA=b({scope:fa,makerCbps:Wc,takerCbps:Wc}),BA=b({upserts:Q(MA).optional(),deletes:Q(fa).optional(),note:p().optional()}),LA=b({op:D(["SET","DELETE"]),scope:fa,makerCbpsBefore:_().int().nullable().optional(),takerCbpsBefore:_().int().nullable().optional(),makerCbpsAfter:_().int().nullable().optional(),takerCbpsAfter:_().int().nullable().optional()}),rge=b({changes:Q(LA),changesRemaining:_().int().min(0).max(500),nextChangeAllowedAt:p().nullable().optional()}),NA=b({upserts:Q(MA).optional(),deletes:Q(fa).optional()}),n3=b({change:LA,shadowedByOverride:Z(),narrowerRulesKept:Q(fa),makerClamped:Z(),takerClamped:Z(),walletHasAccount:Z().nullable().optional()}),nge=b({entries:Q(n3),changesRemaining:_().int().min(0).max(500),refusal:p().nullable().optional()}),$A=b({walletAddress:kA,tradingPairId:p().uuid(),track:t3}),oge=b({makerCbps:Wc,takerCbps:Wc,makerClamped:Z(),takerClamped:Z(),builderFeeEnabled:Z(),capCbps:Wc,revshareBps:_().int().min(0).max(1e4),winningRule:ww.nullable().optional(),matchingRules:Q(ww),winningCap:IA.nullable().optional(),winningRevshare:CA.nullable().optional()});function mi(){return p()}var zA=b({walletAddress:p(),handle:p().nullish(),display:p()}),DA=b({leader:zA,status:mi(),shareBps:_(),bio:p(),minAllocation:p().nullish(),registeredAt:p()}),FA=b({followerCount:_(),allocated:p(),aumEquity:p().nullish()}),qA=b({window:mi(),pnl:p(),roiPct:p().nullish(),maxDrawdownPct:p().nullish(),winRatePct:p().nullish(),closedTrades:_()}),ige=b({profile:DA,followSummary:FA,stats:Q(qA)}),o3=b({profile:DA,followSummary:FA,stats:qA}),sge=b({leaders:Q(o3),nextPageToken:p(),asOf:p()}),age=b({created:Z(),status:mi(),shareBps:_()}),i3=b({walletAddress:p(),display:p(),status:mi(),allocation:p(),startedAt:p()}),cge=b({followers:Q(i3),nextPageToken:p()}),s3=b({tradingPairId:p(),positionSide:p(),action:mi(),size:p().nullish(),exitPrice:p().nullish(),entryPrice:p().nullish(),realizedPnl:p().nullish(),netRealizedPnl:p().nullish(),realizedRoe:p().nullish(),closedAt:p()}),uge=b({closedTrades:Q(s3),nextPageToken:p()}),UA=b({tradingPairId:p(),side:p(),size:p(),entryPrice:p(),markPrice:p().nullish(),unrealizedPnl:p().nullish(),leverage:p().nullish(),marginMode:p()}),lge=b({positions:Q(UA)}),jA=b({followId:p(),leader:zA,status:mi(),marginModePolicy:mi(),sizingMode:mi(),sizingParam:p().nullish(),leverageMode:mi(),fixedLeverage:p().nullish(),allocation:p(),slPct:p().nullish(),copyExisting:Z(),tradingPairIds:Q(p()),consecutiveSkips:_(),copyRiskBucketId:p(),startedAt:p(),stoppedAt:p().nullish(),stopReason:mi().nullish()}),dge=b({follows:Q(jA),nextPageToken:p()}),a3=b({tradingPairId:p(),reason:mi(),requestedQuantity:p(),skippedAt:p()}),pge=b({follow:jA,recentSkips:Q(a3),copyAccountEquity:p().nullish()}),fge=b({positions:Q(UA)}),mge=b({followId:p(),copyRiskBucketId:p(),created:Z()}),hge=b({estimatedMargin:p(),estimatedFee:p(),copiedPositions:_(),skippedPositions:_(),truncated:Z()}),gge=b({followId:p()}),c3=b({followId:p(),closeOrdersPlaced:_(),positionsNotClosed:_()}),u3=b({followId:p(),reason:p()}),yge=b({follows:Q(c3),stoppingFollowIds:Q(p()),failedFollows:Q(u3)}),bge=b({followId:p(),tradingPairId:p(),riskBucketId:p(),positionId:p(),positionMargin:p(),copyAccountAvailable:p()});var HA=b({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty"),side:D(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:p().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:p().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:D(["LIMIT","MARKET"]).optional(),slippageToleranceBps:_().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:_c.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),xge=b({applicationName:p().nullable().optional(),applicationTakerFee:p(),applicationTakerFeeBps:_(),applicationTakerFeeCbps:_().optional(),buyOrderLockAmount:p().nullable().optional(),makerTotalReceipt:p(),applicationMakerFee:p().optional(),applicationMakerFeeBps:_().optional(),applicationMakerFeeCbps:_().optional(),builderFeeClamped:Z().optional(),builderMakerFeeClamped:Z().optional(),monacoMakerRebate:p(),monacoMakerRebateBpsExact:p(),monacoTakerFee:p(),monacoTakerFeeBpsExact:p(),notional:p(),takerTotalPayment:p(),totalTakerFees:p(),maxQuantity:p().nullable(),maxQuantityRaw:p().nullable(),slippageToleranceBps:_().nullable()}),GA=b({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty")}),VA=b({tierLevel:_().int(),minVolumeThreshold:p(),makerFeeBps:p(),takerFeeBps:p()}),wge=b({currentTierLevel:_().int(),weightedVolume14d:p(),spotVolume14d:p(),perpVolume14d:p(),volumeToNextTier:p().nullable().optional(),nextTierLevel:_().int().nullable().optional(),feeSchedule:Q(VA),rateSource:D(["volume","tier_override","custom"]),makerFeeBps:p(),takerFeeBps:p(),rateScope:D(["wallet_application","wallet","application","pair","market_type"]),updatedAt:ll.datetime().nullable().optional()}),WA=b({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty")}),Sge=b({tradingPairId:p(),feeSchedule:Q(VA)});function ma(){return p()}var ZA=b({price:p(),capacity:p()}),Tge=b({rfqId:p(),tradingPairId:p(),product:ma().nullish(),quantity:p(),createdAtMs:_(),deadlineAtMs:_(),side:ma().nullish(),quoteSide:ma().nullish(),leverage:p().nullish(),marginMode:p().nullish()}),KA=b({vwap:p(),grossVwap:p(),asOfMs:_(),levels:_()}),l3=b({vwap:p(),availableQuantity:p(),grossVwap:p().nullish(),estimatedMonacoFee:p().nullish(),estimatedBuilderFee:p().nullish(),estimatedTotalFee:p().nullish(),book:KA.nullish()}),vge=b({viewVersion:_(),bid:l3.nullish(),ask:l3.nullish(),asOfMs:_(),monacoFeeCbps:_().nullish(),builderFeeCbps:_().nullish()}),_ge=b({executionId:p(),price:p(),quantity:p(),fee:p(),monacoFee:p().nullish(),builderFee:p().nullish()}),Ege=b({executedQuantity:p(),unfilledQuantity:p(),vwap:p(),fills:Q(_ge),allInVwap:p().nullish(),bookAtFill:KA.nullish(),bookAtFillFullSize:Z().nullish()}),Pge=b({executionId:p(),price:p(),quantity:p(),fee:p().nullish(),monacoFee:p().nullish(),builderFee:p().nullish()}),Rge=b({viewVersion:_(),acceptedAtMs:_(),vwap:p().nullish(),grossVwap:p().nullish(),availableQuantity:p().nullish(),monacoFeeCbps:_(),builderFeeCbps:_().nullish(),book:KA.nullish(),bookFullSize:Z().nullish()}),Age=b({side:ma(),code:p(),reason:p()}),kge=b({rfqId:p(),quoteId:p(),version:_(),bid:ZA.nullish(),ask:ZA.nullish(),issuedAtMs:_(),validUntilMs:_(),leverage:p().nullish(),marginMode:p().nullish(),refusedSides:Q(Age).nullish()}),Ige=b({acceptanceId:p(),takerSide:ma().nullish(),quoteId:p(),quoteVersion:_(),quantity:p(),frozenTerms:ZA.nullish(),lastLookDeadlineAtMs:_(),monacoFeeCbps:_().nullish(),maxBuilderFeeCbps:_().nullish(),estimatedNet:p().nullish()}),Cge=b({terms:Tge.nullish(),state:ma(),stateVersion:_(),acceptedSide:ma().nullish(),lastLookDeadlineAtMs:_().nullish(),view:vge.nullish(),ownQuote:kge.nullish(),ownSelection:Ige.nullish(),ownLatestVersion:_(),ownQuoteWithdrawn:Z(),outcome:Ege.nullish(),durableSequence:_(),ownFills:Q(Pge).nullish(),acceptance:Rge.nullish()}),Z6e=b({rfqs:Q(Cge),nextPageToken:p()}),Oge=b({tradingPairId:p(),product:ma().nullish(),minQuantity:p(),maxQuantity:p()}),K6e=b({protocolVersion:_(),enabled:Z(),markets:Q(Oge),requestWindowMs:_(),minQuoteValidityMs:_(),maxQuoteValidityMs:_(),lastLookMs:_(),maxNewRfqs:_(),quotaWindowMs:_(),quotaRemaining:_(),quotaRetryAfterMs:_()}),Q6e=b({rfqId:p(),version:_()}),Y6e=b({acceptanceId:p(),response:ma().nullish(),recordedAtMs:_()});var d3=b({token:p(),available:p()}),Mge=b({balances:Q(d3)}),Bge=b({code:p(),createdAt:p(),customCode:p(),isCustom:Z(),display:p()}),p3=D(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Lge=b({available:Z(),reason:Jh((e)=>e===""||e===null?void 0:e,p3.optional())}),QA=b({code:p().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")}),Nge=b({code:p()}),YA=b({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),$ge=b({rewardsBalance:p(),tradingBalance:p()}),f3=b({source:p(),sourceDisplay:p(),level:_(),amount:p(),token:p(),rateApplied:p(),createdAt:p()}),m3=b({wallet:p(),display:p(),level:_()}),zge=b({referrer:p(),referrerDisplay:p(),totalEarned:p(),rewards:Q(f3),upline:Q(m3)}),h3=b({source:p(),sourceDisplay:p(),level:_(),totalEarned:p(),token:p()}),g3=b({wallet:p(),display:p(),referredAt:p(),totalEarned:p()}),y3=b({level:_(),earned:p()}),b3=b({totalEarned:p(),level1Earned:p(),level2Earned:p(),level3Earned:p(),byLevel:Q(y3)}),JA=b({pageSize:_().int().min(1).max(500).optional(),pageToken:p().optional()}),Dge=b({earningsBySource:Q(h3),directReferees:Q(g3),summary:b3,nextPageToken:p()}),XA=b({parent:p().optional(),pageSize:_().int().min(1).max(200).optional(),pageToken:p().optional()}),x3=b({wallet:p(),display:p(),level:_(),parent:p(),referredAt:p(),refereeCount:_(),totalEarned:p()}),Fge=b({parent:p(),parentLevel:_(),nodes:Q(x3),nextPageToken:p()});var w3=p().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),ek=bt([p().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),FN().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),S3=b({assetId:ye,amount:ek,autoWait:Z().optional()}),T3=b({assetId:ye,amount:ek,autoWait:Z().optional(),target:D(["spot","margin","cross_risk_bucket"]).optional(),options:b({asErc20:Z().optional()}).optional()}),v3=b({assetId:ye,amount:ek,destination:p().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:Z().optional(),source:D(["spot","margin","cross_risk_bucket"]).optional()}),uMe=b({assetId:ye}),_3=b({page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var Rg=b({clientId:p().trim().min(1,"Client ID is required"),page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),E3=Rg.extend({status:p().trim().min(1,"Status cannot be empty").optional(),userId:ye.optional(),tradingPairId:ye.optional(),side:p().trim().min(1,"Side cannot be empty").optional(),orderType:p().trim().min(1,"Order type cannot be empty").optional()}),P3=Rg.extend({isActive:Z().optional(),accountType:p().trim().min(1,"Account type cannot be empty").optional(),address:p().trim().min(1,"Address filter cannot be empty").optional()}),R3=Rg.extend({userId:ye.optional(),transactionType:p().trim().min(1,"Transaction type cannot be empty").optional(),entryType:p().trim().min(1,"Entry type cannot be empty").optional(),assetId:ye.optional()}),A3=Rg.extend({userId:ye.optional(),assetId:ye.optional()}),k3=Rg.extend({address:w3.optional()});class I3 extends Error{issues;constructor(e){let t=e.issues.map((r)=>{let n=r.path.join(".");return`${n?`${n}: `:""}${r.message}`});super(`Validation failed:
|
|
131
131
|
- ${t.join(`
|
|
132
132
|
- `)}`);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 X(e,t){let r=e.safeParse(t);if(!r.success)throw new I3(r.error);return r.data}var Tw=p().trim().min(1,"leader handle is required"),qge=p().trim().regex(/^\d+(\.\d+)?$/,"slPct must be a decimal fraction (e.g. '0.25')").refine((e)=>{let t=Number.parseFloat(e);return t>0&&t<=1},"slPct must be greater than 0 and at most 1");function vw(e){return{pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(e,`Page size cannot exceed ${e}`).optional(),pageToken:p().optional()}}var C3=b({shareBps:_().int("shareBps must be an integer").min(0,"shareBps cannot be negative").max(1e4,"shareBps cannot exceed 10000").optional(),bio:p().refine((e)=>new TextEncoder().encode(e).length<=2000,"bio cannot exceed 2,000 bytes").optional(),status:D(["ACTIVE","PAUSED"]).optional(),minAllocation:De.optional()}).strict(),O3=b({followId:ye.optional(),leader:Tw.optional(),marginModePolicy:D(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:D(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:De.optional(),leverageMode:D(["FOLLOW","FIXED"]).optional(),fixedLeverage:De.optional(),allocation:De,slPct:qge.optional(),tradingPairIds:Q(ye).max(256,"at most 256 markets can be copied").optional(),copyExisting:Z().optional()}).strict().superRefine((e,t)=>{if(e.followId===void 0&&e.leader===void 0)t.addIssue({code:"custom",message:"leader is required when creating a follow",path:["leader"]});if(e.followId!==void 0&&e.copyExisting===!0)t.addIssue({code:"custom",message:"copyExisting applies only when creating a follow",path:["copyExisting"]});M3(e,t)});function M3(e,t){let r=e.sizingMode==="FIXED_MARGIN";if(r&&e.sizingParam===void 0)t.addIssue({code:"custom",message:"sizingParam is required for FIXED_MARGIN sizing",path:["sizingParam"]});if(!r&&e.sizingParam!==void 0)t.addIssue({code:"custom",message:"sizingParam is only accepted with FIXED_MARGIN sizing",path:["sizingParam"]});let n=e.leverageMode==="FIXED";if(n&&e.fixedLeverage===void 0)t.addIssue({code:"custom",message:"fixedLeverage is required for FIXED leverage",path:["fixedLeverage"]});if(!n&&e.fixedLeverage!==void 0)t.addIssue({code:"custom",message:"fixedLeverage is only accepted with FIXED leverage",path:["fixedLeverage"]})}var B3=b({leader:Tw,marginModePolicy:D(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:D(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:De.optional(),leverageMode:D(["FOLLOW","FIXED"]).optional(),fixedLeverage:De.optional(),allocation:De,tradingPairIds:Q(ye).max(256,"at most 256 markets can be copied").optional()}).strict().superRefine((e,t)=>M3(e,t)),L3=b({followId:ye,tradingPairId:ye,amount:De}).strict(),N3=b({sort:D(["roi","pnl","followers","allocated","aum","win_rate"]).optional(),window:D(["7d","30d","90d","all"]).optional(),...vw(100)}).strict(),$3=b(vw(100)).strict(),z3=b(vw(1000)).strict(),D3=b(vw(1000)).strict();var F3=b({page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var tk=b({page:ut().optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),U3=tk.extend({state:p().trim().min(1,"State cannot be empty").optional(),tradingPairId:ye.optional()}),j3=b({marginAccountId:ye,tradingPairId:ye.optional()}),H3=b({tradingPairId:ye.optional()}).optional(),G3=b({asset:p().trim().min(1,"Asset cannot be empty").optional()}).optional(),Uge=b({asset:p().trim().min(1,"Asset cannot be empty"),amount:De,tradingPairId:ye.optional(),strategyKey:Pg.optional(),marginMode:D(["ISOLATED","CROSS"]).optional(),idempotencyKey:ls.optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),_w=b({asset:p().trim().min(1,"Asset cannot be empty"),amount:De,idempotencyKey:ls.optional()}),jge=b({tradingPairId:ye,strategyKey:Pg.optional()}),V3=jge.extend({marginMode:Re("ISOLATED").optional(),marginAccountId:ye.optional(),selectedTradingPairIds:ut().optional(),applyToPositionMargin:Z().optional()}),Hge=b({marginMode:Re("CROSS"),marginAccountId:ye.optional(),selectedTradingPairIds:ut().optional(),strategyKey:Pg.optional()}),Gge=b({marginMode:Re("CROSS"),marginAccountId:ye.optional(),selectedTradingPairIds:ut().optional(),strategyKey:Pg.optional(),tradingPairId:ut().optional()}),rk=b({marginAccountId:ye,request:Uge}),W3=b({request:_w}),Vge=b({marginMode:D(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:$t().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is the markets where the bucket has an open position, so a funding call has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),Z3=b({request:Vge.pipe(bt([_w.merge(V3).strict(),_w.merge(Gge).strict()]))}),K3=b({request:_w}),Q3=tk.extend({marginAccountId:ye,movementType:p().trim().min(1,"Movement type cannot be empty").optional()}),Y3=tk.extend({movementType:p().trim().min(1,"Movement type cannot be empty").optional()}).optional(),nk=b({tradingPairId:ye,side:zp,positionSide:_g.optional(),orderType:Dp,price:De.optional(),quantity:De,leverage:De.optional(),reduceOnly:Z().optional(),slippageToleranceBps:L8.optional()}),ok=(e,t)=>{if(e.orderType!=="MARKET"&&e.slippageToleranceBps!==void 0)t.addIssue({code:_c.custom,message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]});if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:_c.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:_c.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},J3=nk.strict().superRefine(ok),Wge=nk.merge(V3).strict().superRefine(ok),Zge=nk.merge(Hge).strict().superRefine(ok),Kge=b({marginMode:D(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:$t().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS preview: cross scope is the markets where the bucket has an open position, so a preview has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),Qge=Kge.pipe(bt([Wge,Zge])),X3=b({marginAccountId:ye,request:J3}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),eU=b({request:J3}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),tU=b({request:Qge}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),rU=b({request:b({subaccountKey:p().trim().min(1,"subaccountKey is required").max(64,"subaccountKey must be at most 64 characters").regex(/^[A-Za-z0-9_.:-]+$/,"subaccountKey may contain only letters, digits, '_', '-', '.' and ':'").refine((e)=>!e.toLowerCase().startsWith("copy:"),"sub-account keys starting with copy: are reserved").refine((e)=>e!=="default","default names the default margin account"),label:p().optional()}).strict()}),nU=b({marginAccountId:ye}),ik=b({marginAccountId:ye,amount:De,idempotencyKey:ls.optional()}),oU=b({marginAccountId:ye}),q3=bt([b({wallet:Re(!0)}).strict(),b({marginAccountId:ye,riskBucketId:ye.optional()}).strict()]),iU=b({request:b({asset:p().trim().min(1,"Asset is required"),amount:De,from:q3,to:q3,idempotencyKey:ls.optional()}).strict()});var sU=D(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),Yge=31536000000,Jge=946684800000,Ew=_().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(Jge,{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()+Yge,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),PMe=b({tradingPairId:ye,interval:sU,startTime:Ew,endTime:Ew}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),RMe=p().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")'}),Xge=_().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),aU=b({tradingPairId:ye,interval:sU,startTime:Ew.optional(),endTime:Ew.optional(),limit:Xge,priceType:D(["trade","mark","reference"]).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 AMe=b({tradingPairId:ye}),kMe=b({query:p().min(1,"Search query cannot be empty").optional(),pageSize:_().int().min(1).max(100).optional(),page:_().int().min(1).optional()}),Qn=b({tradingPairId:ye}),cU=b({page:ut().optional(),startTime:p().optional(),endTime:p().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:D(["ASC","DESC"],{message:'orderBy must be "ASC" or "DESC"'}).optional()}),uU=cU,lU=cU,dU=b({page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),pU=dU.extend({executionSource:D(["RFQ","CLOB"]).optional()}),fU=dU.extend({takerApplicationId:ye.optional()});var hU=b({page:ut().optional(),pageSize:_().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),eye=D(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),tye=D(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),Ag=b({positionId:ye}),gU=hU.extend({marginAccountId:ye.optional(),tradingPairId:ye.optional(),status:eye.optional()}),yU=Ag,bU=Ag.extend({request:b({closeType:tye,limitPrice:De.optional(),slippageToleranceBps:Fp.optional(),quantity:De.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"]}),xU=b({tradingPairId:ye.optional(),tradingPairIds:Q(ye).min(1,{message:"tradingPairIds must list at least one trading pair; omit it to close every pair"}).max(256,{message:"tradingPairIds accepts at most 256 trading pairs"}).optional(),side:U8.optional(),slippageToleranceBps:Fp.optional()}).strict().refine((e)=>e.tradingPairId===void 0||e.tradingPairIds===void 0,{message:"Pass tradingPairId or tradingPairIds, not both",path:["tradingPairIds"]}),wU=Ag,mU=b({triggerPrice:De,orderType:Dp,limitPrice:De.optional(),quantity:De.optional(),closePosition:Z().optional(),timeInForce:bA.optional(),slippageToleranceBps:Fp.optional(),expiresAt:pa.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"]}),SU=Ag.extend({request:b({takeProfit:mU.optional(),stopLoss:mU.optional(),trailingStop:xA.optional(),oco:Z().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0||e.trailingStop!==void 0,{message:"At least one of takeProfit, stopLoss, or trailingStop 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"]})}),TU=hU.extend({positionId:ye.optional(),marginAccountId:ye.optional(),tradingPairId:ye.optional(),reductionOnly:Z().optional()}),rye=D(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),vU=Ag.extend({params:b({interval:rye,startTime:_().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:_().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 nye=D(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),oye=D(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),_U=b({mode:wl}),EU=b({page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:D(["ASC","DESC"]).optional(),entryType:nye.optional(),transactionType:oye.optional(),assetId:ye.optional()}),PU=b({page:ut().optional(),pageSize:_().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:ye.optional(),marginAccountId:ye.optional(),orderId:ye.optional(),pageToken:p().optional()}),RU=b({page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),AU=b({page:ut().optional(),pageSize:_().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),tradingPairId:ye.optional(),positionId:ye.optional(),marginAccountId:ye.optional()}),kU=b({tradingMode:bl.optional()});var IU=D(["BUY","SELL"]),iye=D(["SPOT","PERPETUAL"]),qp=p().regex(/^[A-Za-z0-9._:-]{1,64}$/,"idempotencyKey must be 1-64 letters, digits, or . _ : - without whitespace"),ak=_().int("version must be an integer").min(0,"version cannot be negative"),sk=b({price:De,capacity:De}).strict(),CU=b({tradingPairId:ye,product:iye,quantity:De,side:IU.optional(),leverage:De.optional(),marginMode:xl.optional(),idempotencyKey:qp.optional()}).strict(),OU=b({side:IU,viewVersion:ak,reduceOnly:Z().optional(),idempotencyKey:qp.optional()}).strict(),MU=b({idempotencyKey:qp.optional()}).strict(),BU=b({pageSize:_().int().min(1).max(100).optional(),pageToken:p().min(1).optional()}).strict(),LU=b({expectedVersion:ak,bid:sk.optional(),ask:sk.optional(),validityMs:_().int("validityMs must be an integer").min(15000,"validityMs must be at least 15000").max(60000,"validityMs cannot exceed 60000").optional(),leverage:De.optional(),marginMode:xl.optional(),idempotencyKey:qp.optional()}).strict().refine((e)=>e.bid!==void 0||e.ask!==void 0,"a quote needs a bid, an ask or both"),NU=b({expectedVersion:ak,idempotencyKey:qp.optional()}).strict(),$U=b({acceptanceId:ye,response:D(["REJECT","IMPROVE"]),improvedTerms:sk.optional(),idempotencyKey:qp.optional()}).strict().refine((e)=>e.response==="IMPROVE"===(e.improvedTerms!==void 0),"improvedTerms is required for IMPROVE and not allowed for REJECT");function Pw(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ck=(e)=>e?`"${e}" `:"";function kg(e,t=""){if(typeof e!=="number")throw TypeError(ck(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ck(t)+"expected integer >= 0, got "+e);return e}function ds(e,t,r=""){if(Pw(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)kg(t,"length");let n=Pw(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=ck(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var sye=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},zU=(e,t)=>{sye(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function uk(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function FU(e,t){ds(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function Up(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Rw(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function hi(e,t){return e<<32-t|e>>>t}var qU=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),aye=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bo(e){if(ds(e),qU)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=aye[e[r]];return t}function DU(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function ha(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(qU)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=DU(e.charCodeAt(i)),a=DU(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function Sl(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{Up(t)}}function lk(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];ds(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function cye(e,t,r="opts"){if(zU(e,"defaults"),t!==void 0)zU(t,r);return Object.assign(Object.create(null),e,t)}function dk(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=cye({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}function UU(e=32){kg(e,"bytesLength");let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var pk=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var tu=Tn(kw(),1);var Iw=(()=>BigInt(4294967295))(),ej=BigInt(32);function vye(e,t=!1){if(t)return{h:Number(e&Iw),l:Number(e>>ej&Iw)};return{h:Number(e>>ej&Iw)|0,l:Number(e&Iw)|0}}function tj(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=vye(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var _ye=(e)=>e/4294967296|0,Eye=(e)=>e>>>0;function rj(e,t,r,n){let o=_ye(r),i=Eye(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}var xk=(e,t,r)=>e>>>r,wk=(e,t,r)=>e<<32-r|t>>>r,Tl=(e,t,r)=>e>>>r|t<<32-r,vl=(e,t,r)=>e<<32-r|t>>>r,Ig=(e,t,r)=>e<<64-r|t>>>r-32,Cg=(e,t,r)=>e>>>r-32|t<<64-r;function ps(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/4294967296|0)|0,l:o|0}}var nj=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),oj=(e,t,r,n)=>t+r+n+(e/4294967296|0)|0,ij=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),sj=(e,t,r,n,o)=>t+r+n+o+(e/4294967296|0)|0,aj=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),cj=(e,t,r,n,o,i)=>t+r+n+o+i+(e/4294967296|0)|0;function uj(e,t,r){return e&t^~e&r}function lj(e,t,r){return e&t^e&r^t&r}class Cw{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Rw(this.buffer)}update(e){uk(this),ds(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=Rw(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){uk(this),FU(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);rj(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:Rw(e),a=this.outputLen,c=a/4,u=this.get();if(a%4||c>u.length)throw Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var dj=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var pj=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Rye=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Zc=new Uint32Array(64);class fj extends Cw{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Zc[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Zc[d-15],m=Zc[d-2],g=hi(f,7)^hi(f,18)^f>>>3,y=hi(m,17)^hi(m,19)^m>>>10;Zc[d]=y+Zc[d-7]+g+Zc[d-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let f=hi(s,6)^hi(s,11)^hi(s,25),m=u+f+uj(s,a,c)+Rye[d]+Zc[d]|0,y=(hi(r,2)^hi(r,13)^hi(r,22))+lj(r,n,o)|0;u=c,c=a,a=s,s=i+m|0,i=o,o=n,n=r,r=m+y|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,o,i,s,a,c,u)}roundClean(){Up(Zc)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Up(this.buffer)}}class mj extends fj{constructor(){super(32,dj)}}var hj=(()=>tj(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),Aye=(()=>hj[0])(),kye=(()=>hj[1])(),Kc=new Uint32Array(80),Qc=new Uint32Array(80);class gj extends Cw{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1);this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:f,Gh:m,Gl:g,Hh:y,Hl:x}=this;return[e,t,r,n,o,i,s,a,c,u,d,f,m,g,y,x]}set(e,t,r,n,o,i,s,a,c,u,d,f,m,g,y,x){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=o|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=g|0,this.Hh=y|0,this.Hl=x|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let E=0;E<16;E++,t+=4)Kc[E]=e.getUint32(t),Qc[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let v=Kc[E-15]|0,P=Qc[E-15]|0,R=Tl(v,P,1)^Tl(v,P,8)^xk(v,P,7),C=vl(v,P,1)^vl(v,P,8)^wk(v,P,7),N=Kc[E-2]|0,q=Qc[E-2]|0,M=Tl(N,q,19)^Ig(N,q,61)^xk(N,q,6),k=vl(N,q,19)^Cg(N,q,61)^wk(N,q,6),U=ij(C,k,Qc[E-7],Qc[E-16]),K=sj(U,R,M,Kc[E-7],Kc[E-16]);Kc[E]=K|0,Qc[E]=U|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:f,Fh:m,Fl:g,Gh:y,Gl:x,Hh:S,Hl:T}=this;for(let E=0;E<80;E++){let v=Tl(d,f,14)^Tl(d,f,18)^Ig(d,f,41),P=vl(d,f,14)^vl(d,f,18)^Cg(d,f,41),R=d&m^~d&y,C=f&g^~f&x,N=aj(T,P,C,kye[E],Qc[E]),q=cj(N,S,v,R,Aye[E],Kc[E]),M=N|0,k=Tl(r,n,28)^Ig(r,n,34)^Ig(r,n,39),U=vl(r,n,28)^Cg(r,n,34)^Cg(r,n,39),K=r&o^r&s^o&s,oe=n&i^n&a^i&a;S=y|0,T=x|0,y=m|0,x=g|0,m=d|0,g=f|0,{h:d,l:f}=ps(c|0,u|0,q|0,M|0),c=s|0,u=a|0,s=o|0,a=i|0,o=r|0,i=n|0;let j=nj(M,U,oe);r=oj(j,q,k,K),n=j|0}({h:r,l:n}=ps(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=ps(this.Bh|0,this.Bl|0,o|0,i|0),{h:s,l:a}=ps(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=ps(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l:f}=ps(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:g}=ps(this.Fh|0,this.Fl|0,m|0,g|0),{h:y,l:x}=ps(this.Gh|0,this.Gl|0,y|0,x|0),{h:S,l:T}=ps(this.Hh|0,this.Hl|0,S|0,T|0),this.set(r,n,o,i,s,a,c,u,d,f,m,g,y,x,S,T)}roundClean(){Up(Kc,Qc)}destroy(){this.destroyed=!0,Up(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class yj extends gj{constructor(){super(64,pj)}}var Ow=dk(()=>new mj,pk(1));var Sk=dk(()=>new yj,pk(3));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Bw(e,t,r=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let n=0;n<e.length;n++)r(e[n],`${t}[${n}]`);return e}var Yn=(e,t,r)=>ds(e,t,r),Tk=kg;function Yc(e,t="object"){if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function _l(e,t){if(typeof e!=="function")throw TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var xj=bo,vk=(...e)=>lk(...e),wj=(e)=>ha(e),Og=Pw,_k=(e)=>UU(e),Mw=BigInt(0),bj=BigInt(1),Iye=(e)=>e?`"${e}" `:"";function ga(e,t=""){if(typeof e!=="boolean")throw TypeError(Iye(t)+"expected boolean, got type="+typeof e);return e}function Cye(e){if(typeof e==="bigint"){if(!Jc(e))throw RangeError("positive bigint expected, got "+e)}else Tk(e);return e}function jp(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw RangeError(r+"expected safe integer, got "+e)}}function Sj(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?Mw:BigInt("0x"+e)}function Lw(e){return Sj(bo(e))}function Hp(e){return Sj(bo(Mg(ds(e)).reverse()))}function Ek(e,t){if(kg(t),t===0)throw Error("zero output length is invalid");e=Cye(e);let r=t*2,n=e.toString(16);if(n.length>r)throw RangeError("number is too large");return ha(n.padStart(r,"0"))}function Tj(e,t){return Ek(e,t).reverse()}function Mg(e){return Uint8Array.from(Yn(e))}function Jc(e){return typeof e==="bigint"&&Mw<=e}function Pk(e,t,r){return Jc(e)&&Jc(t)&&Jc(r)&&t<=e&&e<r}function Rk(e,t,r,n){if(!Pk(t,r,n))throw RangeError("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Ak(e){if(e<Mw)throw Error("expected non-negative bigint, got "+e);return e===Mw?0:e.toString(2).length}var vj=(e)=>(jp(e,"n"),(bj<<BigInt(e))-bj);function Xc(e,t={},r={},n="object"){Yc(e,n),Yc(t,"fields"),Yc(r,"optFields");function o(s,a,c){let u=n==="object"?`param "${String(s)}"`:`"${n}.${String(s)}"`,d=e[s];if(!Object.hasOwn(e,s)&&(c?d!==void 0:a!=="function"))throw TypeError(`${u} is invalid: expected own property`);if(c&&d===void 0)return;let f=typeof d;if(f!==a||d===null)throw TypeError(`${u} is invalid: expected ${a}, got ${f}`)}let i=(s,a)=>Object.entries(s).forEach(([c,u])=>o(c,u,a));i(t,!1),i(r,!0)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var qr=BigInt(0),tr=BigInt(1),El=BigInt(2),Pj=BigInt(3),Ik=BigInt(4),Rj=BigInt(5),Oye=BigInt(7),Aj=BigInt(8),Mye=BigInt(9),Bye=BigInt(15),kj=BigInt(16),Lye=BigInt("0x10000000000000000");function Rr(e,t){if(t<=qr)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=qr?r:t+r}function Nye(e,t,r){if(r<=tr)throw Error("pow: expected modulus > 1, got "+r);if(typeof t!=="bigint")throw TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<qr)throw Error("invalid exponent, negatives unsupported");if(t===qr)return tr;if(t===tr)return e;let n=e%r;if(n<qr)n+=r;if(t<Lye){let a=tr;while(t>qr){if(t&tr)a=a*n%r;n=n*n%r,t>>=tr}return a}let o=[];while(t>qr)o.push(Number(t&Bye)),t>>=Ik;let i=Array(16);i[0]=tr,i[1]=n;for(let a=2;a<16;a++)i[a]=i[a-1]*n%r;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%r,s=s*s%r,s=s*s%r,s=s*s%r;let c=o[a];if(c!==0)s=s*i[c]%r}return s}function gi(e,t,r){if(r<=tr)throw Error("pow2: expected modulus > 1, got "+r);if(t<qr)throw Error("pow2: expected non-negative exponent, got "+t);let n=e;while(t-- >qr)n*=n,n%=r;return n}function _j(e,t){if(e===qr)throw Error("invert: expected non-zero number");if(t<=tr)throw Error("invert: expected modulus > 1, got "+t);let r=Rr(e,t),n=t,o=qr,i=tr;while(r!==qr){let a=n/r,c=n-r*a,u=o-i*a;n=r,r=c,o=i,i=u}if(n!==tr)throw Error("invert: does not exist");return Rr(o,t)}function Ck(e,t,r){let n=e;if(!n.eql(n.sqr(t),r))throw Error("Cannot find square root")}function Ok(e,t){if((e&tr)===qr)throw Error(t+": expected odd modulus, got "+e)}function Ij(e,t){let r=e,n=(r.ORDER+tr)/Ik,o=r.pow(t,n);return Ck(r,o,t),o}function $ye(e,t){let r=e,n=(r.ORDER-Rj)/Aj,o=r.mul(t,El),i=r.pow(o,n),s=r.mul(t,i),a=r.mul(r.mul(s,El),i),c=r.mul(s,r.sub(a,r.ONE));return Ck(r,c,t),c}function zye(e){let t=$w(e),r=Cj(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+Oye)/kj;return(a,c)=>{let u=a,d=u.pow(c,s),f=u.mul(d,n),m=u.mul(d,o),g=u.mul(d,i),y=u.eql(u.sqr(f),c),x=u.eql(u.sqr(m),c);d=u.cmov(d,f,y),f=u.cmov(g,m,x);let S=u.eql(u.sqr(f),c),T=u.cmov(d,f,S);return Ck(u,T,c),T}}function Cj(e){if(e<Pj)throw Error("sqrt is not defined for small field");Ok(e,"tonelliShanks");let t=e-tr,r=0;while(t%El===qr)t/=El,r++;let n=El,o=$w(e);while(Bg(o,n)===1)if(n++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return Ij;let i=o.pow(n,t),s=(t+tr)/El;return function(c,u){let d=c;if(d.is0(u))return u;if(Bg(d,u)!==1)throw Error("Cannot find square root");let f=r,m=d.mul(d.ONE,i),g=d.pow(u,t),y=d.pow(u,s);while(!d.eql(g,d.ONE)){if(d.is0(g))throw Error("Cannot find square root: probably non-prime P");let x=1,S=d.sqr(g);while(!d.eql(S,d.ONE))if(x++,S=d.sqr(S),x===f)throw Error("Cannot find square root");let T=tr<<BigInt(f-x-1),E=d.pow(m,T);f=x,m=d.sqr(E),g=d.mul(g,m),y=d.mul(y,E)}return y}}function Dye(e){if(Ok(e,"Fp.sqrt"),e%Ik===Pj)return Ij;if(e%Aj===Rj)return $ye;if(e%kj===Mye)return zye(e);return Cj(e)}var Oj=(e,t)=>(Rr(e,t)&tr)===tr,Fye=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Gp(e){if(Yc(e,"field"),typeof e.ORDER!=="bigint")throw TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);jp(e.BYTES,"BYTES"),jp(e.BITS,"BITS");for(let t of Fye)_l(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=tr)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Nw(e,t,r=!1){Gp(e),Bw(t,"nums"),ga(r,"passZero");let n=e,o=Array(t.length).fill(r?n.ZERO:void 0),i=t.reduce((a,c,u)=>{if(n.is0(c))return a;return o[u]=a,n.mul(a,c)},n.ONE),s=n.inv(i);return t.reduceRight((a,c,u)=>{if(n.is0(c))return a;return o[u]=n.mul(a,o[u]),n.mul(a,c)},s),o}function Bg(e,t){Gp(e);let r=e;Ok(r.ORDER,"FpLegendre");let n=(r.ORDER-tr)/El,o=r.pow(t,n),i=r.eql(o,r.ONE),s=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function qye(e,t){if(t!==void 0)Tk(t);if(e<=qr)throw Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw Error("invalid n length: expected positive bit length, got "+t);let r=Ak(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${r})`);let n=t!==void 0?t:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Ej=new WeakMap;class kk{ORDER;BITS;BYTES;isLE;ZERO=qr;ONE=tr;_lengths;_mod;constructor(e,t={}){if(e<=tr)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:n,nByteLength:o}=qye(e,r);if(o>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,Object.freeze(this)}create(e){return Rr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return qr<=e&&e<this.ORDER}is0(e){return e===qr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&tr)===tr}neg(e){return Rr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Rr(e*e,this.ORDER)}add(e,t){return Rr(e+t,this.ORDER)}sub(e,t){return Rr(e-t,this.ORDER)}mul(e,t){return Rr(e*t,this.ORDER)}pow(e,t){return Nye(e,t,this.ORDER)}div(e,t){return Rr(e*_j(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return _j(e,this.ORDER)}sqrt(e){let t=Ej.get(this);if(!t)Ej.set(this,t=Dye(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?Tj(e,this.BYTES):Ek(e,this.BYTES)}fromBytes(e,t=!1){Yn(e);let{_lengths:r,BYTES:n,isLE:o,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(n);c.set(e,o?0:c.length-e.length),e=c}if(e.length!==n)throw Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let a=o?Hp(e):Lw(e);if(s)a=Rr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Nw(this,e,!0)}cmov(e,t,r){return ga(r,"condition"),r?t:e}}function $w(e,t={}){return Object.freeze(kk.prototype),new kk(e,t)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Lk=BigInt(0),Lg=BigInt(1),Uye=BigInt(4),Mk=16,Mj=128,jye=5,Bj=(()=>2147483648)();function Ng(e){let t=e;if(typeof t!=="function")throw TypeError('"Point" expected constructor, got type='+typeof e);_l(t.fromAffine,"Point.fromAffine"),_l(t.fromBytes,"Point.fromBytes"),_l(t.fromHex,"Point.fromHex"),Yc(t.BASE,"Point.BASE"),Yc(t.ZERO,"Point.ZERO"),Gp(t.Fp),Gp(t.Fn)}function Nj(e,t){Ng(e),$j(t,e);let r=Nw(e.Fp,t.map((n)=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function Hye(e,t,r=1){if(!Number.isSafeInteger(e)||e<r||e>t)throw Error("invalid window size, expected ["+r+".."+t+"], got W="+e)}function Gye(e,t){let r=e*(4*t+128);if(r>Bj)throw Error("invalid window size: table would need ~"+Math.ceil(r/1048576)+" MiB, max "+Bj/1048576+" MiB")}function Vye(e,t){if(e===void 0)return;_l(e,"randomBytes");try{let r=e(t);if(!Og(r)||r.length!==t)return}catch{return}return e}function $j(e,t){Bw(e,"points"),e.forEach((r,n)=>{if(!(r instanceof t))throw Error("invalid point at index "+n)})}function Wye(e,t,r){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach((n,o)=>{if(!(r===void 0?t.isValid(n):Jc(n)&&n<r))throw Error("invalid scalar at index "+o)})}var zj=new WeakMap;function Bk(e){return zj.get(e)||1}function Zye(e,t){let r=e.double(),n=[e];for(let o=1;o<t;o++)n.push(n[o-1].add(r));return n}function Kye(e,t){let r=2**t,n=r/2,o=BigInt(r-1),i=[];while(e>Lk){let s=0;if(e&Lg){if(s=Number(e&o),s>=n)s-=r;e-=BigInt(s)}i.push(s),e>>=Lg}return i}function Qye(e,t,r){let n=2**t,o=n/2,i=BigInt(n-1),s=BigInt(t),a=[];for(let c=0;c<r;c++){let u=Number(e&i);if(e>>=s,u>o)u-=n,e+=Lg;a.push(u)}if(e!==Lk)throw Error("invalid wnaf");return a}function Yye(e,t,r){let n=0;for(let i of r)n=Math.max(n,i.length);let o=e;for(let i=n-1;i>=0;i--){if(i!==n-1)o=o.double();for(let s=0;s<r.length;s++){let a=r[s][i];if(a){let c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class Nk{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Ng(e),this.randomBytes=Vye(t,Mk),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,r){let n=Math.ceil(r/t)+1,o=2**(t-1),i=[],s=e;for(let a=0;a<n;a++){let c=s;for(let u=0;u<o;u++)i.push(c),c=c.add(s);s=i[i.length-1].double()}return{W:t,bits:r,windows:n,comp:i}}wnafCachedCT(e,t){let{W:r,windows:n,comp:o}=e,i=2**(r-1),s=Qye(t,r,n),a=this.ZERO,c=this.BASE;for(let u=0;u<n;u++){let d=s[u],f=u*i,m=Math.abs(d)-1,g=o[f];for(let x=1;x<i;x++)g=x===m?o[f+x]:g;let y=g.negate();if(d===0)c=c.add(o[f]);else a=a.add(d<0?y:g)}return{p:a,f:c}}getWnafPrecomputes(e,t,r,n){let o=this.wnafPrecomputes.get(t),i=o?.find((s)=>s.W===e&&s.bits===r);if(!i){if(i=this.buildWnafTable(t,e,r),typeof n==="function")i={...i,comp:n(i.comp)};if(!o)o=[],this.wnafPrecomputes.set(t,o);o.push(i)}return i}assertPoint(e){if(!(e instanceof this.Point))throw TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!Pk(t,Lg,this.Point.Fn.ORDER))throw Error("invalid scalar")}runCT(e,t,r,n){let o=Bk(e);if(o===1)return this.fixedWindowCT(e,t,r);return this.wnafCachedCT(this.getWnafPrecomputes(o,e,r,n),t)}mulCT(e,t,r){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,r)}mulCTBlinded(e,t,r){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw Error("randomBytes is required for scalar blinding");let n=this.Point.Fn.BITS+Mj,o=this.randomBytes(Mk);if(!Og(o)||o.length!==Mk)throw Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+Lw(o)*this.Point.Fn.ORDER;return this.runCT(e,i,n,r)}fixedWindowCT(e,t,r){let n=jye,o=1<<n,i=vj(n),s=Array(o);s[0]=this.ZERO;for(let u=1;u<o;u++)s[u]=s[u-1].add(e);let a=Math.ceil(r/n),c=this.ZERO;for(let u=a-1;u>=0;u--){if(u!==a-1)for(let m=0;m<n;m++)c=c.double();let d=Number(t>>BigInt(u*n)&i),f=s[0];for(let m=1;m<o;m++)f=m===d?s[m]:f;c=c.add(f)}return{p:c,f:c}}shouldBlind(e,t){if(this.randomBytes===void 0)return!1;if(t===Lg)return!0;if(e!==this.BASE)return!1;if(this.baseCanBeBlinded===void 0)this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0();return this.baseCanBeBlinded}mulSecret(e,t,r,n){return this.shouldBlind(e,r)?this.mulCTBlinded(e,t,n):this.mulCT(e,t,n)}mulUnsafe(e,t,r){if(this.assertPoint(e),!Jc(t))throw Error("invalid scalar");let n=Bk(e);if(n===1||t>=this.Point.Fn.ORDER)return Jye(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(n,e,this.bits,r);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),Hye(t,this.bits);let r=Math.ceil((this.bits+Mj)/t)+1;Gye(r*2**(t-1),this.Point.Fp.BYTES),zj.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Bk(e)!==1}}function Jye(e,t,r,n=!1){if(Ng(e),$j(t,e),ga(n,"allowOversized"),Wye(r,e.Fn,n?e.Fn.ORDER**Uye:void 0),t.length!==r.length)throw Error("arrays of points and scalars must have equal length");let o=t.map((s)=>Zye(s,4)),i=r.map((s)=>Kye(s,4));return Yye(e.ZERO,o,i)}function Lj(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return Gp(t),t}else return $w(e,{isLE:r})}function Dj(e,t,r={},n){if(e!=="weierstrass"&&e!=="edwards")throw Error('expected curve type "weierstrass" or "edwards"');if(n===void 0)n=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);Xc(r);for(let c of["p","n","h"]){let u=t[c];if(!(Jc(u)&&u!==Lk))throw Error(`CURVE.${c} must be positive bigint`)}let o=Lj(t.p,r.Fp,n),i=Lj(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function Fj(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var zw=BigInt(0),Dw=BigInt(1),Fw=BigInt(2),Xye=BigInt(4),qj=BigInt(8);function e0e(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function Uj(e,t={}){Xc(t,{},{},"extraOpts");let r=t,n=Dj("edwards",e,r,r.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;if(Bg(o,s.a)!==1)throw Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Bg(o,s.d)!==-1)throw Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Xc(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?_k:r.randomBytes,u=Fw<<BigInt(o.BYTES*8)-Dw;function d(E){if(!o.isOdd)throw Error("Field does not have .isOdd()");return o.isOdd(E)}let f=r.uvRatio===void 0?(E,v)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,v))}}catch(P){return{isValid:!1,value:zw}}}:r.uvRatio;if(!e0e(o,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");let m=o.eql(s.a,o.neg(o.ONE))?(E)=>o.neg(E):o.eql(s.a,o.ONE)?(E)=>E:(E)=>o.mul(s.a,E);function g(E,v,P=!1){let R=P?Dw:zw;return Rk("coordinate "+E,v,R,u),v}function y(E){if(!(E instanceof x))throw Error("EdwardsPoint expected")}class x{static BASE=new x(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new x(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(E,v,P,R){this.X=g("x",E),this.Y=g("y",v),this.Z=g("z",P,!0),this.T=g("t",R),Object.freeze(this)}static CURVE(){return s}static fromAffine(E){if(E instanceof x)throw Error("extended point not allowed");let{x:v,y:P}=E||{};return g("x",v),g("y",P),new x(v,P,o.ONE,o.mul(v,P))}static fromBytes(E,v=!1){let P=o.BYTES,{a:R,d:C}=s;E=Mg(Yn(E,P,"point")),ga(v,"zip215");let N=Mg(E),q=E[P-1];N[P-1]=q&-129;let M=Hp(N),k=v?u:o.ORDER;Rk("point.y",M,zw,k);let U=o.sqr(M),K=o.sub(U,o.ONE),oe=o.sub(o.mulN(C,U),R),{isValid:j,value:B}=f(K,oe);if(!j)throw Error("bad point: invalid y coordinate");let F=d(B),re=(q&128)!==0;if(!v&&o.is0(B)&&re)throw Error("bad point: x=0 and x_0=1");if(re!==F)B=o.neg(B);return x.fromAffine({x:B,y:M})}static fromHex(E,v=!1){return x.fromBytes(wj(E),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=6,v=!0){if(T.setWindowSize(this,E),!v)this.multiply(Fw);return this}assertValidity(){let E=this,{a:v,d:P}=s;if(E.is0())throw Error("bad point: ZERO");let{X:R,Y:C,Z:N,T:q}=E,M=o.sqr(R),k=o.sqr(C),U=o.sqr(N),K=o.sqr(U),oe=o.mul(M,v),j=o.mul(o.add(oe,k),U),B=o.add(K,o.mul(P,o.mul(M,k)));if(!o.eql(j,B))throw Error("bad point: equation left != right (1)");let F=o.mul(R,C),re=o.mul(N,q);if(!o.eql(F,re))throw Error("bad point: equation left != right (2)")}equals(E){y(E);let{X:v,Y:P,Z:R}=this,{X:C,Y:N,Z:q}=E,M=o.mul(v,q),k=o.mul(C,R),U=o.mul(P,q),K=o.mul(N,R);return o.eql(M,k)&&o.eql(U,K)}is0(){return this.equals(x.ZERO)}negate(){return new x(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:E,Y:v,Z:P}=this,R=o.sqr(E),C=o.sqr(v),N=o.mul(o.sqr(P),Fw),q=m(R),M=o.addN(E,v),k=o.sub(o.subN(o.sqr(M),R),C),U=o.addN(q,C),K=o.subN(U,N),oe=o.subN(q,C),j=o.mul(k,K),B=o.mul(U,oe),F=o.mul(k,oe),re=o.mul(K,U);return new x(j,B,re,F)}add(E){y(E);let{d:v}=s,{X:P,Y:R,Z:C,T:N}=this,{X:q,Y:M,Z:k,T:U}=E,K=o.mul(P,q),oe=o.mul(R,M),j=o.mul(o.mulN(N,v),U),B=o.mul(C,k),F=o.sub(o.subN(o.mulN(o.addN(P,R),o.addN(q,M)),K),oe),re=o.subN(B,j),be=o.addN(B,j),me=o.sub(oe,m(K)),ue=o.mul(F,re),$e=o.mul(be,me),xe=o.mul(F,me),Pt=o.mul(re,be);return new x(ue,$e,Pt,xe)}subtract(E){return y(E),this.add(E.negate())}multiply(E){if(!i.isValidNot0(E))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:P}=T.mulSecret(this,E,a,S);return S([v,P])[0]}multiplyUnsafe(E){if(!i.isValid(E))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(E===zw)return x.ZERO;if(this.is0()||E===Dw)return this;return T.mulUnsafe(this,E,S)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return T.mulUnsafe(this,s.n).is0()}toAffine(E){let v=this,P=E;if(P!=null&&typeof P!=="bigint")throw TypeError('"invertedZ" expected bigint, got type='+typeof P);let{X:R,Y:C,Z:N}=v,q=v.is0();if(P==null)P=q?o.create(qj):o.inv(N);let M=o.mul(R,P),k=o.mul(C,P),U=o.mul(N,P);if(q)return{x:o.ZERO,y:o.ONE};if(!o.eql(U,o.ONE))throw Error("invZ was invalid");return{x:M,y:k}}clearCofactor(){if(a===Dw)return this;if(a===Fw)return this.double();if(a===Xye)return this.double().double();if(a===qj)return this.double().double().double();return this.multiplyUnsafe(a)}toBytes(){let{x:E,y:v}=this.toAffine(),P=o.toBytes(v);return P[P.length-1]|=d(E)?128:0,P}toHex(){return xj(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let S=(E)=>Nj(x,E),T=new Nk(x,c);if(T.bits>=6)x.BASE.precompute(6);return Object.freeze(x.prototype),Object.freeze(x),x}function jj(e,t,r={}){if(Ng(e),typeof t!=="function")throw Error('"hash" function param is required');let n=t,o=r;Xc(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,u=n.outputLen,d=2*a.BYTES;if(u!==void 0){if(jp(u,"hash.outputLen"),u!==d)throw Error(`hash.outputLen must be ${d}, got ${u}`)}let f=o.randomBytes===void 0?_k:o.randomBytes,{toMontgomery:m,toMontgomerySecret:g}=o,y=o.adjustScalarBytes===void 0?(j)=>j:o.adjustScalarBytes,x=o.domain===void 0?(j,B,F)=>{if(ga(F,"phflag"),B.length||F)throw Error("Contexts/pre-hash are not supported");return j}:o.domain;function S(j){return c.create(Hp(j))}function T(j){let B=M.secretKey;Yn(j,M.secretKey,"secretKey");let F=Yn(n(j),2*B,"hashedSecretKey"),re=y(F.slice(0,B)),be=F.slice(B,2*B),me=S(re);return{head:re,prefix:be,scalar:me}}function E(j){let{head:B,prefix:F,scalar:re}=T(j),be=s.multiply(re),me=be.toBytes();return{head:B,prefix:F,scalar:re,point:be,pointBytes:me}}function v(j){return E(j).pointBytes}function P(j=Uint8Array.of(),...B){let F=vk(...B);return S(n(x(F,Yn(j,void 0,"context"),!!i)))}function R(j,B,F={}){if(Xc(F,{},{},"options"),j=Mg(Yn(j,void 0,"message")),i)j=i(j);let{prefix:re,scalar:be,pointBytes:me}=E(B),ue=P(F.context,re,j),$e=s.multiply(ue).toBytes(),xe=P(F.context,$e,me,j),Pt=c.create(ue+xe*be);if(!c.isValid(Pt))throw Error("sign failed: invalid s");let Ye=vk($e,c.toBytes(Pt));return Yn(Ye,M.signature,"result")}let C={zip215:o.zip215};function N(j,B,F,re=C){Xc(re);let{context:be}=re,me=re.zip215===void 0?!!C.zip215:re.zip215,ue=M.signature;if(j=Yn(j,ue,"signature"),B=Yn(B,void 0,"message"),F=Yn(F,M.publicKey,"publicKey"),me!==void 0)ga(me,"zip215");if(i)B=i(B);let $e=ue/2,xe=j.subarray(0,$e),Pt=Hp(j.subarray($e,ue)),Ye,at,kr;try{Ye=e.fromBytes(F,me),at=e.fromBytes(xe,me),kr=s.multiplyUnsafe(Pt)}catch(Kr){return!1}if(!me&&Ye.isSmallOrder())return!1;let _r=P(be,xe,F,B);return at.add(Ye.multiplyUnsafe(_r)).subtract(kr).clearCofactor().is0()}let q=a.BYTES,M={secretKey:q,publicKey:q,signature:2*q,seed:q};function k(j){return j=j===void 0?f(M.seed):j,Yn(j,M.seed,"seed")}function U(j){return Og(j)&&j.length===M.secretKey}function K(j,B){try{return!!e.fromBytes(j,B===void 0?C.zip215:B)}catch(F){return!1}}let oe={getExtendedPublicKey:E,randomSecretKey:k,isValidSecretKey:U,isValidPublicKey:K,toMontgomery(j){if(m===void 0)throw Error("Montgomery conversion is not supported for this curve");return m(e.fromBytes(j))},toMontgomerySecret(j){if(g===void 0)throw Error("Montgomery conversion is not supported for this curve");return g(j)}};return Object.freeze(M),Object.freeze(oe),Object.freeze({keygen:Fj(k,v),getPublicKey:v,sign:R,verify:N,utils:oe,Point:e,lengths:M})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var $k=BigInt(1),Hj=BigInt(2);var t0e=BigInt(5),r0e=BigInt(8),zk=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n0e=(()=>({p:zk,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:r0e,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function o0e(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=zk,a=e*e%i*e%i,c=gi(a,Hj,i)*a%i,u=gi(c,$k,i)*e%i,d=gi(u,t0e,i)*u%i,f=gi(d,t,i)*d%i,m=gi(f,r,i)*f%i,g=gi(m,n,i)*m%i,y=gi(g,o,i)*g%i,x=gi(y,o,i)*g%i,S=gi(x,t,i)*d%i;return{pow_p_5_8:gi(S,Hj,i)*e%i,b2:a}}function Wj(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Gj=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function i0e(e,t){let r=zk,n=Rr(t*t*t,r),o=Rr(n*n*t,r),i=o0e(e*o).pow_p_5_8,s=Rr(e*n*i,r),a=Rr(t*s*s,r),c=s,u=Rr(s*Gj,r),d=a===e,f=a===Rr(-e,r),m=a===Rr(-e*Gj,r);if(d)s=c;if(f||m)s=u;if(Oj(s,r))s=Rr(-s,r);return{isValid:d||f,value:s}}var Dk=Uj(n0e,{uvRatio:i0e}),Vj=(()=>Dk.Fp)();function s0e(e){let{y:t}=e;return Vj.toBytes(Vj.div($k+t,$k-t))}function a0e(e){let t=Dk.Fp.BYTES;return ds(e,t),Wj(Sk(e.subarray(0,t))).subarray(0,t)}function c0e(e){return jj(Dk,Sk,Object.assign({adjustScalarBytes:Wj,toMontgomery:s0e,toMontgomerySecret:a0e,zip215:!0},e))}var Vp=c0e({});function Zj(e){return btoa(String.fromCharCode(...e))}function Kj(e,t,r,n,o){if(!Number.isSafeInteger(o)||o<0||o>999999999999999)throw Error("Invalid signature creation time");if(!/^[A-Z]+$/.test(t)||!r.startsWith("/")||/[\s#\u0000-\u001f\u007f]/.test(r))throw Error("Invalid signature request target");let i=r.indexOf("?"),s=i<0?r:r.slice(0,i),a=i<0?"?":r.slice(i),c=`sha-256=:${Zj(Ow(n))}:`,u=`("@method" "@path" "@query" "content-digest");created=${o};keyid="${bo(e.publicKey)}";alg="ed25519"`,d=`"@method": ${t}
|
|
133
133
|
"@path": ${s}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0xmonaco/mcp-server",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.22",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"homepage": "https://docs.0xmonaco.com/sdk/typescript",
|
|
6
6
|
"description": "MCP server for the Monaco SDK",
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
},
|
|
22
22
|
"author": "@codebycarson",
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@0xmonaco/core": "1.1.
|
|
25
|
-
"@0xmonaco/types": "1.1.
|
|
24
|
+
"@0xmonaco/core": "1.1.22",
|
|
25
|
+
"@0xmonaco/types": "1.1.22",
|
|
26
26
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
27
27
|
"node-fetch": "^3.3.2",
|
|
28
28
|
"viem": "^2.57.20",
|