@0xmonaco/mcp-server 1.0.58-develop.f12e78b → 1.0.59
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 +10 -10
- package/package.json +3 -3
package/dist/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as LH}from"node:module";var kH=Object.create;var{getPrototypeOf:RH,defineProperty:Kx,getOwnPropertyNames:OH}=Object;var pk=Object.prototype.hasOwnProperty;function CH(e){return this[e]}var MH,$H,Vr=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?MH??=new WeakMap:$H??=new WeakMap,i=o.get(e);if(i)return i}r=e!=null?kH(RH(e)):{};let s=t||!e||!e.__esModule||!pk.call(e,"default")?Kx(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of OH(e))if(!pk.call(s,a))Kx(s,a,{get:CH.bind(e,a),enumerable:!0})}if(n)o.set(e,s);return s};var ie=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var NH=(e)=>e;function zH(e,t){this[e]=NH.bind(null,t)}var BH=(e,t)=>{for(var r in t)Kx(e,r,{get:t[r],enumerable:!0,configurable:!0,set:zH.bind(t,r)})};var V=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var Lt=LH(import.meta.url);var hk=ie(function(uh,mk){(function(e,t){typeof uh==="object"&&typeof mk<"u"?t(uh):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.WebStreamsPolyfill={}))})(uh,function(e){function t(){return}function r(u){return typeof u==="object"&&u!==null||typeof u==="function"}let n=t;function o(u,f){try{Object.defineProperty(u,"name",{value:f,configurable:!0})}catch(g){}}let i=Promise,s=Promise.prototype.then,a=Promise.reject.bind(i);function c(u){return new i(u)}function d(u){return c((f)=>f(u))}function l(u){return a(u)}function p(u,f,g){return s.call(u,f,g)}function m(u,f,g){p(p(u,f,g),void 0,n)}function h(u,f){m(u,f)}function y(u,f){m(u,void 0,f)}function x(u,f,g){return p(u,f,g)}function _(u){p(u,void 0,n)}let w=(u)=>{if(typeof queueMicrotask==="function")w=queueMicrotask;else{let f=d(void 0);w=(g)=>p(f,g)}return w(u)};function A(u,f,g){if(typeof u!=="function")throw TypeError("Argument is not a function");return Function.prototype.apply.call(u,f,g)}function S(u,f,g){try{return d(A(u,f,g))}catch(E){return l(E)}}let v=16384;class P{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(u){let f=this._back,g=f;if(f._elements.length===v-1)g={_elements:[],_next:void 0};if(f._elements.push(u),g!==f)this._back=g,f._next=g;++this._size}shift(){let u=this._front,f=u,g=this._cursor,E=g+1,I=u._elements,B=I[g];if(E===v)f=u._next,E=0;if(--this._size,this._cursor=E,u!==f)this._front=f;return I[g]=void 0,B}forEach(u){let f=this._cursor,g=this._front,E=g._elements;while(f!==E.length||g._next!==void 0){if(f===E.length){if(g=g._next,E=g._elements,f=0,E.length===0)break}u(E[f]),++f}}peek(){let u=this._front,f=this._cursor;return u._elements[f]}}let k=Symbol("[[AbortSteps]]"),O=Symbol("[[ErrorSteps]]"),N=Symbol("[[CancelSteps]]"),j=Symbol("[[PullSteps]]"),R=Symbol("[[ReleaseSteps]]");function K(u,f){if(u._ownerReadableStream=f,f._reader=u,f._state==="readable")U(u);else if(f._state==="closed")me(u);else ee(u,f._storedError)}function Z(u,f){let g=u._ownerReadableStream;return oo(g,f)}function re(u){let f=u._ownerReadableStream;if(f._state==="readable")z(u,TypeError("Reader was released and can no longer be used to monitor the stream's closedness"));else F(u,TypeError("Reader was released and can no longer be used to monitor the stream's closedness"));f._readableStreamController[R](),f._reader=void 0,u._ownerReadableStream=void 0}function pe(u){return TypeError("Cannot "+u+" a stream using a released reader")}function U(u){u._closedPromise=c((f,g)=>{u._closedPromise_resolve=f,u._closedPromise_reject=g})}function ee(u,f){U(u),z(u,f)}function me(u){U(u),Y(u)}function z(u,f){if(u._closedPromise_reject===void 0)return;_(u._closedPromise),u._closedPromise_reject(f),u._closedPromise_resolve=void 0,u._closedPromise_reject=void 0}function F(u,f){ee(u,f)}function Y(u){if(u._closedPromise_resolve===void 0)return;u._closedPromise_resolve(void 0),u._closedPromise_resolve=void 0,u._closedPromise_reject=void 0}let we=Number.isFinite||function(u){return typeof u==="number"&&isFinite(u)},te=Math.trunc||function(u){return u<0?Math.ceil(u):Math.floor(u)};function $e(u){return typeof u==="object"||typeof u==="function"}function Te(u,f){if(u!==void 0&&!$e(u))throw TypeError(`${f} is not an object.`)}function Pe(u,f){if(typeof u!=="function")throw TypeError(`${f} is not a function.`)}function tt(u){return typeof u==="object"&&u!==null||typeof u==="function"}function yt(u,f){if(!tt(u))throw TypeError(`${f} is not an object.`)}function ft(u,f,g){if(u===void 0)throw TypeError(`Parameter ${f} is required in '${g}'.`)}function q(u,f,g){if(u===void 0)throw TypeError(`${f} is required in '${g}'.`)}function ne(u){return Number(u)}function ce(u){return u===0?0:u}function he(u){return ce(te(u))}function Q(u,f){let E=Number.MAX_SAFE_INTEGER,I=Number(u);if(I=ce(I),!we(I))throw TypeError(`${f} is not a finite number`);if(I=he(I),I<0||I>E)throw TypeError(`${f} is outside the accepted range of 0 to ${E}, inclusive`);if(!we(I)||I===0)return 0;return I}function Be(u,f){if(!Ts(u))throw TypeError(`${f} is not a ReadableStream.`)}function bt(u){return new Hr(u)}function xt(u,f){u._reader._readRequests.push(f)}function Qe(u,f,g){let I=u._reader._readRequests.shift();if(g)I._closeSteps();else I._chunkSteps(f)}function vt(u){return u._reader._readRequests.length}function wt(u){let f=u._reader;if(f===void 0)return!1;if(!_s(f))return!1;return!0}class Hr{constructor(u){if(ft(u,1,"ReadableStreamDefaultReader"),Be(u,"First parameter"),Es(u))throw TypeError("This stream has already been locked for exclusive reading by another reader");K(this,u),this._readRequests=new P}get closed(){if(!_s(this))return l(Lm("closed"));return this._closedPromise}cancel(u=void 0){if(!_s(this))return l(Lm("cancel"));if(this._ownerReadableStream===void 0)return l(pe("cancel"));return Z(this,u)}read(){if(!_s(this))return l(Lm("read"));if(this._ownerReadableStream===void 0)return l(pe("read from"));let u,f,g=c((I,B)=>{u=I,f=B});return $l(this,{_chunkSteps:(I)=>u({value:I,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:(I)=>f(I)}),g}releaseLock(){if(!_s(this))throw Lm("releaseLock");if(this._ownerReadableStream===void 0)return;Gq(this)}}if(Object.defineProperties(Hr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Hr.prototype.cancel,"cancel"),o(Hr.prototype.read,"read"),o(Hr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Hr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function _s(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_readRequests"))return!1;return u instanceof Hr}function $l(u,f){let g=u._ownerReadableStream;if(g._disturbed=!0,g._state==="closed")f._closeSteps();else if(g._state==="errored")f._errorSteps(g._storedError);else g._readableStreamController[j](f)}function Gq(u){re(u);let f=TypeError("Reader was released");iI(u,f)}function iI(u,f){let g=u._readRequests;u._readRequests=new P,g.forEach((E)=>{E._errorSteps(f)})}function Lm(u){return TypeError(`ReadableStreamDefaultReader.prototype.${u} can only be used on a ReadableStreamDefaultReader`)}let Vq=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class bx{constructor(u,f){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=u,this._preventCancel=f}next(){let u=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?x(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let f=()=>this._returnSteps(u);return this._ongoingPromise?x(this._ongoingPromise,f,f):f()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,f,g,E=c((B,W)=>{f=B,g=W});return $l(u,{_chunkSteps:(B)=>{this._ongoingPromise=void 0,w(()=>f({value:B,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,re(u),f({value:void 0,done:!0})},_errorSteps:(B)=>{this._ongoingPromise=void 0,this._isFinished=!0,re(u),g(B)}}),E}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let f=this._reader;if(!this._preventCancel){let g=Z(f,u);return re(f),x(g,()=>({value:u,done:!0}))}return re(f),d({value:u,done:!0})}}let sI={next(){if(!aI(this))return l(cI("next"));return this._asyncIteratorImpl.next()},return(u){if(!aI(this))return l(cI("return"));return this._asyncIteratorImpl.return(u)}};Object.setPrototypeOf(sI,Vq);function Zq(u,f){let g=bt(u),E=new bx(g,f),I=Object.create(sI);return I._asyncIteratorImpl=E,I}function aI(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_asyncIteratorImpl"))return!1;try{return u._asyncIteratorImpl instanceof bx}catch(f){return!1}}function cI(u){return TypeError(`ReadableStreamAsyncIterator.${u} can only be used on a ReadableSteamAsyncIterator`)}let uI=Number.isNaN||function(u){return u!==u};var xx,_x,wx;function Nl(u){return u.slice()}function dI(u,f,g,E,I){new Uint8Array(u).set(new Uint8Array(g,E,I),f)}let hi=(u)=>{if(typeof u.transfer==="function")hi=(f)=>f.transfer();else if(typeof structuredClone==="function")hi=(f)=>structuredClone(f,{transfer:[f]});else hi=(f)=>f;return hi(u)},ws=(u)=>{if(typeof u.detached==="boolean")ws=(f)=>f.detached;else ws=(f)=>f.byteLength===0;return ws(u)};function lI(u,f,g){if(u.slice)return u.slice(f,g);let E=g-f,I=new ArrayBuffer(E);return dI(I,0,u,f,E),I}function Dm(u,f){let g=u[f];if(g===void 0||g===null)return;if(typeof g!=="function")throw TypeError(`${String(f)} is not a function`);return g}function Wq(u){let f={[Symbol.iterator]:()=>u.iterator},g=async function*(){return yield*f}(),E=g.next;return{iterator:g,nextMethod:E,done:!1}}let Sx=(wx=(xx=Symbol.asyncIterator)!==null&&xx!==void 0?xx:(_x=Symbol.for)===null||_x===void 0?void 0:_x.call(Symbol,"Symbol.asyncIterator"))!==null&&wx!==void 0?wx:"@@asyncIterator";function pI(u,f="sync",g){if(g===void 0)if(f==="async"){if(g=Dm(u,Sx),g===void 0){let B=Dm(u,Symbol.iterator),W=pI(u,"sync",B);return Wq(W)}}else g=Dm(u,Symbol.iterator);if(g===void 0)throw TypeError("The object is not iterable");let E=A(g,u,[]);if(!r(E))throw TypeError("The iterator method must return an object");let I=E.next;return{iterator:E,nextMethod:I,done:!1}}function Kq(u){let f=A(u.nextMethod,u.iterator,[]);if(!r(f))throw TypeError("The iterator.next() method must return an object");return f}function Yq(u){return Boolean(u.done)}function Jq(u){return u.value}function Qq(u){if(typeof u!=="number")return!1;if(uI(u))return!1;if(u<0)return!1;return!0}function fI(u){let f=lI(u.buffer,u.byteOffset,u.byteOffset+u.byteLength);return new Uint8Array(f)}function vx(u){let f=u._queue.shift();if(u._queueTotalSize-=f.size,u._queueTotalSize<0)u._queueTotalSize=0;return f.value}function Tx(u,f,g){if(!Qq(g)||g===1/0)throw RangeError("Size must be a finite, non-NaN, non-negative number.");u._queue.push({value:f,size:g}),u._queueTotalSize+=g}function Xq(u){return u._queue.peek().value}function Ss(u){u._queue=new P,u._queueTotalSize=0}function mI(u){return u===DataView}function e7(u){return mI(u.constructor)}function t7(u){if(mI(u))return 1;return u.BYTES_PER_ELEMENT}class vs{constructor(){throw TypeError("Illegal constructor")}get view(){if(!Ex(this))throw Rx("view");return this._view}respond(u){if(!Ex(this))throw Rx("respond");if(ft(u,1,"respond"),u=Q(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw TypeError("This BYOB request has been invalidated");if(ws(this._view.buffer))throw TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");qm(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!Ex(this))throw Rx("respondWithNewView");if(ft(u,1,"respondWithNewView"),!ArrayBuffer.isView(u))throw TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw TypeError("This BYOB request has been invalidated");if(ws(u.buffer))throw TypeError("The given view's buffer has been detached and so cannot be used as a response");Hm(this._associatedReadableByteStreamController,u)}}if(Object.defineProperties(vs.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(vs.prototype.respond,"respond"),o(vs.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(vs.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class $o{constructor(){throw TypeError("Illegal constructor")}get byobRequest(){if(!Oa(this))throw Bl("byobRequest");return kx(this)}get desiredSize(){if(!Oa(this))throw Bl("desiredSize");return TI(this)}close(){if(!Oa(this))throw Bl("close");if(this._closeRequested)throw TypeError("The stream has already been closed; do not close it again!");let u=this._controlledReadableByteStream._state;if(u!=="readable")throw TypeError(`The stream (in ${u} state) is not in the readable state and cannot be closed`);zl(this)}enqueue(u){if(!Oa(this))throw Bl("enqueue");if(ft(u,1,"enqueue"),!ArrayBuffer.isView(u))throw TypeError("chunk must be an array buffer view");if(u.byteLength===0)throw TypeError("chunk must have non-zero byteLength");if(u.buffer.byteLength===0)throw TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw TypeError("stream is closed or draining");let f=this._controlledReadableByteStream._state;if(f!=="readable")throw TypeError(`The stream (in ${f} state) is not in the readable state and cannot be enqueued to`);jm(this,u)}error(u=void 0){if(!Oa(this))throw Bl("error");Bn(this,u)}[N](u){hI(this),Ss(this);let f=this._cancelAlgorithm(u);return Fm(this),f}[j](u){let f=this._controlledReadableByteStream;if(this._queueTotalSize>0){vI(this,u);return}let g=this._autoAllocateChunkSize;if(g!==void 0){let E;try{E=new ArrayBuffer(g)}catch(B){u._errorSteps(B);return}let I={buffer:E,bufferByteLength:g,byteOffset:0,byteLength:g,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(I)}xt(f,u),Ca(this)}[R](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new P,this._pendingPullIntos.push(u)}}}if(Object.defineProperties($o.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o($o.prototype.close,"close"),o($o.prototype.enqueue,"enqueue"),o($o.prototype.error,"error"),typeof Symbol.toStringTag==="symbol")Object.defineProperty($o.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Oa(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_controlledReadableByteStream"))return!1;return u instanceof $o}function Ex(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_associatedReadableByteStreamController"))return!1;return u instanceof vs}function Ca(u){if(!s7(u))return;if(u._pulling){u._pullAgain=!0;return}u._pulling=!0;let g=u._pullAlgorithm();m(g,()=>{if(u._pulling=!1,u._pullAgain)u._pullAgain=!1,Ca(u);return null},(E)=>(Bn(u,E),null))}function hI(u){Ax(u),u._pendingPullIntos=new P}function Px(u,f){let g=!1;if(u._state==="closed")g=!0;let E=gI(f);if(f.readerType==="default")Qe(u,E,g);else p7(u,E,g)}function gI(u){let{bytesFilled:f,elementSize:g}=u;return new u.viewConstructor(u.buffer,u.byteOffset,f/g)}function Um(u,f,g,E){u._queue.push({buffer:f,byteOffset:g,byteLength:E}),u._queueTotalSize+=E}function yI(u,f,g,E){let I;try{I=lI(f,g,g+E)}catch(B){throw Bn(u,B),B}Um(u,I,0,E)}function bI(u,f){if(f.bytesFilled>0)yI(u,f.buffer,f.byteOffset,f.bytesFilled);Yc(u)}function xI(u,f){let g=Math.min(u._queueTotalSize,f.byteLength-f.bytesFilled),E=f.bytesFilled+g,I=g,B=!1,W=E%f.elementSize,be=E-W;if(be>=f.minimumFill)I=be-f.bytesFilled,B=!0;let Re=u._queue;while(I>0){let Ue=Re.peek(),Ge=Math.min(I,Ue.byteLength),rt=f.byteOffset+f.bytesFilled;if(dI(f.buffer,rt,Ue.buffer,Ue.byteOffset,Ge),Ue.byteLength===Ge)Re.shift();else Ue.byteOffset+=Ge,Ue.byteLength-=Ge;u._queueTotalSize-=Ge,_I(u,Ge,f),I-=Ge}return B}function _I(u,f,g){g.bytesFilled+=f}function wI(u){if(u._queueTotalSize===0&&u._closeRequested)Fm(u),ql(u._controlledReadableByteStream);else Ca(u)}function Ax(u){if(u._byobRequest===null)return;u._byobRequest._associatedReadableByteStreamController=void 0,u._byobRequest._view=null,u._byobRequest=null}function Ix(u){while(u._pendingPullIntos.length>0){if(u._queueTotalSize===0)return;let f=u._pendingPullIntos.peek();if(xI(u,f))Yc(u),Px(u._controlledReadableByteStream,f)}}function r7(u){let f=u._controlledReadableByteStream._reader;while(f._readRequests.length>0){if(u._queueTotalSize===0)return;let g=f._readRequests.shift();vI(u,g)}}function n7(u,f,g,E){let I=u._controlledReadableByteStream,B=f.constructor,W=t7(B),{byteOffset:be,byteLength:Re}=f,Ue=g*W,Ge;try{Ge=hi(f.buffer)}catch(It){E._errorSteps(It);return}let rt={buffer:Ge,bufferByteLength:Ge.byteLength,byteOffset:be,byteLength:Re,bytesFilled:0,minimumFill:Ue,elementSize:W,viewConstructor:B,readerType:"byob"};if(u._pendingPullIntos.length>0){u._pendingPullIntos.push(rt),AI(I,E);return}if(I._state==="closed"){let It=new B(rt.buffer,rt.byteOffset,0);E._closeSteps(It);return}if(u._queueTotalSize>0){if(xI(u,rt)){let It=gI(rt);wI(u),E._chunkSteps(It);return}if(u._closeRequested){let It=TypeError("Insufficient bytes to fill elements in the given buffer");Bn(u,It),E._errorSteps(It);return}}u._pendingPullIntos.push(rt),AI(I,E),Ca(u)}function o7(u,f){if(f.readerType==="none")Yc(u);let g=u._controlledReadableByteStream;if(Ox(g))while(II(g)>0){let E=Yc(u);Px(g,E)}}function i7(u,f,g){if(_I(u,f,g),g.readerType==="none"){bI(u,g),Ix(u);return}if(g.bytesFilled<g.minimumFill)return;Yc(u);let E=g.bytesFilled%g.elementSize;if(E>0){let I=g.byteOffset+g.bytesFilled;yI(u,g.buffer,I-E,E)}g.bytesFilled-=E,Px(u._controlledReadableByteStream,g),Ix(u)}function SI(u,f){let g=u._pendingPullIntos.peek();if(Ax(u),u._controlledReadableByteStream._state==="closed")o7(u,g);else i7(u,f,g);Ca(u)}function Yc(u){return u._pendingPullIntos.shift()}function s7(u){let f=u._controlledReadableByteStream;if(f._state!=="readable")return!1;if(u._closeRequested)return!1;if(!u._started)return!1;if(wt(f)&&vt(f)>0)return!0;if(Ox(f)&&II(f)>0)return!0;if(TI(u)>0)return!0;return!1}function Fm(u){u._pullAlgorithm=void 0,u._cancelAlgorithm=void 0}function zl(u){let f=u._controlledReadableByteStream;if(u._closeRequested||f._state!=="readable")return;if(u._queueTotalSize>0){u._closeRequested=!0;return}if(u._pendingPullIntos.length>0){let g=u._pendingPullIntos.peek();if(g.bytesFilled%g.elementSize!==0){let E=TypeError("Insufficient bytes to fill elements in the given buffer");throw Bn(u,E),E}}Fm(u),ql(f)}function jm(u,f){let g=u._controlledReadableByteStream;if(u._closeRequested||g._state!=="readable")return;let{buffer:E,byteOffset:I,byteLength:B}=f;if(ws(E))throw TypeError("chunk's buffer is detached and so cannot be enqueued");let W=hi(E);if(u._pendingPullIntos.length>0){let be=u._pendingPullIntos.peek();if(ws(be.buffer))throw TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");if(Ax(u),be.buffer=hi(be.buffer),be.readerType==="none")bI(u,be)}if(wt(g))if(r7(u),vt(g)===0)Um(u,W,I,B);else{if(u._pendingPullIntos.length>0)Yc(u);let be=new Uint8Array(W,I,B);Qe(g,be,!1)}else if(Ox(g))Um(u,W,I,B),Ix(u);else Um(u,W,I,B);Ca(u)}function Bn(u,f){let g=u._controlledReadableByteStream;if(g._state!=="readable")return;hI(u),Ss(u),Fm(u),QI(g,f)}function vI(u,f){let g=u._queue.shift();u._queueTotalSize-=g.byteLength,wI(u);let E=new Uint8Array(g.buffer,g.byteOffset,g.byteLength);f._chunkSteps(E)}function kx(u){if(u._byobRequest===null&&u._pendingPullIntos.length>0){let f=u._pendingPullIntos.peek(),g=new Uint8Array(f.buffer,f.byteOffset+f.bytesFilled,f.byteLength-f.bytesFilled),E=Object.create(vs.prototype);c7(E,u,g),u._byobRequest=E}return u._byobRequest}function TI(u){let f=u._controlledReadableByteStream._state;if(f==="errored")return null;if(f==="closed")return 0;return u._strategyHWM-u._queueTotalSize}function qm(u,f){let g=u._pendingPullIntos.peek();if(u._controlledReadableByteStream._state==="closed"){if(f!==0)throw TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(f===0)throw TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(g.bytesFilled+f>g.byteLength)throw RangeError("bytesWritten out of range")}g.buffer=hi(g.buffer),SI(u,f)}function Hm(u,f){let g=u._pendingPullIntos.peek();if(u._controlledReadableByteStream._state==="closed"){if(f.byteLength!==0)throw TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(f.byteLength===0)throw TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(g.byteOffset+g.bytesFilled!==f.byteOffset)throw RangeError("The region specified by view does not match byobRequest");if(g.bufferByteLength!==f.buffer.byteLength)throw RangeError("The buffer of view has different capacity than byobRequest");if(g.bytesFilled+f.byteLength>g.byteLength)throw RangeError("The region specified by view is larger than byobRequest");let I=f.byteLength;g.buffer=hi(f.buffer),SI(u,I)}function EI(u,f,g,E,I,B,W){f._controlledReadableByteStream=u,f._pullAgain=!1,f._pulling=!1,f._byobRequest=null,f._queue=f._queueTotalSize=void 0,Ss(f),f._closeRequested=!1,f._started=!1,f._strategyHWM=B,f._pullAlgorithm=E,f._cancelAlgorithm=I,f._autoAllocateChunkSize=W,f._pendingPullIntos=new P,u._readableStreamController=f;let be=g();m(d(be),()=>(f._started=!0,Ca(f),null),(Re)=>(Bn(f,Re),null))}function a7(u,f,g){let E=Object.create($o.prototype),I,B,W;if(f.start!==void 0)I=()=>f.start(E);else I=()=>{return};if(f.pull!==void 0)B=()=>f.pull(E);else B=()=>d(void 0);if(f.cancel!==void 0)W=(Re)=>f.cancel(Re);else W=()=>d(void 0);let be=f.autoAllocateChunkSize;if(be===0)throw TypeError("autoAllocateChunkSize must be greater than 0");EI(u,E,I,B,W,g,be)}function c7(u,f,g){u._associatedReadableByteStreamController=f,u._view=g}function Rx(u){return TypeError(`ReadableStreamBYOBRequest.prototype.${u} can only be used on a ReadableStreamBYOBRequest`)}function Bl(u){return TypeError(`ReadableByteStreamController.prototype.${u} can only be used on a ReadableByteStreamController`)}function u7(u,f){Te(u,f);let g=u===null||u===void 0?void 0:u.mode;return{mode:g===void 0?void 0:d7(g,`${f} has member 'mode' that`)}}function d7(u,f){if(u=`${u}`,u!=="byob")throw TypeError(`${f} '${u}' is not a valid enumeration value for ReadableStreamReaderMode`);return u}function l7(u,f){var g;Te(u,f);let E=(g=u===null||u===void 0?void 0:u.min)!==null&&g!==void 0?g:1;return{min:Q(E,`${f} has member 'min' that`)}}function PI(u){return new gi(u)}function AI(u,f){u._reader._readIntoRequests.push(f)}function p7(u,f,g){let I=u._reader._readIntoRequests.shift();if(g)I._closeSteps(f);else I._chunkSteps(f)}function II(u){return u._reader._readIntoRequests.length}function Ox(u){let f=u._reader;if(f===void 0)return!1;if(!Ma(f))return!1;return!0}class gi{constructor(u){if(ft(u,1,"ReadableStreamBYOBReader"),Be(u,"First parameter"),Es(u))throw TypeError("This stream has already been locked for exclusive reading by another reader");if(!Oa(u._readableStreamController))throw TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");K(this,u),this._readIntoRequests=new P}get closed(){if(!Ma(this))return l(Gm("closed"));return this._closedPromise}cancel(u=void 0){if(!Ma(this))return l(Gm("cancel"));if(this._ownerReadableStream===void 0)return l(pe("cancel"));return Z(this,u)}read(u,f={}){if(!Ma(this))return l(Gm("read"));if(!ArrayBuffer.isView(u))return l(TypeError("view must be an array buffer view"));if(u.byteLength===0)return l(TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return l(TypeError("view's buffer must have non-zero byteLength"));if(ws(u.buffer))return l(TypeError("view's buffer has been detached"));let g;try{g=l7(f,"options")}catch(Re){return l(Re)}let E=g.min;if(E===0)return l(TypeError("options.min must be greater than 0"));if(!e7(u)){if(E>u.length)return l(RangeError("options.min must be less than or equal to view's length"))}else if(E>u.byteLength)return l(RangeError("options.min must be less than or equal to view's byteLength"));if(this._ownerReadableStream===void 0)return l(pe("read from"));let I,B,W=c((Re,Ue)=>{I=Re,B=Ue});return kI(this,u,E,{_chunkSteps:(Re)=>I({value:Re,done:!1}),_closeSteps:(Re)=>I({value:Re,done:!0}),_errorSteps:(Re)=>B(Re)}),W}releaseLock(){if(!Ma(this))throw Gm("releaseLock");if(this._ownerReadableStream===void 0)return;f7(this)}}if(Object.defineProperties(gi.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(gi.prototype.cancel,"cancel"),o(gi.prototype.read,"read"),o(gi.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(gi.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Ma(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_readIntoRequests"))return!1;return u instanceof gi}function kI(u,f,g,E){let I=u._ownerReadableStream;if(I._disturbed=!0,I._state==="errored")E._errorSteps(I._storedError);else n7(I._readableStreamController,f,g,E)}function f7(u){re(u);let f=TypeError("Reader was released");RI(u,f)}function RI(u,f){let g=u._readIntoRequests;u._readIntoRequests=new P,g.forEach((E)=>{E._errorSteps(f)})}function Gm(u){return TypeError(`ReadableStreamBYOBReader.prototype.${u} can only be used on a ReadableStreamBYOBReader`)}function Ll(u,f){let{highWaterMark:g}=u;if(g===void 0)return f;if(uI(g)||g<0)throw RangeError("Invalid highWaterMark");return g}function Vm(u){let{size:f}=u;if(!f)return()=>1;return f}function Zm(u,f){Te(u,f);let g=u===null||u===void 0?void 0:u.highWaterMark,E=u===null||u===void 0?void 0:u.size;return{highWaterMark:g===void 0?void 0:ne(g),size:E===void 0?void 0:m7(E,`${f} has member 'size' that`)}}function m7(u,f){return Pe(u,f),(g)=>ne(u(g))}function h7(u,f){Te(u,f);let g=u===null||u===void 0?void 0:u.abort,E=u===null||u===void 0?void 0:u.close,I=u===null||u===void 0?void 0:u.start,B=u===null||u===void 0?void 0:u.type,W=u===null||u===void 0?void 0:u.write;return{abort:g===void 0?void 0:g7(g,u,`${f} has member 'abort' that`),close:E===void 0?void 0:y7(E,u,`${f} has member 'close' that`),start:I===void 0?void 0:b7(I,u,`${f} has member 'start' that`),write:W===void 0?void 0:x7(W,u,`${f} has member 'write' that`),type:B}}function g7(u,f,g){return Pe(u,g),(E)=>S(u,f,[E])}function y7(u,f,g){return Pe(u,g),()=>S(u,f,[])}function b7(u,f,g){return Pe(u,g),(E)=>A(u,f,[E])}function x7(u,f,g){return Pe(u,g),(E,I)=>S(u,f,[E,I])}function OI(u,f){if(!Jc(u))throw TypeError(`${f} is not a WritableStream.`)}function _7(u){if(typeof u!=="object"||u===null)return!1;try{return typeof u.aborted==="boolean"}catch(f){return!1}}let w7=typeof AbortController==="function";function S7(){if(w7)return new AbortController;return}class yi{constructor(u={},f={}){if(u===void 0)u=null;else yt(u,"First parameter");let g=Zm(f,"Second parameter"),E=h7(u,"First parameter");if(MI(this),E.type!==void 0)throw RangeError("Invalid type is specified");let B=Vm(g),W=Ll(g,1);z7(this,E,W,B)}get locked(){if(!Jc(this))throw Qm("locked");return Qc(this)}abort(u=void 0){if(!Jc(this))return l(Qm("abort"));if(Qc(this))return l(TypeError("Cannot abort a stream that already has a writer"));return Wm(this,u)}close(){if(!Jc(this))return l(Qm("close"));if(Qc(this))return l(TypeError("Cannot close a stream that already has a writer"));if(No(this))return l(TypeError("Cannot close an already-closing stream"));return $I(this)}getWriter(){if(!Jc(this))throw Qm("getWriter");return CI(this)}}if(Object.defineProperties(yi.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(yi.prototype.abort,"abort"),o(yi.prototype.close,"close"),o(yi.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(yi.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function CI(u){return new zo(u)}function v7(u,f,g,E,I=1,B=()=>1){let W=Object.create(yi.prototype);MI(W);let be=Object.create(Na.prototype);return UI(W,be,u,f,g,E,I,B),W}function MI(u){u._state="writable",u._storedError=void 0,u._writer=void 0,u._writableStreamController=void 0,u._writeRequests=new P,u._inFlightWriteRequest=void 0,u._closeRequest=void 0,u._inFlightCloseRequest=void 0,u._pendingAbortRequest=void 0,u._backpressure=!1}function Jc(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_writableStreamController"))return!1;return u instanceof yi}function Qc(u){if(u._writer===void 0)return!1;return!0}function Wm(u,f){var g;if(u._state==="closed"||u._state==="errored")return d(void 0);u._writableStreamController._abortReason=f,(g=u._writableStreamController._abortController)===null||g===void 0||g.abort(f);let E=u._state;if(E==="closed"||E==="errored")return d(void 0);if(u._pendingAbortRequest!==void 0)return u._pendingAbortRequest._promise;let I=!1;if(E==="erroring")I=!0,f=void 0;let B=c((W,be)=>{u._pendingAbortRequest={_promise:void 0,_resolve:W,_reject:be,_reason:f,_wasAlreadyErroring:I}});if(u._pendingAbortRequest._promise=B,!I)Mx(u,f);return B}function $I(u){let f=u._state;if(f==="closed"||f==="errored")return l(TypeError(`The stream (in ${f} state) is not in the writable state and cannot be closed`));let g=c((I,B)=>{let W={_resolve:I,_reject:B};u._closeRequest=W}),E=u._writer;if(E!==void 0&&u._backpressure&&f==="writable")Fx(E);return B7(u._writableStreamController),g}function T7(u){return c((g,E)=>{let I={_resolve:g,_reject:E};u._writeRequests.push(I)})}function Cx(u,f){if(u._state==="writable"){Mx(u,f);return}$x(u)}function Mx(u,f){let g=u._writableStreamController;u._state="erroring",u._storedError=f;let E=u._writer;if(E!==void 0)zI(E,f);if(!k7(u)&&g._started)$x(u)}function $x(u){u._state="errored",u._writableStreamController[O]();let f=u._storedError;if(u._writeRequests.forEach((I)=>{I._reject(f)}),u._writeRequests=new P,u._pendingAbortRequest===void 0){Km(u);return}let g=u._pendingAbortRequest;if(u._pendingAbortRequest=void 0,g._wasAlreadyErroring){g._reject(f),Km(u);return}let E=u._writableStreamController[k](g._reason);m(E,()=>(g._resolve(),Km(u),null),(I)=>(g._reject(I),Km(u),null))}function E7(u){u._inFlightWriteRequest._resolve(void 0),u._inFlightWriteRequest=void 0}function P7(u,f){u._inFlightWriteRequest._reject(f),u._inFlightWriteRequest=void 0,Cx(u,f)}function A7(u){if(u._inFlightCloseRequest._resolve(void 0),u._inFlightCloseRequest=void 0,u._state==="erroring"){if(u._storedError=void 0,u._pendingAbortRequest!==void 0)u._pendingAbortRequest._resolve(),u._pendingAbortRequest=void 0}u._state="closed";let g=u._writer;if(g!==void 0)HI(g)}function I7(u,f){if(u._inFlightCloseRequest._reject(f),u._inFlightCloseRequest=void 0,u._pendingAbortRequest!==void 0)u._pendingAbortRequest._reject(f),u._pendingAbortRequest=void 0;Cx(u,f)}function No(u){if(u._closeRequest===void 0&&u._inFlightCloseRequest===void 0)return!1;return!0}function k7(u){if(u._inFlightWriteRequest===void 0&&u._inFlightCloseRequest===void 0)return!1;return!0}function R7(u){u._inFlightCloseRequest=u._closeRequest,u._closeRequest=void 0}function O7(u){u._inFlightWriteRequest=u._writeRequests.shift()}function Km(u){if(u._closeRequest!==void 0)u._closeRequest._reject(u._storedError),u._closeRequest=void 0;let f=u._writer;if(f!==void 0)Dx(f,u._storedError)}function Nx(u,f){let g=u._writer;if(g!==void 0&&f!==u._backpressure)if(f)H7(g);else Fx(g);u._backpressure=f}class zo{constructor(u){if(ft(u,1,"WritableStreamDefaultWriter"),OI(u,"First parameter"),Qc(u))throw TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=u,u._writer=this;let f=u._state;if(f==="writable"){if(!No(u)&&u._backpressure)eh(this);else GI(this);Xm(this)}else if(f==="erroring")Ux(this,u._storedError),Xm(this);else if(f==="closed")GI(this),j7(this);else{let g=u._storedError;Ux(this,g),qI(this,g)}}get closed(){if(!$a(this))return l(za("closed"));return this._closedPromise}get desiredSize(){if(!$a(this))throw za("desiredSize");if(this._ownerWritableStream===void 0)throw Ul("desiredSize");return N7(this)}get ready(){if(!$a(this))return l(za("ready"));return this._readyPromise}abort(u=void 0){if(!$a(this))return l(za("abort"));if(this._ownerWritableStream===void 0)return l(Ul("abort"));return C7(this,u)}close(){if(!$a(this))return l(za("close"));let u=this._ownerWritableStream;if(u===void 0)return l(Ul("close"));if(No(u))return l(TypeError("Cannot close an already-closing stream"));return NI(this)}releaseLock(){if(!$a(this))throw za("releaseLock");if(this._ownerWritableStream===void 0)return;BI(this)}write(u=void 0){if(!$a(this))return l(za("write"));if(this._ownerWritableStream===void 0)return l(Ul("write to"));return LI(this,u)}}if(Object.defineProperties(zo.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(zo.prototype.abort,"abort"),o(zo.prototype.close,"close"),o(zo.prototype.releaseLock,"releaseLock"),o(zo.prototype.write,"write"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(zo.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function $a(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_ownerWritableStream"))return!1;return u instanceof zo}function C7(u,f){let g=u._ownerWritableStream;return Wm(g,f)}function NI(u){let f=u._ownerWritableStream;return $I(f)}function M7(u){let f=u._ownerWritableStream,g=f._state;if(No(f)||g==="closed")return d(void 0);if(g==="errored")return l(f._storedError);return NI(u)}function $7(u,f){if(u._closedPromiseState==="pending")Dx(u,f);else q7(u,f)}function zI(u,f){if(u._readyPromiseState==="pending")VI(u,f);else G7(u,f)}function N7(u){let f=u._ownerWritableStream,g=f._state;if(g==="errored"||g==="erroring")return null;if(g==="closed")return 0;return FI(f._writableStreamController)}function BI(u){let f=u._ownerWritableStream,g=TypeError("Writer was released and can no longer be used to monitor the stream's closedness");zI(u,g),$7(u,g),f._writer=void 0,u._ownerWritableStream=void 0}function LI(u,f){let g=u._ownerWritableStream,E=g._writableStreamController,I=L7(E,f);if(g!==u._ownerWritableStream)return l(Ul("write to"));let B=g._state;if(B==="errored")return l(g._storedError);if(No(g)||B==="closed")return l(TypeError("The stream is closing or closed and cannot be written to"));if(B==="erroring")return l(g._storedError);let W=T7(g);return D7(E,f,I),W}let DI={};class Na{constructor(){throw TypeError("Illegal constructor")}get abortReason(){if(!zx(this))throw Lx("abortReason");return this._abortReason}get signal(){if(!zx(this))throw Lx("signal");if(this._abortController===void 0)throw TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!zx(this))throw Lx("error");if(this._controlledWritableStream._state!=="writable")return;jI(this,u)}[k](u){let f=this._abortAlgorithm(u);return Ym(this),f}[O](){Ss(this)}}if(Object.defineProperties(Na.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Na.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function zx(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_controlledWritableStream"))return!1;return u instanceof Na}function UI(u,f,g,E,I,B,W,be){f._controlledWritableStream=u,u._writableStreamController=f,f._queue=void 0,f._queueTotalSize=void 0,Ss(f),f._abortReason=void 0,f._abortController=S7(),f._started=!1,f._strategySizeAlgorithm=be,f._strategyHWM=W,f._writeAlgorithm=E,f._closeAlgorithm=I,f._abortAlgorithm=B;let Re=Bx(f);Nx(u,Re);let Ue=g(),Ge=d(Ue);m(Ge,()=>(f._started=!0,Jm(f),null),(rt)=>(f._started=!0,Cx(u,rt),null))}function z7(u,f,g,E){let I=Object.create(Na.prototype),B,W,be,Re;if(f.start!==void 0)B=()=>f.start(I);else B=()=>{return};if(f.write!==void 0)W=(Ue)=>f.write(Ue,I);else W=()=>d(void 0);if(f.close!==void 0)be=()=>f.close();else be=()=>d(void 0);if(f.abort!==void 0)Re=(Ue)=>f.abort(Ue);else Re=()=>d(void 0);UI(u,I,B,W,be,Re,g,E)}function Ym(u){u._writeAlgorithm=void 0,u._closeAlgorithm=void 0,u._abortAlgorithm=void 0,u._strategySizeAlgorithm=void 0}function B7(u){Tx(u,DI,0),Jm(u)}function L7(u,f){try{return u._strategySizeAlgorithm(f)}catch(g){return Dl(u,g),1}}function FI(u){return u._strategyHWM-u._queueTotalSize}function D7(u,f,g){try{Tx(u,f,g)}catch(I){Dl(u,I);return}let E=u._controlledWritableStream;if(!No(E)&&E._state==="writable"){let I=Bx(u);Nx(E,I)}Jm(u)}function Jm(u){let f=u._controlledWritableStream;if(!u._started)return;if(f._inFlightWriteRequest!==void 0)return;if(f._state==="erroring"){$x(f);return}if(u._queue.length===0)return;let E=Xq(u);if(E===DI)U7(u);else F7(u,E)}function Dl(u,f){if(u._controlledWritableStream._state==="writable")jI(u,f)}function U7(u){let f=u._controlledWritableStream;R7(f),vx(u);let g=u._closeAlgorithm();Ym(u),m(g,()=>(A7(f),null),(E)=>(I7(f,E),null))}function F7(u,f){let g=u._controlledWritableStream;O7(g);let E=u._writeAlgorithm(f);m(E,()=>{E7(g);let I=g._state;if(vx(u),!No(g)&&I==="writable"){let B=Bx(u);Nx(g,B)}return Jm(u),null},(I)=>{if(g._state==="writable")Ym(u);return P7(g,I),null})}function Bx(u){return FI(u)<=0}function jI(u,f){let g=u._controlledWritableStream;Ym(u),Mx(g,f)}function Qm(u){return TypeError(`WritableStream.prototype.${u} can only be used on a WritableStream`)}function Lx(u){return TypeError(`WritableStreamDefaultController.prototype.${u} can only be used on a WritableStreamDefaultController`)}function za(u){return TypeError(`WritableStreamDefaultWriter.prototype.${u} can only be used on a WritableStreamDefaultWriter`)}function Ul(u){return TypeError("Cannot "+u+" a stream using a released writer")}function Xm(u){u._closedPromise=c((f,g)=>{u._closedPromise_resolve=f,u._closedPromise_reject=g,u._closedPromiseState="pending"})}function qI(u,f){Xm(u),Dx(u,f)}function j7(u){Xm(u),HI(u)}function Dx(u,f){if(u._closedPromise_reject===void 0)return;_(u._closedPromise),u._closedPromise_reject(f),u._closedPromise_resolve=void 0,u._closedPromise_reject=void 0,u._closedPromiseState="rejected"}function q7(u,f){qI(u,f)}function HI(u){if(u._closedPromise_resolve===void 0)return;u._closedPromise_resolve(void 0),u._closedPromise_resolve=void 0,u._closedPromise_reject=void 0,u._closedPromiseState="resolved"}function eh(u){u._readyPromise=c((f,g)=>{u._readyPromise_resolve=f,u._readyPromise_reject=g}),u._readyPromiseState="pending"}function Ux(u,f){eh(u),VI(u,f)}function GI(u){eh(u),Fx(u)}function VI(u,f){if(u._readyPromise_reject===void 0)return;_(u._readyPromise),u._readyPromise_reject(f),u._readyPromise_resolve=void 0,u._readyPromise_reject=void 0,u._readyPromiseState="rejected"}function H7(u){eh(u)}function G7(u,f){Ux(u,f)}function Fx(u){if(u._readyPromise_resolve===void 0)return;u._readyPromise_resolve(void 0),u._readyPromise_resolve=void 0,u._readyPromise_reject=void 0,u._readyPromiseState="fulfilled"}function V7(){if(typeof globalThis<"u")return globalThis;else if(typeof self<"u")return self;else if(typeof global<"u")return global;return}let jx=V7();function Z7(u){if(!(typeof u==="function"||typeof u==="object"))return!1;if(u.name!=="DOMException")return!1;try{return new u,!0}catch(f){return!1}}function W7(){let u=jx===null||jx===void 0?void 0:jx.DOMException;return Z7(u)?u:void 0}function K7(){let u=function(g,E){if(this.message=g||"",this.name=E||"Error",Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)};return o(u,"DOMException"),u.prototype=Object.create(Error.prototype),Object.defineProperty(u.prototype,"constructor",{value:u,writable:!0,configurable:!0}),u}let Y7=W7()||K7();function ZI(u,f,g,E,I,B){let W=bt(u),be=CI(f);u._disturbed=!0;let Re=!1,Ue=d(void 0);return c((Ge,rt)=>{let It;if(B!==void 0){if(It=()=>{let Ne=B.reason!==void 0?B.reason:new Y7("Aborted","AbortError"),ot=[];if(!E)ot.push(()=>{if(f._state==="writable")return Wm(f,Ne);return d(void 0)});if(!I)ot.push(()=>{if(u._state==="readable")return oo(u,Ne);return d(void 0)});cn(()=>Promise.all(ot.map((Ct)=>Ct())),!0,Ne)},B.aborted){It();return}B.addEventListener("abort",It)}function xi(){return c((Ne,ot)=>{function Ct(vn){if(vn)Ne();else p(ru(),Ct,ot)}Ct(!1)})}function ru(){if(Re)return d(!0);return p(be._readyPromise,()=>c((Ne,ot)=>{$l(W,{_chunkSteps:(Ct)=>{Ue=p(LI(be,Ct),void 0,t),Ne(!1)},_closeSteps:()=>Ne(!0),_errorSteps:ot})}))}if(_i(u,W._closedPromise,(Ne)=>{if(!E)cn(()=>Wm(f,Ne),!0,Ne);else Ln(!0,Ne);return null}),_i(f,be._closedPromise,(Ne)=>{if(!I)cn(()=>oo(u,Ne),!0,Ne);else Ln(!0,Ne);return null}),Gr(u,W._closedPromise,()=>{if(!g)cn(()=>M7(be));else Ln();return null}),No(f)||f._state==="closed"){let Ne=TypeError("the destination writable stream closed before all data could be piped to it");if(!I)cn(()=>oo(u,Ne),!0,Ne);else Ln(!0,Ne)}_(xi());function Ps(){let Ne=Ue;return p(Ue,()=>Ne!==Ue?Ps():void 0)}function _i(Ne,ot,Ct){if(Ne._state==="errored")Ct(Ne._storedError);else y(ot,Ct)}function Gr(Ne,ot,Ct){if(Ne._state==="closed")Ct();else h(ot,Ct)}function cn(Ne,ot,Ct){if(Re)return;if(Re=!0,f._state==="writable"&&!No(f))h(Ps(),vn);else vn();function vn(){return m(Ne(),()=>wi(ot,Ct),(nu)=>wi(!0,nu)),null}}function Ln(Ne,ot){if(Re)return;if(Re=!0,f._state==="writable"&&!No(f))h(Ps(),()=>wi(Ne,ot));else wi(Ne,ot)}function wi(Ne,ot){if(BI(be),re(W),B!==void 0)B.removeEventListener("abort",It);if(Ne)rt(ot);else Ge(void 0);return null}})}class Bo{constructor(){throw TypeError("Illegal constructor")}get desiredSize(){if(!th(this))throw nh("desiredSize");return qx(this)}close(){if(!th(this))throw nh("close");if(!eu(this))throw TypeError("The stream is not in a state that permits close");Ba(this)}enqueue(u=void 0){if(!th(this))throw nh("enqueue");if(!eu(this))throw TypeError("The stream is not in a state that permits enqueue");return Xc(this,u)}error(u=void 0){if(!th(this))throw nh("error");no(this,u)}[N](u){Ss(this);let f=this._cancelAlgorithm(u);return rh(this),f}[j](u){let f=this._controlledReadableStream;if(this._queue.length>0){let g=vx(this);if(this._closeRequested&&this._queue.length===0)rh(this),ql(f);else Fl(this);u._chunkSteps(g)}else xt(f,u),Fl(this)}[R](){}}if(Object.defineProperties(Bo.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Bo.prototype.close,"close"),o(Bo.prototype.enqueue,"enqueue"),o(Bo.prototype.error,"error"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Bo.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function th(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_controlledReadableStream"))return!1;return u instanceof Bo}function Fl(u){if(!WI(u))return;if(u._pulling){u._pullAgain=!0;return}u._pulling=!0;let g=u._pullAlgorithm();m(g,()=>{if(u._pulling=!1,u._pullAgain)u._pullAgain=!1,Fl(u);return null},(E)=>(no(u,E),null))}function WI(u){let f=u._controlledReadableStream;if(!eu(u))return!1;if(!u._started)return!1;if(Es(f)&&vt(f)>0)return!0;if(qx(u)>0)return!0;return!1}function rh(u){u._pullAlgorithm=void 0,u._cancelAlgorithm=void 0,u._strategySizeAlgorithm=void 0}function Ba(u){if(!eu(u))return;let f=u._controlledReadableStream;if(u._closeRequested=!0,u._queue.length===0)rh(u),ql(f)}function Xc(u,f){if(!eu(u))return;let g=u._controlledReadableStream;if(Es(g)&&vt(g)>0)Qe(g,f,!1);else{let E;try{E=u._strategySizeAlgorithm(f)}catch(I){throw no(u,I),I}try{Tx(u,f,E)}catch(I){throw no(u,I),I}}Fl(u)}function no(u,f){let g=u._controlledReadableStream;if(g._state!=="readable")return;Ss(u),rh(u),QI(g,f)}function qx(u){let f=u._controlledReadableStream._state;if(f==="errored")return null;if(f==="closed")return 0;return u._strategyHWM-u._queueTotalSize}function J7(u){if(WI(u))return!1;return!0}function eu(u){let f=u._controlledReadableStream._state;if(!u._closeRequested&&f==="readable")return!0;return!1}function KI(u,f,g,E,I,B,W){f._controlledReadableStream=u,f._queue=void 0,f._queueTotalSize=void 0,Ss(f),f._started=!1,f._closeRequested=!1,f._pullAgain=!1,f._pulling=!1,f._strategySizeAlgorithm=W,f._strategyHWM=B,f._pullAlgorithm=E,f._cancelAlgorithm=I,u._readableStreamController=f;let be=g();m(d(be),()=>(f._started=!0,Fl(f),null),(Re)=>(no(f,Re),null))}function Q7(u,f,g,E){let I=Object.create(Bo.prototype),B,W,be;if(f.start!==void 0)B=()=>f.start(I);else B=()=>{return};if(f.pull!==void 0)W=()=>f.pull(I);else W=()=>d(void 0);if(f.cancel!==void 0)be=(Re)=>f.cancel(Re);else be=()=>d(void 0);KI(u,I,B,W,be,g,E)}function nh(u){return TypeError(`ReadableStreamDefaultController.prototype.${u} can only be used on a ReadableStreamDefaultController`)}function X7(u,f){if(Oa(u._readableStreamController))return tH(u);return eH(u)}function eH(u,f){let g=bt(u),E=!1,I=!1,B=!1,W=!1,be,Re,Ue,Ge,rt,It=c((Gr)=>{rt=Gr});function xi(){if(E)return I=!0,d(void 0);return E=!0,$l(g,{_chunkSteps:(cn)=>{w(()=>{I=!1;let Ln=cn,wi=cn;if(!B)Xc(Ue._readableStreamController,Ln);if(!W)Xc(Ge._readableStreamController,wi);if(E=!1,I)xi()})},_closeSteps:()=>{if(E=!1,!B)Ba(Ue._readableStreamController);if(!W)Ba(Ge._readableStreamController);if(!B||!W)rt(void 0)},_errorSteps:()=>{E=!1}}),d(void 0)}function ru(Gr){if(B=!0,be=Gr,W){let cn=Nl([be,Re]),Ln=oo(u,cn);rt(Ln)}return It}function Ps(Gr){if(W=!0,Re=Gr,B){let cn=Nl([be,Re]),Ln=oo(u,cn);rt(Ln)}return It}function _i(){}return Ue=jl(_i,xi,ru),Ge=jl(_i,xi,Ps),y(g._closedPromise,(Gr)=>{if(no(Ue._readableStreamController,Gr),no(Ge._readableStreamController,Gr),!B||!W)rt(void 0);return null}),[Ue,Ge]}function tH(u){let f=bt(u),g=!1,E=!1,I=!1,B=!1,W=!1,be,Re,Ue,Ge,rt,It=c((Ne)=>{rt=Ne});function xi(Ne){y(Ne._closedPromise,(ot)=>{if(Ne!==f)return null;if(Bn(Ue._readableStreamController,ot),Bn(Ge._readableStreamController,ot),!B||!W)rt(void 0);return null})}function ru(){if(Ma(f))re(f),f=bt(u),xi(f);$l(f,{_chunkSteps:(ot)=>{w(()=>{E=!1,I=!1;let Ct=ot,vn=ot;if(!B&&!W)try{vn=fI(ot)}catch(nu){Bn(Ue._readableStreamController,nu),Bn(Ge._readableStreamController,nu),rt(oo(u,nu));return}if(!B)jm(Ue._readableStreamController,Ct);if(!W)jm(Ge._readableStreamController,vn);if(g=!1,E)_i();else if(I)Gr()})},_closeSteps:()=>{if(g=!1,!B)zl(Ue._readableStreamController);if(!W)zl(Ge._readableStreamController);if(Ue._readableStreamController._pendingPullIntos.length>0)qm(Ue._readableStreamController,0);if(Ge._readableStreamController._pendingPullIntos.length>0)qm(Ge._readableStreamController,0);if(!B||!W)rt(void 0)},_errorSteps:()=>{g=!1}})}function Ps(Ne,ot){if(_s(f))re(f),f=PI(u),xi(f);let Ct=ot?Ge:Ue,vn=ot?Ue:Ge;kI(f,Ne,1,{_chunkSteps:(ou)=>{w(()=>{E=!1,I=!1;let iu=ot?W:B;if(!(ot?B:W)){let lk;try{lk=fI(ou)}catch(Wx){Bn(Ct._readableStreamController,Wx),Bn(vn._readableStreamController,Wx),rt(oo(u,Wx));return}if(!iu)Hm(Ct._readableStreamController,ou);jm(vn._readableStreamController,lk)}else if(!iu)Hm(Ct._readableStreamController,ou);if(g=!1,E)_i();else if(I)Gr()})},_closeSteps:(ou)=>{g=!1;let iu=ot?W:B,ch=ot?B:W;if(!iu)zl(Ct._readableStreamController);if(!ch)zl(vn._readableStreamController);if(ou!==void 0){if(!iu)Hm(Ct._readableStreamController,ou);if(!ch&&vn._readableStreamController._pendingPullIntos.length>0)qm(vn._readableStreamController,0)}if(!iu||!ch)rt(void 0)},_errorSteps:()=>{g=!1}})}function _i(){if(g)return E=!0,d(void 0);g=!0;let Ne=kx(Ue._readableStreamController);if(Ne===null)ru();else Ps(Ne._view,!1);return d(void 0)}function Gr(){if(g)return I=!0,d(void 0);g=!0;let Ne=kx(Ge._readableStreamController);if(Ne===null)ru();else Ps(Ne._view,!0);return d(void 0)}function cn(Ne){if(B=!0,be=Ne,W){let ot=Nl([be,Re]),Ct=oo(u,ot);rt(Ct)}return It}function Ln(Ne){if(W=!0,Re=Ne,B){let ot=Nl([be,Re]),Ct=oo(u,ot);rt(Ct)}return It}function wi(){return}return Ue=JI(wi,_i,cn),Ge=JI(wi,Gr,Ln),xi(f),[Ue,Ge]}function rH(u){return r(u)&&typeof u.getReader<"u"}function nH(u){if(rH(u))return iH(u.getReader());return oH(u)}function oH(u){let f,g=pI(u,"async"),E=t;function I(){let W;try{W=Kq(g)}catch(Re){return l(Re)}let be=d(W);return x(be,(Re)=>{if(!r(Re))throw TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Yq(Re))Ba(f._readableStreamController);else{let Ge=Jq(Re);Xc(f._readableStreamController,Ge)}})}function B(W){let be=g.iterator,Re;try{Re=Dm(be,"return")}catch(rt){return l(rt)}if(Re===void 0)return d(void 0);let Ue;try{Ue=A(Re,be,[W])}catch(rt){return l(rt)}let Ge=d(Ue);return x(Ge,(rt)=>{if(!r(rt))throw TypeError("The promise returned by the iterator.return() method must fulfill with an object");return})}return f=jl(E,I,B,0),f}function iH(u){let f,g=t;function E(){let B;try{B=u.read()}catch(W){return l(W)}return x(B,(W)=>{if(!r(W))throw TypeError("The promise returned by the reader.read() method must fulfill with an object");if(W.done)Ba(f._readableStreamController);else{let be=W.value;Xc(f._readableStreamController,be)}})}function I(B){try{return d(u.cancel(B))}catch(W){return l(W)}}return f=jl(g,E,I,0),f}function sH(u,f){Te(u,f);let g=u,E=g===null||g===void 0?void 0:g.autoAllocateChunkSize,I=g===null||g===void 0?void 0:g.cancel,B=g===null||g===void 0?void 0:g.pull,W=g===null||g===void 0?void 0:g.start,be=g===null||g===void 0?void 0:g.type;return{autoAllocateChunkSize:E===void 0?void 0:Q(E,`${f} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:aH(I,g,`${f} has member 'cancel' that`),pull:B===void 0?void 0:cH(B,g,`${f} has member 'pull' that`),start:W===void 0?void 0:uH(W,g,`${f} has member 'start' that`),type:be===void 0?void 0:dH(be,`${f} has member 'type' that`)}}function aH(u,f,g){return Pe(u,g),(E)=>S(u,f,[E])}function cH(u,f,g){return Pe(u,g),(E)=>S(u,f,[E])}function uH(u,f,g){return Pe(u,g),(E)=>A(u,f,[E])}function dH(u,f){if(u=`${u}`,u!=="bytes")throw TypeError(`${f} '${u}' is not a valid enumeration value for ReadableStreamType`);return u}function lH(u,f){Te(u,f);let g=u===null||u===void 0?void 0:u.preventCancel;return{preventCancel:Boolean(g)}}function YI(u,f){Te(u,f);let g=u===null||u===void 0?void 0:u.preventAbort,E=u===null||u===void 0?void 0:u.preventCancel,I=u===null||u===void 0?void 0:u.preventClose,B=u===null||u===void 0?void 0:u.signal;if(B!==void 0)pH(B,`${f} has member 'signal' that`);return{preventAbort:Boolean(g),preventCancel:Boolean(E),preventClose:Boolean(I),signal:B}}function pH(u,f){if(!_7(u))throw TypeError(`${f} is not an AbortSignal.`)}function fH(u,f){Te(u,f);let g=u===null||u===void 0?void 0:u.readable;q(g,"readable","ReadableWritablePair"),Be(g,`${f} has member 'readable' that`);let E=u===null||u===void 0?void 0:u.writable;return q(E,"writable","ReadableWritablePair"),OI(E,`${f} has member 'writable' that`),{readable:g,writable:E}}class Pr{constructor(u={},f={}){if(u===void 0)u=null;else yt(u,"First parameter");let g=Zm(f,"Second parameter"),E=sH(u,"First parameter");if(Hx(this),E.type==="bytes"){if(g.size!==void 0)throw RangeError("The strategy for a byte stream cannot have a size function");let I=Ll(g,0);a7(this,E,I)}else{let I=Vm(g),B=Ll(g,1);Q7(this,E,B,I)}}get locked(){if(!Ts(this))throw La("locked");return Es(this)}cancel(u=void 0){if(!Ts(this))return l(La("cancel"));if(Es(this))return l(TypeError("Cannot cancel a stream that already has a reader"));return oo(this,u)}getReader(u=void 0){if(!Ts(this))throw La("getReader");if(u7(u,"First parameter").mode===void 0)return bt(this);return PI(this)}pipeThrough(u,f={}){if(!Ts(this))throw La("pipeThrough");ft(u,1,"pipeThrough");let g=fH(u,"First parameter"),E=YI(f,"Second parameter");if(Es(this))throw TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Qc(g.writable))throw TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let I=ZI(this,g.writable,E.preventClose,E.preventAbort,E.preventCancel,E.signal);return _(I),g.readable}pipeTo(u,f={}){if(!Ts(this))return l(La("pipeTo"));if(u===void 0)return l("Parameter 1 is required in 'pipeTo'.");if(!Jc(u))return l(TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let g;try{g=YI(f,"Second parameter")}catch(E){return l(E)}if(Es(this))return l(TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(Qc(u))return l(TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));return ZI(this,u,g.preventClose,g.preventAbort,g.preventCancel,g.signal)}tee(){if(!Ts(this))throw La("tee");let u=X7(this);return Nl(u)}values(u=void 0){if(!Ts(this))throw La("values");let f=lH(u,"First parameter");return Zq(this,f.preventCancel)}[Sx](u){return this.values(u)}static from(u){return nH(u)}}if(Object.defineProperties(Pr,{from:{enumerable:!0}}),Object.defineProperties(Pr.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Pr.from,"from"),o(Pr.prototype.cancel,"cancel"),o(Pr.prototype.getReader,"getReader"),o(Pr.prototype.pipeThrough,"pipeThrough"),o(Pr.prototype.pipeTo,"pipeTo"),o(Pr.prototype.tee,"tee"),o(Pr.prototype.values,"values"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Pr.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0});Object.defineProperty(Pr.prototype,Sx,{value:Pr.prototype.values,writable:!0,configurable:!0});function jl(u,f,g,E=1,I=()=>1){let B=Object.create(Pr.prototype);Hx(B);let W=Object.create(Bo.prototype);return KI(B,W,u,f,g,E,I),B}function JI(u,f,g){let E=Object.create(Pr.prototype);Hx(E);let I=Object.create($o.prototype);return EI(E,I,u,f,g,0,void 0),E}function Hx(u){u._state="readable",u._reader=void 0,u._storedError=void 0,u._disturbed=!1}function Ts(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_readableStreamController"))return!1;return u instanceof Pr}function Es(u){if(u._reader===void 0)return!1;return!0}function oo(u,f){if(u._disturbed=!0,u._state==="closed")return d(void 0);if(u._state==="errored")return l(u._storedError);ql(u);let g=u._reader;if(g!==void 0&&Ma(g)){let I=g._readIntoRequests;g._readIntoRequests=new P,I.forEach((B)=>{B._closeSteps(void 0)})}let E=u._readableStreamController[N](f);return x(E,t)}function ql(u){u._state="closed";let f=u._reader;if(f===void 0)return;if(Y(f),_s(f)){let g=f._readRequests;f._readRequests=new P,g.forEach((E)=>{E._closeSteps()})}}function QI(u,f){u._state="errored",u._storedError=f;let g=u._reader;if(g===void 0)return;if(z(g,f),_s(g))iI(g,f);else RI(g,f)}function La(u){return TypeError(`ReadableStream.prototype.${u} can only be used on a ReadableStream`)}function XI(u,f){Te(u,f);let g=u===null||u===void 0?void 0:u.highWaterMark;return q(g,"highWaterMark","QueuingStrategyInit"),{highWaterMark:ne(g)}}let ek=(u)=>u.byteLength;o(ek,"size");class Hl{constructor(u){ft(u,1,"ByteLengthQueuingStrategy"),u=XI(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!rk(this))throw tk("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!rk(this))throw tk("size");return ek}}if(Object.defineProperties(Hl.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Hl.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function tk(u){return TypeError(`ByteLengthQueuingStrategy.prototype.${u} can only be used on a ByteLengthQueuingStrategy`)}function rk(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_byteLengthQueuingStrategyHighWaterMark"))return!1;return u instanceof Hl}let nk=()=>1;o(nk,"size");class Gl{constructor(u){ft(u,1,"CountQueuingStrategy"),u=XI(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!ik(this))throw ok("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ik(this))throw ok("size");return nk}}if(Object.defineProperties(Gl.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Gl.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function ok(u){return TypeError(`CountQueuingStrategy.prototype.${u} can only be used on a CountQueuingStrategy`)}function ik(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_countQueuingStrategyHighWaterMark"))return!1;return u instanceof Gl}function mH(u,f){Te(u,f);let g=u===null||u===void 0?void 0:u.cancel,E=u===null||u===void 0?void 0:u.flush,I=u===null||u===void 0?void 0:u.readableType,B=u===null||u===void 0?void 0:u.start,W=u===null||u===void 0?void 0:u.transform,be=u===null||u===void 0?void 0:u.writableType;return{cancel:g===void 0?void 0:bH(g,u,`${f} has member 'cancel' that`),flush:E===void 0?void 0:hH(E,u,`${f} has member 'flush' that`),readableType:I,start:B===void 0?void 0:gH(B,u,`${f} has member 'start' that`),transform:W===void 0?void 0:yH(W,u,`${f} has member 'transform' that`),writableType:be}}function hH(u,f,g){return Pe(u,g),(E)=>S(u,f,[E])}function gH(u,f,g){return Pe(u,g),(E)=>A(u,f,[E])}function yH(u,f,g){return Pe(u,g),(E,I)=>S(u,f,[E,I])}function bH(u,f,g){return Pe(u,g),(E)=>S(u,f,[E])}class Vl{constructor(u={},f={},g={}){if(u===void 0)u=null;let E=Zm(f,"Second parameter"),I=Zm(g,"Third parameter"),B=mH(u,"First parameter");if(B.readableType!==void 0)throw RangeError("Invalid readableType specified");if(B.writableType!==void 0)throw RangeError("Invalid writableType specified");let W=Ll(I,0),be=Vm(I),Re=Ll(E,1),Ue=Vm(E),Ge,rt=c((It)=>{Ge=It});if(xH(this,rt,Re,Ue,W,be),wH(this,B),B.start!==void 0)Ge(B.start(this._transformStreamController));else Ge(void 0)}get readable(){if(!sk(this))throw dk("readable");return this._readable}get writable(){if(!sk(this))throw dk("writable");return this._writable}}if(Object.defineProperties(Vl.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Vl.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function xH(u,f,g,E,I,B){function W(){return f}function be(It){return TH(u,It)}function Re(It){return EH(u,It)}function Ue(){return PH(u)}u._writable=v7(W,be,Ue,Re,g,E);function Ge(){return AH(u)}function rt(It){return IH(u,It)}u._readable=jl(W,Ge,rt,I,B),u._backpressure=void 0,u._backpressureChangePromise=void 0,u._backpressureChangePromise_resolve=void 0,oh(u,!0),u._transformStreamController=void 0}function sk(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_transformStreamController"))return!1;return u instanceof Vl}function ak(u,f){no(u._readable._readableStreamController,f),Gx(u,f)}function Gx(u,f){sh(u._transformStreamController),Dl(u._writable._writableStreamController,f),Vx(u)}function Vx(u){if(u._backpressure)oh(u,!1)}function oh(u,f){if(u._backpressureChangePromise!==void 0)u._backpressureChangePromise_resolve();u._backpressureChangePromise=c((g)=>{u._backpressureChangePromise_resolve=g}),u._backpressure=f}class bi{constructor(){throw TypeError("Illegal constructor")}get desiredSize(){if(!ih(this))throw ah("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return qx(u)}enqueue(u=void 0){if(!ih(this))throw ah("enqueue");ck(this,u)}error(u=void 0){if(!ih(this))throw ah("error");SH(this,u)}terminate(){if(!ih(this))throw ah("terminate");vH(this)}}if(Object.defineProperties(bi.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(bi.prototype.enqueue,"enqueue"),o(bi.prototype.error,"error"),o(bi.prototype.terminate,"terminate"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(bi.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ih(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_controlledTransformStream"))return!1;return u instanceof bi}function _H(u,f,g,E,I){f._controlledTransformStream=u,u._transformStreamController=f,f._transformAlgorithm=g,f._flushAlgorithm=E,f._cancelAlgorithm=I,f._finishPromise=void 0,f._finishPromise_resolve=void 0,f._finishPromise_reject=void 0}function wH(u,f){let g=Object.create(bi.prototype),E,I,B;if(f.transform!==void 0)E=(W)=>f.transform(W,g);else E=(W)=>{try{return ck(g,W),d(void 0)}catch(be){return l(be)}};if(f.flush!==void 0)I=()=>f.flush(g);else I=()=>d(void 0);if(f.cancel!==void 0)B=(W)=>f.cancel(W);else B=()=>d(void 0);_H(u,g,E,I,B)}function sh(u){u._transformAlgorithm=void 0,u._flushAlgorithm=void 0,u._cancelAlgorithm=void 0}function ck(u,f){let g=u._controlledTransformStream,E=g._readable._readableStreamController;if(!eu(E))throw TypeError("Readable side is not in a state that permits enqueue");try{Xc(E,f)}catch(B){throw Gx(g,B),g._readable._storedError}if(J7(E)!==g._backpressure)oh(g,!0)}function SH(u,f){ak(u._controlledTransformStream,f)}function uk(u,f){let g=u._transformAlgorithm(f);return x(g,void 0,(E)=>{throw ak(u._controlledTransformStream,E),E})}function vH(u){let f=u._controlledTransformStream,g=f._readable._readableStreamController;Ba(g);let E=TypeError("TransformStream terminated");Gx(f,E)}function TH(u,f){let g=u._transformStreamController;if(u._backpressure){let E=u._backpressureChangePromise;return x(E,()=>{let I=u._writable;if(I._state==="erroring")throw I._storedError;return uk(g,f)})}return uk(g,f)}function EH(u,f){let g=u._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let E=u._readable;g._finishPromise=c((B,W)=>{g._finishPromise_resolve=B,g._finishPromise_reject=W});let I=g._cancelAlgorithm(f);return sh(g),m(I,()=>{if(E._state==="errored")tu(g,E._storedError);else no(E._readableStreamController,f),Zx(g);return null},(B)=>(no(E._readableStreamController,B),tu(g,B),null)),g._finishPromise}function PH(u){let f=u._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let g=u._readable;f._finishPromise=c((I,B)=>{f._finishPromise_resolve=I,f._finishPromise_reject=B});let E=f._flushAlgorithm();return sh(f),m(E,()=>{if(g._state==="errored")tu(f,g._storedError);else Ba(g._readableStreamController),Zx(f);return null},(I)=>(no(g._readableStreamController,I),tu(f,I),null)),f._finishPromise}function AH(u){return oh(u,!1),u._backpressureChangePromise}function IH(u,f){let g=u._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let E=u._writable;g._finishPromise=c((B,W)=>{g._finishPromise_resolve=B,g._finishPromise_reject=W});let I=g._cancelAlgorithm(f);return sh(g),m(I,()=>{if(E._state==="errored")tu(g,E._storedError);else Dl(E._writableStreamController,f),Vx(u),Zx(g);return null},(B)=>(Dl(E._writableStreamController,B),Vx(u),tu(g,B),null)),g._finishPromise}function ah(u){return TypeError(`TransformStreamDefaultController.prototype.${u} can only be used on a TransformStreamDefaultController`)}function Zx(u){if(u._finishPromise_resolve===void 0)return;u._finishPromise_resolve(),u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function tu(u,f){if(u._finishPromise_reject===void 0)return;_(u._finishPromise),u._finishPromise_reject(f),u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function dk(u){return TypeError(`TransformStream.prototype.${u} can only be used on a TransformStream`)}e.ByteLengthQueuingStrategy=Hl,e.CountQueuingStrategy=Gl,e.ReadableByteStreamController=$o,e.ReadableStream=Pr,e.ReadableStreamBYOBReader=gi,e.ReadableStreamBYOBRequest=vs,e.ReadableStreamDefaultController=Bo,e.ReadableStreamDefaultReader=Hr,e.TransformStream=Vl,e.TransformStreamDefaultController=bi,e.WritableStream=yi,e.WritableStreamDefaultController=Na,e.WritableStreamDefaultWriter=zo})});var gk=ie(function(){if(!globalThis.ReadableStream)try{let e=Lt("node:process"),{emitWarning:t}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,Lt("node:stream/web")),e.emitWarning=t}catch(r){throw e.emitWarning=t,r}}catch(e){Object.assign(globalThis,hk())}try{let{Blob:e}=Lt("buffer");if(e&&!e.prototype.stream)e.prototype.stream=function(r){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(i){let a=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();if(n+=a.byteLength,i.enqueue(new Uint8Array(a)),n===o.size)i.close()}})}}catch(e){}});async function*Yx(e,t=!0){for(let r of e)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(t){let n=r.byteOffset,o=r.byteOffset+r.byteLength;while(n!==o){let i=Math.min(o-n,yk),s=r.buffer.slice(n,n+i);n+=s.byteLength,yield new Uint8Array(s)}}else yield r;else{let n=0,o=r;while(n!==o.size){let s=await o.slice(n,Math.min(o.size,n+yk)).arrayBuffer();n+=s.byteLength,yield new Uint8Array(s)}}}var vpe,yk=65536,bk,UH,Si;var Zl=V(()=>{vpe=Vr(gk(),1);/*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */bk=class e{#e=[];#t="";#r=0;#n="transparent";constructor(t=[],r={}){if(typeof t!=="object"||t===null)throw TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!=="function")throw TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof r!=="object"&&typeof r!=="function")throw TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");if(r===null)r={};let n=new TextEncoder;for(let i of t){let s;if(ArrayBuffer.isView(i))s=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength));else if(i instanceof ArrayBuffer)s=new Uint8Array(i.slice(0));else if(i instanceof e)s=i;else s=n.encode(`${i}`);this.#r+=ArrayBuffer.isView(s)?s.byteLength:s.size,this.#e.push(s)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let o=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let t=new TextDecoder,r="";for await(let n of Yx(this.#e,!1))r+=t.decode(n,{stream:!0});return r+=t.decode(),r}async arrayBuffer(){let t=new Uint8Array(this.size),r=0;for await(let n of Yx(this.#e,!1))t.set(n,r),r+=n.length;return t.buffer}stream(){let t=Yx(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let n=await t.next();n.done?r.close():r.enqueue(n.value)},async cancel(){await t.return()}})}slice(t=0,r=this.size,n=""){let{size:o}=this,i=t<0?Math.max(o+t,0):Math.min(t,o),s=r<0?Math.max(o+r,0):Math.min(r,o),a=Math.max(s-i,0),c=this.#e,d=[],l=0;for(let m of c){if(l>=a)break;let h=ArrayBuffer.isView(m)?m.byteLength:m.size;if(i&&h<=i)i-=h,s-=h;else{let y;if(ArrayBuffer.isView(m))y=m.subarray(i,Math.min(h,s)),l+=y.byteLength;else y=m.slice(i,Math.min(h,s)),l+=y.size;s-=h,d.push(y),i=0}}let p=new e([],{type:String(n).toLowerCase()});return p.#r=a,p.#e=d,p}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](t){return t&&typeof t==="object"&&typeof t.constructor==="function"&&(typeof t.stream==="function"||typeof t.arrayBuffer==="function")&&/^(Blob|File)$/.test(t[Symbol.toStringTag])}};Object.defineProperties(bk.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});UH=bk,Si=UH});var FH,jH,su;var Jx=V(()=>{Zl();FH=class extends Si{#e=0;#t="";constructor(t,r,n={}){if(arguments.length<2)throw TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,n);if(n===null)n={};let o=n.lastModified===void 0?Date.now():Number(n.lastModified);if(!Number.isNaN(o))this.#e=o;this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Si&&/^(File)$/.test(t[Symbol.toStringTag])}},jH=FH,su=jH});function wk(e,t=Si){var r=`${xk()}${xk()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${r}\r
|
|
2
|
+
import{createRequire as LH}from"node:module";var kH=Object.create;var{getPrototypeOf:RH,defineProperty:Kx,getOwnPropertyNames:OH}=Object;var pk=Object.prototype.hasOwnProperty;function CH(e){return this[e]}var MH,$H,Vr=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?MH??=new WeakMap:$H??=new WeakMap,i=o.get(e);if(i)return i}r=e!=null?kH(RH(e)):{};let s=t||!e||!e.__esModule||!pk.call(e,"default")?Kx(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of OH(e))if(!pk.call(s,a))Kx(s,a,{get:CH.bind(e,a),enumerable:!0})}if(n)o.set(e,s);return s};var ie=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var NH=(e)=>e;function zH(e,t){this[e]=NH.bind(null,t)}var BH=(e,t)=>{for(var r in t)Kx(e,r,{get:t[r],enumerable:!0,configurable:!0,set:zH.bind(t,r)})};var V=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var Lt=LH(import.meta.url);var hk=ie(function(uh,mk){(function(e,t){typeof uh==="object"&&typeof mk<"u"?t(uh):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.WebStreamsPolyfill={}))})(uh,function(e){function t(){return}function r(u){return typeof u==="object"&&u!==null||typeof u==="function"}let n=t;function o(u,f){try{Object.defineProperty(u,"name",{value:f,configurable:!0})}catch(g){}}let i=Promise,s=Promise.prototype.then,a=Promise.reject.bind(i);function c(u){return new i(u)}function d(u){return c((f)=>f(u))}function l(u){return a(u)}function p(u,f,g){return s.call(u,f,g)}function m(u,f,g){p(p(u,f,g),void 0,n)}function h(u,f){m(u,f)}function y(u,f){m(u,void 0,f)}function x(u,f,g){return p(u,f,g)}function _(u){p(u,void 0,n)}let w=(u)=>{if(typeof queueMicrotask==="function")w=queueMicrotask;else{let f=d(void 0);w=(g)=>p(f,g)}return w(u)};function A(u,f,g){if(typeof u!=="function")throw TypeError("Argument is not a function");return Function.prototype.apply.call(u,f,g)}function S(u,f,g){try{return d(A(u,f,g))}catch(E){return l(E)}}let v=16384;class P{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(u){let f=this._back,g=f;if(f._elements.length===v-1)g={_elements:[],_next:void 0};if(f._elements.push(u),g!==f)this._back=g,f._next=g;++this._size}shift(){let u=this._front,f=u,g=this._cursor,E=g+1,I=u._elements,B=I[g];if(E===v)f=u._next,E=0;if(--this._size,this._cursor=E,u!==f)this._front=f;return I[g]=void 0,B}forEach(u){let f=this._cursor,g=this._front,E=g._elements;while(f!==E.length||g._next!==void 0){if(f===E.length){if(g=g._next,E=g._elements,f=0,E.length===0)break}u(E[f]),++f}}peek(){let u=this._front,f=this._cursor;return u._elements[f]}}let k=Symbol("[[AbortSteps]]"),O=Symbol("[[ErrorSteps]]"),N=Symbol("[[CancelSteps]]"),j=Symbol("[[PullSteps]]"),R=Symbol("[[ReleaseSteps]]");function K(u,f){if(u._ownerReadableStream=f,f._reader=u,f._state==="readable")U(u);else if(f._state==="closed")me(u);else ee(u,f._storedError)}function Z(u,f){let g=u._ownerReadableStream;return oo(g,f)}function re(u){let f=u._ownerReadableStream;if(f._state==="readable")z(u,TypeError("Reader was released and can no longer be used to monitor the stream's closedness"));else F(u,TypeError("Reader was released and can no longer be used to monitor the stream's closedness"));f._readableStreamController[R](),f._reader=void 0,u._ownerReadableStream=void 0}function pe(u){return TypeError("Cannot "+u+" a stream using a released reader")}function U(u){u._closedPromise=c((f,g)=>{u._closedPromise_resolve=f,u._closedPromise_reject=g})}function ee(u,f){U(u),z(u,f)}function me(u){U(u),Y(u)}function z(u,f){if(u._closedPromise_reject===void 0)return;_(u._closedPromise),u._closedPromise_reject(f),u._closedPromise_resolve=void 0,u._closedPromise_reject=void 0}function F(u,f){ee(u,f)}function Y(u){if(u._closedPromise_resolve===void 0)return;u._closedPromise_resolve(void 0),u._closedPromise_resolve=void 0,u._closedPromise_reject=void 0}let we=Number.isFinite||function(u){return typeof u==="number"&&isFinite(u)},te=Math.trunc||function(u){return u<0?Math.ceil(u):Math.floor(u)};function $e(u){return typeof u==="object"||typeof u==="function"}function Ee(u,f){if(u!==void 0&&!$e(u))throw TypeError(`${f} is not an object.`)}function Ae(u,f){if(typeof u!=="function")throw TypeError(`${f} is not a function.`)}function tt(u){return typeof u==="object"&&u!==null||typeof u==="function"}function yt(u,f){if(!tt(u))throw TypeError(`${f} is not an object.`)}function ft(u,f,g){if(u===void 0)throw TypeError(`Parameter ${f} is required in '${g}'.`)}function q(u,f,g){if(u===void 0)throw TypeError(`${f} is required in '${g}'.`)}function ne(u){return Number(u)}function ce(u){return u===0?0:u}function he(u){return ce(te(u))}function Q(u,f){let E=Number.MAX_SAFE_INTEGER,I=Number(u);if(I=ce(I),!we(I))throw TypeError(`${f} is not a finite number`);if(I=he(I),I<0||I>E)throw TypeError(`${f} is outside the accepted range of 0 to ${E}, inclusive`);if(!we(I)||I===0)return 0;return I}function Be(u,f){if(!Ts(u))throw TypeError(`${f} is not a ReadableStream.`)}function bt(u){return new Hr(u)}function xt(u,f){u._reader._readRequests.push(f)}function Qe(u,f,g){let I=u._reader._readRequests.shift();if(g)I._closeSteps();else I._chunkSteps(f)}function vt(u){return u._reader._readRequests.length}function wt(u){let f=u._reader;if(f===void 0)return!1;if(!_s(f))return!1;return!0}class Hr{constructor(u){if(ft(u,1,"ReadableStreamDefaultReader"),Be(u,"First parameter"),Es(u))throw TypeError("This stream has already been locked for exclusive reading by another reader");K(this,u),this._readRequests=new P}get closed(){if(!_s(this))return l(Lm("closed"));return this._closedPromise}cancel(u=void 0){if(!_s(this))return l(Lm("cancel"));if(this._ownerReadableStream===void 0)return l(pe("cancel"));return Z(this,u)}read(){if(!_s(this))return l(Lm("read"));if(this._ownerReadableStream===void 0)return l(pe("read from"));let u,f,g=c((I,B)=>{u=I,f=B});return $l(this,{_chunkSteps:(I)=>u({value:I,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:(I)=>f(I)}),g}releaseLock(){if(!_s(this))throw Lm("releaseLock");if(this._ownerReadableStream===void 0)return;Gq(this)}}if(Object.defineProperties(Hr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Hr.prototype.cancel,"cancel"),o(Hr.prototype.read,"read"),o(Hr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Hr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function _s(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_readRequests"))return!1;return u instanceof Hr}function $l(u,f){let g=u._ownerReadableStream;if(g._disturbed=!0,g._state==="closed")f._closeSteps();else if(g._state==="errored")f._errorSteps(g._storedError);else g._readableStreamController[j](f)}function Gq(u){re(u);let f=TypeError("Reader was released");iI(u,f)}function iI(u,f){let g=u._readRequests;u._readRequests=new P,g.forEach((E)=>{E._errorSteps(f)})}function Lm(u){return TypeError(`ReadableStreamDefaultReader.prototype.${u} can only be used on a ReadableStreamDefaultReader`)}let Vq=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class bx{constructor(u,f){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=u,this._preventCancel=f}next(){let u=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?x(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let f=()=>this._returnSteps(u);return this._ongoingPromise?x(this._ongoingPromise,f,f):f()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,f,g,E=c((B,W)=>{f=B,g=W});return $l(u,{_chunkSteps:(B)=>{this._ongoingPromise=void 0,w(()=>f({value:B,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,re(u),f({value:void 0,done:!0})},_errorSteps:(B)=>{this._ongoingPromise=void 0,this._isFinished=!0,re(u),g(B)}}),E}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let f=this._reader;if(!this._preventCancel){let g=Z(f,u);return re(f),x(g,()=>({value:u,done:!0}))}return re(f),d({value:u,done:!0})}}let sI={next(){if(!aI(this))return l(cI("next"));return this._asyncIteratorImpl.next()},return(u){if(!aI(this))return l(cI("return"));return this._asyncIteratorImpl.return(u)}};Object.setPrototypeOf(sI,Vq);function Zq(u,f){let g=bt(u),E=new bx(g,f),I=Object.create(sI);return I._asyncIteratorImpl=E,I}function aI(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_asyncIteratorImpl"))return!1;try{return u._asyncIteratorImpl instanceof bx}catch(f){return!1}}function cI(u){return TypeError(`ReadableStreamAsyncIterator.${u} can only be used on a ReadableSteamAsyncIterator`)}let uI=Number.isNaN||function(u){return u!==u};var xx,_x,wx;function Nl(u){return u.slice()}function dI(u,f,g,E,I){new Uint8Array(u).set(new Uint8Array(g,E,I),f)}let hi=(u)=>{if(typeof u.transfer==="function")hi=(f)=>f.transfer();else if(typeof structuredClone==="function")hi=(f)=>structuredClone(f,{transfer:[f]});else hi=(f)=>f;return hi(u)},ws=(u)=>{if(typeof u.detached==="boolean")ws=(f)=>f.detached;else ws=(f)=>f.byteLength===0;return ws(u)};function lI(u,f,g){if(u.slice)return u.slice(f,g);let E=g-f,I=new ArrayBuffer(E);return dI(I,0,u,f,E),I}function Dm(u,f){let g=u[f];if(g===void 0||g===null)return;if(typeof g!=="function")throw TypeError(`${String(f)} is not a function`);return g}function Wq(u){let f={[Symbol.iterator]:()=>u.iterator},g=async function*(){return yield*f}(),E=g.next;return{iterator:g,nextMethod:E,done:!1}}let Sx=(wx=(xx=Symbol.asyncIterator)!==null&&xx!==void 0?xx:(_x=Symbol.for)===null||_x===void 0?void 0:_x.call(Symbol,"Symbol.asyncIterator"))!==null&&wx!==void 0?wx:"@@asyncIterator";function pI(u,f="sync",g){if(g===void 0)if(f==="async"){if(g=Dm(u,Sx),g===void 0){let B=Dm(u,Symbol.iterator),W=pI(u,"sync",B);return Wq(W)}}else g=Dm(u,Symbol.iterator);if(g===void 0)throw TypeError("The object is not iterable");let E=A(g,u,[]);if(!r(E))throw TypeError("The iterator method must return an object");let I=E.next;return{iterator:E,nextMethod:I,done:!1}}function Kq(u){let f=A(u.nextMethod,u.iterator,[]);if(!r(f))throw TypeError("The iterator.next() method must return an object");return f}function Yq(u){return Boolean(u.done)}function Jq(u){return u.value}function Qq(u){if(typeof u!=="number")return!1;if(uI(u))return!1;if(u<0)return!1;return!0}function fI(u){let f=lI(u.buffer,u.byteOffset,u.byteOffset+u.byteLength);return new Uint8Array(f)}function vx(u){let f=u._queue.shift();if(u._queueTotalSize-=f.size,u._queueTotalSize<0)u._queueTotalSize=0;return f.value}function Tx(u,f,g){if(!Qq(g)||g===1/0)throw RangeError("Size must be a finite, non-NaN, non-negative number.");u._queue.push({value:f,size:g}),u._queueTotalSize+=g}function Xq(u){return u._queue.peek().value}function Ss(u){u._queue=new P,u._queueTotalSize=0}function mI(u){return u===DataView}function e7(u){return mI(u.constructor)}function t7(u){if(mI(u))return 1;return u.BYTES_PER_ELEMENT}class vs{constructor(){throw TypeError("Illegal constructor")}get view(){if(!Ex(this))throw Rx("view");return this._view}respond(u){if(!Ex(this))throw Rx("respond");if(ft(u,1,"respond"),u=Q(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw TypeError("This BYOB request has been invalidated");if(ws(this._view.buffer))throw TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");qm(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!Ex(this))throw Rx("respondWithNewView");if(ft(u,1,"respondWithNewView"),!ArrayBuffer.isView(u))throw TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw TypeError("This BYOB request has been invalidated");if(ws(u.buffer))throw TypeError("The given view's buffer has been detached and so cannot be used as a response");Hm(this._associatedReadableByteStreamController,u)}}if(Object.defineProperties(vs.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(vs.prototype.respond,"respond"),o(vs.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(vs.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class $o{constructor(){throw TypeError("Illegal constructor")}get byobRequest(){if(!Oa(this))throw Bl("byobRequest");return kx(this)}get desiredSize(){if(!Oa(this))throw Bl("desiredSize");return TI(this)}close(){if(!Oa(this))throw Bl("close");if(this._closeRequested)throw TypeError("The stream has already been closed; do not close it again!");let u=this._controlledReadableByteStream._state;if(u!=="readable")throw TypeError(`The stream (in ${u} state) is not in the readable state and cannot be closed`);zl(this)}enqueue(u){if(!Oa(this))throw Bl("enqueue");if(ft(u,1,"enqueue"),!ArrayBuffer.isView(u))throw TypeError("chunk must be an array buffer view");if(u.byteLength===0)throw TypeError("chunk must have non-zero byteLength");if(u.buffer.byteLength===0)throw TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw TypeError("stream is closed or draining");let f=this._controlledReadableByteStream._state;if(f!=="readable")throw TypeError(`The stream (in ${f} state) is not in the readable state and cannot be enqueued to`);jm(this,u)}error(u=void 0){if(!Oa(this))throw Bl("error");Bn(this,u)}[N](u){hI(this),Ss(this);let f=this._cancelAlgorithm(u);return Fm(this),f}[j](u){let f=this._controlledReadableByteStream;if(this._queueTotalSize>0){vI(this,u);return}let g=this._autoAllocateChunkSize;if(g!==void 0){let E;try{E=new ArrayBuffer(g)}catch(B){u._errorSteps(B);return}let I={buffer:E,bufferByteLength:g,byteOffset:0,byteLength:g,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(I)}xt(f,u),Ca(this)}[R](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new P,this._pendingPullIntos.push(u)}}}if(Object.defineProperties($o.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o($o.prototype.close,"close"),o($o.prototype.enqueue,"enqueue"),o($o.prototype.error,"error"),typeof Symbol.toStringTag==="symbol")Object.defineProperty($o.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Oa(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_controlledReadableByteStream"))return!1;return u instanceof $o}function Ex(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_associatedReadableByteStreamController"))return!1;return u instanceof vs}function Ca(u){if(!s7(u))return;if(u._pulling){u._pullAgain=!0;return}u._pulling=!0;let g=u._pullAlgorithm();m(g,()=>{if(u._pulling=!1,u._pullAgain)u._pullAgain=!1,Ca(u);return null},(E)=>(Bn(u,E),null))}function hI(u){Ax(u),u._pendingPullIntos=new P}function Px(u,f){let g=!1;if(u._state==="closed")g=!0;let E=gI(f);if(f.readerType==="default")Qe(u,E,g);else p7(u,E,g)}function gI(u){let{bytesFilled:f,elementSize:g}=u;return new u.viewConstructor(u.buffer,u.byteOffset,f/g)}function Um(u,f,g,E){u._queue.push({buffer:f,byteOffset:g,byteLength:E}),u._queueTotalSize+=E}function yI(u,f,g,E){let I;try{I=lI(f,g,g+E)}catch(B){throw Bn(u,B),B}Um(u,I,0,E)}function bI(u,f){if(f.bytesFilled>0)yI(u,f.buffer,f.byteOffset,f.bytesFilled);Yc(u)}function xI(u,f){let g=Math.min(u._queueTotalSize,f.byteLength-f.bytesFilled),E=f.bytesFilled+g,I=g,B=!1,W=E%f.elementSize,be=E-W;if(be>=f.minimumFill)I=be-f.bytesFilled,B=!0;let Oe=u._queue;while(I>0){let Ue=Oe.peek(),Ge=Math.min(I,Ue.byteLength),rt=f.byteOffset+f.bytesFilled;if(dI(f.buffer,rt,Ue.buffer,Ue.byteOffset,Ge),Ue.byteLength===Ge)Oe.shift();else Ue.byteOffset+=Ge,Ue.byteLength-=Ge;u._queueTotalSize-=Ge,_I(u,Ge,f),I-=Ge}return B}function _I(u,f,g){g.bytesFilled+=f}function wI(u){if(u._queueTotalSize===0&&u._closeRequested)Fm(u),ql(u._controlledReadableByteStream);else Ca(u)}function Ax(u){if(u._byobRequest===null)return;u._byobRequest._associatedReadableByteStreamController=void 0,u._byobRequest._view=null,u._byobRequest=null}function Ix(u){while(u._pendingPullIntos.length>0){if(u._queueTotalSize===0)return;let f=u._pendingPullIntos.peek();if(xI(u,f))Yc(u),Px(u._controlledReadableByteStream,f)}}function r7(u){let f=u._controlledReadableByteStream._reader;while(f._readRequests.length>0){if(u._queueTotalSize===0)return;let g=f._readRequests.shift();vI(u,g)}}function n7(u,f,g,E){let I=u._controlledReadableByteStream,B=f.constructor,W=t7(B),{byteOffset:be,byteLength:Oe}=f,Ue=g*W,Ge;try{Ge=hi(f.buffer)}catch(It){E._errorSteps(It);return}let rt={buffer:Ge,bufferByteLength:Ge.byteLength,byteOffset:be,byteLength:Oe,bytesFilled:0,minimumFill:Ue,elementSize:W,viewConstructor:B,readerType:"byob"};if(u._pendingPullIntos.length>0){u._pendingPullIntos.push(rt),AI(I,E);return}if(I._state==="closed"){let It=new B(rt.buffer,rt.byteOffset,0);E._closeSteps(It);return}if(u._queueTotalSize>0){if(xI(u,rt)){let It=gI(rt);wI(u),E._chunkSteps(It);return}if(u._closeRequested){let It=TypeError("Insufficient bytes to fill elements in the given buffer");Bn(u,It),E._errorSteps(It);return}}u._pendingPullIntos.push(rt),AI(I,E),Ca(u)}function o7(u,f){if(f.readerType==="none")Yc(u);let g=u._controlledReadableByteStream;if(Ox(g))while(II(g)>0){let E=Yc(u);Px(g,E)}}function i7(u,f,g){if(_I(u,f,g),g.readerType==="none"){bI(u,g),Ix(u);return}if(g.bytesFilled<g.minimumFill)return;Yc(u);let E=g.bytesFilled%g.elementSize;if(E>0){let I=g.byteOffset+g.bytesFilled;yI(u,g.buffer,I-E,E)}g.bytesFilled-=E,Px(u._controlledReadableByteStream,g),Ix(u)}function SI(u,f){let g=u._pendingPullIntos.peek();if(Ax(u),u._controlledReadableByteStream._state==="closed")o7(u,g);else i7(u,f,g);Ca(u)}function Yc(u){return u._pendingPullIntos.shift()}function s7(u){let f=u._controlledReadableByteStream;if(f._state!=="readable")return!1;if(u._closeRequested)return!1;if(!u._started)return!1;if(wt(f)&&vt(f)>0)return!0;if(Ox(f)&&II(f)>0)return!0;if(TI(u)>0)return!0;return!1}function Fm(u){u._pullAlgorithm=void 0,u._cancelAlgorithm=void 0}function zl(u){let f=u._controlledReadableByteStream;if(u._closeRequested||f._state!=="readable")return;if(u._queueTotalSize>0){u._closeRequested=!0;return}if(u._pendingPullIntos.length>0){let g=u._pendingPullIntos.peek();if(g.bytesFilled%g.elementSize!==0){let E=TypeError("Insufficient bytes to fill elements in the given buffer");throw Bn(u,E),E}}Fm(u),ql(f)}function jm(u,f){let g=u._controlledReadableByteStream;if(u._closeRequested||g._state!=="readable")return;let{buffer:E,byteOffset:I,byteLength:B}=f;if(ws(E))throw TypeError("chunk's buffer is detached and so cannot be enqueued");let W=hi(E);if(u._pendingPullIntos.length>0){let be=u._pendingPullIntos.peek();if(ws(be.buffer))throw TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");if(Ax(u),be.buffer=hi(be.buffer),be.readerType==="none")bI(u,be)}if(wt(g))if(r7(u),vt(g)===0)Um(u,W,I,B);else{if(u._pendingPullIntos.length>0)Yc(u);let be=new Uint8Array(W,I,B);Qe(g,be,!1)}else if(Ox(g))Um(u,W,I,B),Ix(u);else Um(u,W,I,B);Ca(u)}function Bn(u,f){let g=u._controlledReadableByteStream;if(g._state!=="readable")return;hI(u),Ss(u),Fm(u),QI(g,f)}function vI(u,f){let g=u._queue.shift();u._queueTotalSize-=g.byteLength,wI(u);let E=new Uint8Array(g.buffer,g.byteOffset,g.byteLength);f._chunkSteps(E)}function kx(u){if(u._byobRequest===null&&u._pendingPullIntos.length>0){let f=u._pendingPullIntos.peek(),g=new Uint8Array(f.buffer,f.byteOffset+f.bytesFilled,f.byteLength-f.bytesFilled),E=Object.create(vs.prototype);c7(E,u,g),u._byobRequest=E}return u._byobRequest}function TI(u){let f=u._controlledReadableByteStream._state;if(f==="errored")return null;if(f==="closed")return 0;return u._strategyHWM-u._queueTotalSize}function qm(u,f){let g=u._pendingPullIntos.peek();if(u._controlledReadableByteStream._state==="closed"){if(f!==0)throw TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(f===0)throw TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(g.bytesFilled+f>g.byteLength)throw RangeError("bytesWritten out of range")}g.buffer=hi(g.buffer),SI(u,f)}function Hm(u,f){let g=u._pendingPullIntos.peek();if(u._controlledReadableByteStream._state==="closed"){if(f.byteLength!==0)throw TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(f.byteLength===0)throw TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(g.byteOffset+g.bytesFilled!==f.byteOffset)throw RangeError("The region specified by view does not match byobRequest");if(g.bufferByteLength!==f.buffer.byteLength)throw RangeError("The buffer of view has different capacity than byobRequest");if(g.bytesFilled+f.byteLength>g.byteLength)throw RangeError("The region specified by view is larger than byobRequest");let I=f.byteLength;g.buffer=hi(f.buffer),SI(u,I)}function EI(u,f,g,E,I,B,W){f._controlledReadableByteStream=u,f._pullAgain=!1,f._pulling=!1,f._byobRequest=null,f._queue=f._queueTotalSize=void 0,Ss(f),f._closeRequested=!1,f._started=!1,f._strategyHWM=B,f._pullAlgorithm=E,f._cancelAlgorithm=I,f._autoAllocateChunkSize=W,f._pendingPullIntos=new P,u._readableStreamController=f;let be=g();m(d(be),()=>(f._started=!0,Ca(f),null),(Oe)=>(Bn(f,Oe),null))}function a7(u,f,g){let E=Object.create($o.prototype),I,B,W;if(f.start!==void 0)I=()=>f.start(E);else I=()=>{return};if(f.pull!==void 0)B=()=>f.pull(E);else B=()=>d(void 0);if(f.cancel!==void 0)W=(Oe)=>f.cancel(Oe);else W=()=>d(void 0);let be=f.autoAllocateChunkSize;if(be===0)throw TypeError("autoAllocateChunkSize must be greater than 0");EI(u,E,I,B,W,g,be)}function c7(u,f,g){u._associatedReadableByteStreamController=f,u._view=g}function Rx(u){return TypeError(`ReadableStreamBYOBRequest.prototype.${u} can only be used on a ReadableStreamBYOBRequest`)}function Bl(u){return TypeError(`ReadableByteStreamController.prototype.${u} can only be used on a ReadableByteStreamController`)}function u7(u,f){Ee(u,f);let g=u===null||u===void 0?void 0:u.mode;return{mode:g===void 0?void 0:d7(g,`${f} has member 'mode' that`)}}function d7(u,f){if(u=`${u}`,u!=="byob")throw TypeError(`${f} '${u}' is not a valid enumeration value for ReadableStreamReaderMode`);return u}function l7(u,f){var g;Ee(u,f);let E=(g=u===null||u===void 0?void 0:u.min)!==null&&g!==void 0?g:1;return{min:Q(E,`${f} has member 'min' that`)}}function PI(u){return new gi(u)}function AI(u,f){u._reader._readIntoRequests.push(f)}function p7(u,f,g){let I=u._reader._readIntoRequests.shift();if(g)I._closeSteps(f);else I._chunkSteps(f)}function II(u){return u._reader._readIntoRequests.length}function Ox(u){let f=u._reader;if(f===void 0)return!1;if(!Ma(f))return!1;return!0}class gi{constructor(u){if(ft(u,1,"ReadableStreamBYOBReader"),Be(u,"First parameter"),Es(u))throw TypeError("This stream has already been locked for exclusive reading by another reader");if(!Oa(u._readableStreamController))throw TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");K(this,u),this._readIntoRequests=new P}get closed(){if(!Ma(this))return l(Gm("closed"));return this._closedPromise}cancel(u=void 0){if(!Ma(this))return l(Gm("cancel"));if(this._ownerReadableStream===void 0)return l(pe("cancel"));return Z(this,u)}read(u,f={}){if(!Ma(this))return l(Gm("read"));if(!ArrayBuffer.isView(u))return l(TypeError("view must be an array buffer view"));if(u.byteLength===0)return l(TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return l(TypeError("view's buffer must have non-zero byteLength"));if(ws(u.buffer))return l(TypeError("view's buffer has been detached"));let g;try{g=l7(f,"options")}catch(Oe){return l(Oe)}let E=g.min;if(E===0)return l(TypeError("options.min must be greater than 0"));if(!e7(u)){if(E>u.length)return l(RangeError("options.min must be less than or equal to view's length"))}else if(E>u.byteLength)return l(RangeError("options.min must be less than or equal to view's byteLength"));if(this._ownerReadableStream===void 0)return l(pe("read from"));let I,B,W=c((Oe,Ue)=>{I=Oe,B=Ue});return kI(this,u,E,{_chunkSteps:(Oe)=>I({value:Oe,done:!1}),_closeSteps:(Oe)=>I({value:Oe,done:!0}),_errorSteps:(Oe)=>B(Oe)}),W}releaseLock(){if(!Ma(this))throw Gm("releaseLock");if(this._ownerReadableStream===void 0)return;f7(this)}}if(Object.defineProperties(gi.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(gi.prototype.cancel,"cancel"),o(gi.prototype.read,"read"),o(gi.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(gi.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Ma(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_readIntoRequests"))return!1;return u instanceof gi}function kI(u,f,g,E){let I=u._ownerReadableStream;if(I._disturbed=!0,I._state==="errored")E._errorSteps(I._storedError);else n7(I._readableStreamController,f,g,E)}function f7(u){re(u);let f=TypeError("Reader was released");RI(u,f)}function RI(u,f){let g=u._readIntoRequests;u._readIntoRequests=new P,g.forEach((E)=>{E._errorSteps(f)})}function Gm(u){return TypeError(`ReadableStreamBYOBReader.prototype.${u} can only be used on a ReadableStreamBYOBReader`)}function Ll(u,f){let{highWaterMark:g}=u;if(g===void 0)return f;if(uI(g)||g<0)throw RangeError("Invalid highWaterMark");return g}function Vm(u){let{size:f}=u;if(!f)return()=>1;return f}function Zm(u,f){Ee(u,f);let g=u===null||u===void 0?void 0:u.highWaterMark,E=u===null||u===void 0?void 0:u.size;return{highWaterMark:g===void 0?void 0:ne(g),size:E===void 0?void 0:m7(E,`${f} has member 'size' that`)}}function m7(u,f){return Ae(u,f),(g)=>ne(u(g))}function h7(u,f){Ee(u,f);let g=u===null||u===void 0?void 0:u.abort,E=u===null||u===void 0?void 0:u.close,I=u===null||u===void 0?void 0:u.start,B=u===null||u===void 0?void 0:u.type,W=u===null||u===void 0?void 0:u.write;return{abort:g===void 0?void 0:g7(g,u,`${f} has member 'abort' that`),close:E===void 0?void 0:y7(E,u,`${f} has member 'close' that`),start:I===void 0?void 0:b7(I,u,`${f} has member 'start' that`),write:W===void 0?void 0:x7(W,u,`${f} has member 'write' that`),type:B}}function g7(u,f,g){return Ae(u,g),(E)=>S(u,f,[E])}function y7(u,f,g){return Ae(u,g),()=>S(u,f,[])}function b7(u,f,g){return Ae(u,g),(E)=>A(u,f,[E])}function x7(u,f,g){return Ae(u,g),(E,I)=>S(u,f,[E,I])}function OI(u,f){if(!Jc(u))throw TypeError(`${f} is not a WritableStream.`)}function _7(u){if(typeof u!=="object"||u===null)return!1;try{return typeof u.aborted==="boolean"}catch(f){return!1}}let w7=typeof AbortController==="function";function S7(){if(w7)return new AbortController;return}class yi{constructor(u={},f={}){if(u===void 0)u=null;else yt(u,"First parameter");let g=Zm(f,"Second parameter"),E=h7(u,"First parameter");if(MI(this),E.type!==void 0)throw RangeError("Invalid type is specified");let B=Vm(g),W=Ll(g,1);z7(this,E,W,B)}get locked(){if(!Jc(this))throw Qm("locked");return Qc(this)}abort(u=void 0){if(!Jc(this))return l(Qm("abort"));if(Qc(this))return l(TypeError("Cannot abort a stream that already has a writer"));return Wm(this,u)}close(){if(!Jc(this))return l(Qm("close"));if(Qc(this))return l(TypeError("Cannot close a stream that already has a writer"));if(No(this))return l(TypeError("Cannot close an already-closing stream"));return $I(this)}getWriter(){if(!Jc(this))throw Qm("getWriter");return CI(this)}}if(Object.defineProperties(yi.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(yi.prototype.abort,"abort"),o(yi.prototype.close,"close"),o(yi.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(yi.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function CI(u){return new zo(u)}function v7(u,f,g,E,I=1,B=()=>1){let W=Object.create(yi.prototype);MI(W);let be=Object.create(Na.prototype);return UI(W,be,u,f,g,E,I,B),W}function MI(u){u._state="writable",u._storedError=void 0,u._writer=void 0,u._writableStreamController=void 0,u._writeRequests=new P,u._inFlightWriteRequest=void 0,u._closeRequest=void 0,u._inFlightCloseRequest=void 0,u._pendingAbortRequest=void 0,u._backpressure=!1}function Jc(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_writableStreamController"))return!1;return u instanceof yi}function Qc(u){if(u._writer===void 0)return!1;return!0}function Wm(u,f){var g;if(u._state==="closed"||u._state==="errored")return d(void 0);u._writableStreamController._abortReason=f,(g=u._writableStreamController._abortController)===null||g===void 0||g.abort(f);let E=u._state;if(E==="closed"||E==="errored")return d(void 0);if(u._pendingAbortRequest!==void 0)return u._pendingAbortRequest._promise;let I=!1;if(E==="erroring")I=!0,f=void 0;let B=c((W,be)=>{u._pendingAbortRequest={_promise:void 0,_resolve:W,_reject:be,_reason:f,_wasAlreadyErroring:I}});if(u._pendingAbortRequest._promise=B,!I)Mx(u,f);return B}function $I(u){let f=u._state;if(f==="closed"||f==="errored")return l(TypeError(`The stream (in ${f} state) is not in the writable state and cannot be closed`));let g=c((I,B)=>{let W={_resolve:I,_reject:B};u._closeRequest=W}),E=u._writer;if(E!==void 0&&u._backpressure&&f==="writable")Fx(E);return B7(u._writableStreamController),g}function T7(u){return c((g,E)=>{let I={_resolve:g,_reject:E};u._writeRequests.push(I)})}function Cx(u,f){if(u._state==="writable"){Mx(u,f);return}$x(u)}function Mx(u,f){let g=u._writableStreamController;u._state="erroring",u._storedError=f;let E=u._writer;if(E!==void 0)zI(E,f);if(!k7(u)&&g._started)$x(u)}function $x(u){u._state="errored",u._writableStreamController[O]();let f=u._storedError;if(u._writeRequests.forEach((I)=>{I._reject(f)}),u._writeRequests=new P,u._pendingAbortRequest===void 0){Km(u);return}let g=u._pendingAbortRequest;if(u._pendingAbortRequest=void 0,g._wasAlreadyErroring){g._reject(f),Km(u);return}let E=u._writableStreamController[k](g._reason);m(E,()=>(g._resolve(),Km(u),null),(I)=>(g._reject(I),Km(u),null))}function E7(u){u._inFlightWriteRequest._resolve(void 0),u._inFlightWriteRequest=void 0}function P7(u,f){u._inFlightWriteRequest._reject(f),u._inFlightWriteRequest=void 0,Cx(u,f)}function A7(u){if(u._inFlightCloseRequest._resolve(void 0),u._inFlightCloseRequest=void 0,u._state==="erroring"){if(u._storedError=void 0,u._pendingAbortRequest!==void 0)u._pendingAbortRequest._resolve(),u._pendingAbortRequest=void 0}u._state="closed";let g=u._writer;if(g!==void 0)HI(g)}function I7(u,f){if(u._inFlightCloseRequest._reject(f),u._inFlightCloseRequest=void 0,u._pendingAbortRequest!==void 0)u._pendingAbortRequest._reject(f),u._pendingAbortRequest=void 0;Cx(u,f)}function No(u){if(u._closeRequest===void 0&&u._inFlightCloseRequest===void 0)return!1;return!0}function k7(u){if(u._inFlightWriteRequest===void 0&&u._inFlightCloseRequest===void 0)return!1;return!0}function R7(u){u._inFlightCloseRequest=u._closeRequest,u._closeRequest=void 0}function O7(u){u._inFlightWriteRequest=u._writeRequests.shift()}function Km(u){if(u._closeRequest!==void 0)u._closeRequest._reject(u._storedError),u._closeRequest=void 0;let f=u._writer;if(f!==void 0)Dx(f,u._storedError)}function Nx(u,f){let g=u._writer;if(g!==void 0&&f!==u._backpressure)if(f)H7(g);else Fx(g);u._backpressure=f}class zo{constructor(u){if(ft(u,1,"WritableStreamDefaultWriter"),OI(u,"First parameter"),Qc(u))throw TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=u,u._writer=this;let f=u._state;if(f==="writable"){if(!No(u)&&u._backpressure)eh(this);else GI(this);Xm(this)}else if(f==="erroring")Ux(this,u._storedError),Xm(this);else if(f==="closed")GI(this),j7(this);else{let g=u._storedError;Ux(this,g),qI(this,g)}}get closed(){if(!$a(this))return l(za("closed"));return this._closedPromise}get desiredSize(){if(!$a(this))throw za("desiredSize");if(this._ownerWritableStream===void 0)throw Ul("desiredSize");return N7(this)}get ready(){if(!$a(this))return l(za("ready"));return this._readyPromise}abort(u=void 0){if(!$a(this))return l(za("abort"));if(this._ownerWritableStream===void 0)return l(Ul("abort"));return C7(this,u)}close(){if(!$a(this))return l(za("close"));let u=this._ownerWritableStream;if(u===void 0)return l(Ul("close"));if(No(u))return l(TypeError("Cannot close an already-closing stream"));return NI(this)}releaseLock(){if(!$a(this))throw za("releaseLock");if(this._ownerWritableStream===void 0)return;BI(this)}write(u=void 0){if(!$a(this))return l(za("write"));if(this._ownerWritableStream===void 0)return l(Ul("write to"));return LI(this,u)}}if(Object.defineProperties(zo.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(zo.prototype.abort,"abort"),o(zo.prototype.close,"close"),o(zo.prototype.releaseLock,"releaseLock"),o(zo.prototype.write,"write"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(zo.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function $a(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_ownerWritableStream"))return!1;return u instanceof zo}function C7(u,f){let g=u._ownerWritableStream;return Wm(g,f)}function NI(u){let f=u._ownerWritableStream;return $I(f)}function M7(u){let f=u._ownerWritableStream,g=f._state;if(No(f)||g==="closed")return d(void 0);if(g==="errored")return l(f._storedError);return NI(u)}function $7(u,f){if(u._closedPromiseState==="pending")Dx(u,f);else q7(u,f)}function zI(u,f){if(u._readyPromiseState==="pending")VI(u,f);else G7(u,f)}function N7(u){let f=u._ownerWritableStream,g=f._state;if(g==="errored"||g==="erroring")return null;if(g==="closed")return 0;return FI(f._writableStreamController)}function BI(u){let f=u._ownerWritableStream,g=TypeError("Writer was released and can no longer be used to monitor the stream's closedness");zI(u,g),$7(u,g),f._writer=void 0,u._ownerWritableStream=void 0}function LI(u,f){let g=u._ownerWritableStream,E=g._writableStreamController,I=L7(E,f);if(g!==u._ownerWritableStream)return l(Ul("write to"));let B=g._state;if(B==="errored")return l(g._storedError);if(No(g)||B==="closed")return l(TypeError("The stream is closing or closed and cannot be written to"));if(B==="erroring")return l(g._storedError);let W=T7(g);return D7(E,f,I),W}let DI={};class Na{constructor(){throw TypeError("Illegal constructor")}get abortReason(){if(!zx(this))throw Lx("abortReason");return this._abortReason}get signal(){if(!zx(this))throw Lx("signal");if(this._abortController===void 0)throw TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!zx(this))throw Lx("error");if(this._controlledWritableStream._state!=="writable")return;jI(this,u)}[k](u){let f=this._abortAlgorithm(u);return Ym(this),f}[O](){Ss(this)}}if(Object.defineProperties(Na.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Na.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function zx(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_controlledWritableStream"))return!1;return u instanceof Na}function UI(u,f,g,E,I,B,W,be){f._controlledWritableStream=u,u._writableStreamController=f,f._queue=void 0,f._queueTotalSize=void 0,Ss(f),f._abortReason=void 0,f._abortController=S7(),f._started=!1,f._strategySizeAlgorithm=be,f._strategyHWM=W,f._writeAlgorithm=E,f._closeAlgorithm=I,f._abortAlgorithm=B;let Oe=Bx(f);Nx(u,Oe);let Ue=g(),Ge=d(Ue);m(Ge,()=>(f._started=!0,Jm(f),null),(rt)=>(f._started=!0,Cx(u,rt),null))}function z7(u,f,g,E){let I=Object.create(Na.prototype),B,W,be,Oe;if(f.start!==void 0)B=()=>f.start(I);else B=()=>{return};if(f.write!==void 0)W=(Ue)=>f.write(Ue,I);else W=()=>d(void 0);if(f.close!==void 0)be=()=>f.close();else be=()=>d(void 0);if(f.abort!==void 0)Oe=(Ue)=>f.abort(Ue);else Oe=()=>d(void 0);UI(u,I,B,W,be,Oe,g,E)}function Ym(u){u._writeAlgorithm=void 0,u._closeAlgorithm=void 0,u._abortAlgorithm=void 0,u._strategySizeAlgorithm=void 0}function B7(u){Tx(u,DI,0),Jm(u)}function L7(u,f){try{return u._strategySizeAlgorithm(f)}catch(g){return Dl(u,g),1}}function FI(u){return u._strategyHWM-u._queueTotalSize}function D7(u,f,g){try{Tx(u,f,g)}catch(I){Dl(u,I);return}let E=u._controlledWritableStream;if(!No(E)&&E._state==="writable"){let I=Bx(u);Nx(E,I)}Jm(u)}function Jm(u){let f=u._controlledWritableStream;if(!u._started)return;if(f._inFlightWriteRequest!==void 0)return;if(f._state==="erroring"){$x(f);return}if(u._queue.length===0)return;let E=Xq(u);if(E===DI)U7(u);else F7(u,E)}function Dl(u,f){if(u._controlledWritableStream._state==="writable")jI(u,f)}function U7(u){let f=u._controlledWritableStream;R7(f),vx(u);let g=u._closeAlgorithm();Ym(u),m(g,()=>(A7(f),null),(E)=>(I7(f,E),null))}function F7(u,f){let g=u._controlledWritableStream;O7(g);let E=u._writeAlgorithm(f);m(E,()=>{E7(g);let I=g._state;if(vx(u),!No(g)&&I==="writable"){let B=Bx(u);Nx(g,B)}return Jm(u),null},(I)=>{if(g._state==="writable")Ym(u);return P7(g,I),null})}function Bx(u){return FI(u)<=0}function jI(u,f){let g=u._controlledWritableStream;Ym(u),Mx(g,f)}function Qm(u){return TypeError(`WritableStream.prototype.${u} can only be used on a WritableStream`)}function Lx(u){return TypeError(`WritableStreamDefaultController.prototype.${u} can only be used on a WritableStreamDefaultController`)}function za(u){return TypeError(`WritableStreamDefaultWriter.prototype.${u} can only be used on a WritableStreamDefaultWriter`)}function Ul(u){return TypeError("Cannot "+u+" a stream using a released writer")}function Xm(u){u._closedPromise=c((f,g)=>{u._closedPromise_resolve=f,u._closedPromise_reject=g,u._closedPromiseState="pending"})}function qI(u,f){Xm(u),Dx(u,f)}function j7(u){Xm(u),HI(u)}function Dx(u,f){if(u._closedPromise_reject===void 0)return;_(u._closedPromise),u._closedPromise_reject(f),u._closedPromise_resolve=void 0,u._closedPromise_reject=void 0,u._closedPromiseState="rejected"}function q7(u,f){qI(u,f)}function HI(u){if(u._closedPromise_resolve===void 0)return;u._closedPromise_resolve(void 0),u._closedPromise_resolve=void 0,u._closedPromise_reject=void 0,u._closedPromiseState="resolved"}function eh(u){u._readyPromise=c((f,g)=>{u._readyPromise_resolve=f,u._readyPromise_reject=g}),u._readyPromiseState="pending"}function Ux(u,f){eh(u),VI(u,f)}function GI(u){eh(u),Fx(u)}function VI(u,f){if(u._readyPromise_reject===void 0)return;_(u._readyPromise),u._readyPromise_reject(f),u._readyPromise_resolve=void 0,u._readyPromise_reject=void 0,u._readyPromiseState="rejected"}function H7(u){eh(u)}function G7(u,f){Ux(u,f)}function Fx(u){if(u._readyPromise_resolve===void 0)return;u._readyPromise_resolve(void 0),u._readyPromise_resolve=void 0,u._readyPromise_reject=void 0,u._readyPromiseState="fulfilled"}function V7(){if(typeof globalThis<"u")return globalThis;else if(typeof self<"u")return self;else if(typeof global<"u")return global;return}let jx=V7();function Z7(u){if(!(typeof u==="function"||typeof u==="object"))return!1;if(u.name!=="DOMException")return!1;try{return new u,!0}catch(f){return!1}}function W7(){let u=jx===null||jx===void 0?void 0:jx.DOMException;return Z7(u)?u:void 0}function K7(){let u=function(g,E){if(this.message=g||"",this.name=E||"Error",Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)};return o(u,"DOMException"),u.prototype=Object.create(Error.prototype),Object.defineProperty(u.prototype,"constructor",{value:u,writable:!0,configurable:!0}),u}let Y7=W7()||K7();function ZI(u,f,g,E,I,B){let W=bt(u),be=CI(f);u._disturbed=!0;let Oe=!1,Ue=d(void 0);return c((Ge,rt)=>{let It;if(B!==void 0){if(It=()=>{let Ne=B.reason!==void 0?B.reason:new Y7("Aborted","AbortError"),ot=[];if(!E)ot.push(()=>{if(f._state==="writable")return Wm(f,Ne);return d(void 0)});if(!I)ot.push(()=>{if(u._state==="readable")return oo(u,Ne);return d(void 0)});cn(()=>Promise.all(ot.map((Ct)=>Ct())),!0,Ne)},B.aborted){It();return}B.addEventListener("abort",It)}function xi(){return c((Ne,ot)=>{function Ct(vn){if(vn)Ne();else p(ru(),Ct,ot)}Ct(!1)})}function ru(){if(Oe)return d(!0);return p(be._readyPromise,()=>c((Ne,ot)=>{$l(W,{_chunkSteps:(Ct)=>{Ue=p(LI(be,Ct),void 0,t),Ne(!1)},_closeSteps:()=>Ne(!0),_errorSteps:ot})}))}if(_i(u,W._closedPromise,(Ne)=>{if(!E)cn(()=>Wm(f,Ne),!0,Ne);else Ln(!0,Ne);return null}),_i(f,be._closedPromise,(Ne)=>{if(!I)cn(()=>oo(u,Ne),!0,Ne);else Ln(!0,Ne);return null}),Gr(u,W._closedPromise,()=>{if(!g)cn(()=>M7(be));else Ln();return null}),No(f)||f._state==="closed"){let Ne=TypeError("the destination writable stream closed before all data could be piped to it");if(!I)cn(()=>oo(u,Ne),!0,Ne);else Ln(!0,Ne)}_(xi());function Ps(){let Ne=Ue;return p(Ue,()=>Ne!==Ue?Ps():void 0)}function _i(Ne,ot,Ct){if(Ne._state==="errored")Ct(Ne._storedError);else y(ot,Ct)}function Gr(Ne,ot,Ct){if(Ne._state==="closed")Ct();else h(ot,Ct)}function cn(Ne,ot,Ct){if(Oe)return;if(Oe=!0,f._state==="writable"&&!No(f))h(Ps(),vn);else vn();function vn(){return m(Ne(),()=>wi(ot,Ct),(nu)=>wi(!0,nu)),null}}function Ln(Ne,ot){if(Oe)return;if(Oe=!0,f._state==="writable"&&!No(f))h(Ps(),()=>wi(Ne,ot));else wi(Ne,ot)}function wi(Ne,ot){if(BI(be),re(W),B!==void 0)B.removeEventListener("abort",It);if(Ne)rt(ot);else Ge(void 0);return null}})}class Bo{constructor(){throw TypeError("Illegal constructor")}get desiredSize(){if(!th(this))throw nh("desiredSize");return qx(this)}close(){if(!th(this))throw nh("close");if(!eu(this))throw TypeError("The stream is not in a state that permits close");Ba(this)}enqueue(u=void 0){if(!th(this))throw nh("enqueue");if(!eu(this))throw TypeError("The stream is not in a state that permits enqueue");return Xc(this,u)}error(u=void 0){if(!th(this))throw nh("error");no(this,u)}[N](u){Ss(this);let f=this._cancelAlgorithm(u);return rh(this),f}[j](u){let f=this._controlledReadableStream;if(this._queue.length>0){let g=vx(this);if(this._closeRequested&&this._queue.length===0)rh(this),ql(f);else Fl(this);u._chunkSteps(g)}else xt(f,u),Fl(this)}[R](){}}if(Object.defineProperties(Bo.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Bo.prototype.close,"close"),o(Bo.prototype.enqueue,"enqueue"),o(Bo.prototype.error,"error"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Bo.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function th(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_controlledReadableStream"))return!1;return u instanceof Bo}function Fl(u){if(!WI(u))return;if(u._pulling){u._pullAgain=!0;return}u._pulling=!0;let g=u._pullAlgorithm();m(g,()=>{if(u._pulling=!1,u._pullAgain)u._pullAgain=!1,Fl(u);return null},(E)=>(no(u,E),null))}function WI(u){let f=u._controlledReadableStream;if(!eu(u))return!1;if(!u._started)return!1;if(Es(f)&&vt(f)>0)return!0;if(qx(u)>0)return!0;return!1}function rh(u){u._pullAlgorithm=void 0,u._cancelAlgorithm=void 0,u._strategySizeAlgorithm=void 0}function Ba(u){if(!eu(u))return;let f=u._controlledReadableStream;if(u._closeRequested=!0,u._queue.length===0)rh(u),ql(f)}function Xc(u,f){if(!eu(u))return;let g=u._controlledReadableStream;if(Es(g)&&vt(g)>0)Qe(g,f,!1);else{let E;try{E=u._strategySizeAlgorithm(f)}catch(I){throw no(u,I),I}try{Tx(u,f,E)}catch(I){throw no(u,I),I}}Fl(u)}function no(u,f){let g=u._controlledReadableStream;if(g._state!=="readable")return;Ss(u),rh(u),QI(g,f)}function qx(u){let f=u._controlledReadableStream._state;if(f==="errored")return null;if(f==="closed")return 0;return u._strategyHWM-u._queueTotalSize}function J7(u){if(WI(u))return!1;return!0}function eu(u){let f=u._controlledReadableStream._state;if(!u._closeRequested&&f==="readable")return!0;return!1}function KI(u,f,g,E,I,B,W){f._controlledReadableStream=u,f._queue=void 0,f._queueTotalSize=void 0,Ss(f),f._started=!1,f._closeRequested=!1,f._pullAgain=!1,f._pulling=!1,f._strategySizeAlgorithm=W,f._strategyHWM=B,f._pullAlgorithm=E,f._cancelAlgorithm=I,u._readableStreamController=f;let be=g();m(d(be),()=>(f._started=!0,Fl(f),null),(Oe)=>(no(f,Oe),null))}function Q7(u,f,g,E){let I=Object.create(Bo.prototype),B,W,be;if(f.start!==void 0)B=()=>f.start(I);else B=()=>{return};if(f.pull!==void 0)W=()=>f.pull(I);else W=()=>d(void 0);if(f.cancel!==void 0)be=(Oe)=>f.cancel(Oe);else be=()=>d(void 0);KI(u,I,B,W,be,g,E)}function nh(u){return TypeError(`ReadableStreamDefaultController.prototype.${u} can only be used on a ReadableStreamDefaultController`)}function X7(u,f){if(Oa(u._readableStreamController))return tH(u);return eH(u)}function eH(u,f){let g=bt(u),E=!1,I=!1,B=!1,W=!1,be,Oe,Ue,Ge,rt,It=c((Gr)=>{rt=Gr});function xi(){if(E)return I=!0,d(void 0);return E=!0,$l(g,{_chunkSteps:(cn)=>{w(()=>{I=!1;let Ln=cn,wi=cn;if(!B)Xc(Ue._readableStreamController,Ln);if(!W)Xc(Ge._readableStreamController,wi);if(E=!1,I)xi()})},_closeSteps:()=>{if(E=!1,!B)Ba(Ue._readableStreamController);if(!W)Ba(Ge._readableStreamController);if(!B||!W)rt(void 0)},_errorSteps:()=>{E=!1}}),d(void 0)}function ru(Gr){if(B=!0,be=Gr,W){let cn=Nl([be,Oe]),Ln=oo(u,cn);rt(Ln)}return It}function Ps(Gr){if(W=!0,Oe=Gr,B){let cn=Nl([be,Oe]),Ln=oo(u,cn);rt(Ln)}return It}function _i(){}return Ue=jl(_i,xi,ru),Ge=jl(_i,xi,Ps),y(g._closedPromise,(Gr)=>{if(no(Ue._readableStreamController,Gr),no(Ge._readableStreamController,Gr),!B||!W)rt(void 0);return null}),[Ue,Ge]}function tH(u){let f=bt(u),g=!1,E=!1,I=!1,B=!1,W=!1,be,Oe,Ue,Ge,rt,It=c((Ne)=>{rt=Ne});function xi(Ne){y(Ne._closedPromise,(ot)=>{if(Ne!==f)return null;if(Bn(Ue._readableStreamController,ot),Bn(Ge._readableStreamController,ot),!B||!W)rt(void 0);return null})}function ru(){if(Ma(f))re(f),f=bt(u),xi(f);$l(f,{_chunkSteps:(ot)=>{w(()=>{E=!1,I=!1;let Ct=ot,vn=ot;if(!B&&!W)try{vn=fI(ot)}catch(nu){Bn(Ue._readableStreamController,nu),Bn(Ge._readableStreamController,nu),rt(oo(u,nu));return}if(!B)jm(Ue._readableStreamController,Ct);if(!W)jm(Ge._readableStreamController,vn);if(g=!1,E)_i();else if(I)Gr()})},_closeSteps:()=>{if(g=!1,!B)zl(Ue._readableStreamController);if(!W)zl(Ge._readableStreamController);if(Ue._readableStreamController._pendingPullIntos.length>0)qm(Ue._readableStreamController,0);if(Ge._readableStreamController._pendingPullIntos.length>0)qm(Ge._readableStreamController,0);if(!B||!W)rt(void 0)},_errorSteps:()=>{g=!1}})}function Ps(Ne,ot){if(_s(f))re(f),f=PI(u),xi(f);let Ct=ot?Ge:Ue,vn=ot?Ue:Ge;kI(f,Ne,1,{_chunkSteps:(ou)=>{w(()=>{E=!1,I=!1;let iu=ot?W:B;if(!(ot?B:W)){let lk;try{lk=fI(ou)}catch(Wx){Bn(Ct._readableStreamController,Wx),Bn(vn._readableStreamController,Wx),rt(oo(u,Wx));return}if(!iu)Hm(Ct._readableStreamController,ou);jm(vn._readableStreamController,lk)}else if(!iu)Hm(Ct._readableStreamController,ou);if(g=!1,E)_i();else if(I)Gr()})},_closeSteps:(ou)=>{g=!1;let iu=ot?W:B,ch=ot?B:W;if(!iu)zl(Ct._readableStreamController);if(!ch)zl(vn._readableStreamController);if(ou!==void 0){if(!iu)Hm(Ct._readableStreamController,ou);if(!ch&&vn._readableStreamController._pendingPullIntos.length>0)qm(vn._readableStreamController,0)}if(!iu||!ch)rt(void 0)},_errorSteps:()=>{g=!1}})}function _i(){if(g)return E=!0,d(void 0);g=!0;let Ne=kx(Ue._readableStreamController);if(Ne===null)ru();else Ps(Ne._view,!1);return d(void 0)}function Gr(){if(g)return I=!0,d(void 0);g=!0;let Ne=kx(Ge._readableStreamController);if(Ne===null)ru();else Ps(Ne._view,!0);return d(void 0)}function cn(Ne){if(B=!0,be=Ne,W){let ot=Nl([be,Oe]),Ct=oo(u,ot);rt(Ct)}return It}function Ln(Ne){if(W=!0,Oe=Ne,B){let ot=Nl([be,Oe]),Ct=oo(u,ot);rt(Ct)}return It}function wi(){return}return Ue=JI(wi,_i,cn),Ge=JI(wi,Gr,Ln),xi(f),[Ue,Ge]}function rH(u){return r(u)&&typeof u.getReader<"u"}function nH(u){if(rH(u))return iH(u.getReader());return oH(u)}function oH(u){let f,g=pI(u,"async"),E=t;function I(){let W;try{W=Kq(g)}catch(Oe){return l(Oe)}let be=d(W);return x(be,(Oe)=>{if(!r(Oe))throw TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Yq(Oe))Ba(f._readableStreamController);else{let Ge=Jq(Oe);Xc(f._readableStreamController,Ge)}})}function B(W){let be=g.iterator,Oe;try{Oe=Dm(be,"return")}catch(rt){return l(rt)}if(Oe===void 0)return d(void 0);let Ue;try{Ue=A(Oe,be,[W])}catch(rt){return l(rt)}let Ge=d(Ue);return x(Ge,(rt)=>{if(!r(rt))throw TypeError("The promise returned by the iterator.return() method must fulfill with an object");return})}return f=jl(E,I,B,0),f}function iH(u){let f,g=t;function E(){let B;try{B=u.read()}catch(W){return l(W)}return x(B,(W)=>{if(!r(W))throw TypeError("The promise returned by the reader.read() method must fulfill with an object");if(W.done)Ba(f._readableStreamController);else{let be=W.value;Xc(f._readableStreamController,be)}})}function I(B){try{return d(u.cancel(B))}catch(W){return l(W)}}return f=jl(g,E,I,0),f}function sH(u,f){Ee(u,f);let g=u,E=g===null||g===void 0?void 0:g.autoAllocateChunkSize,I=g===null||g===void 0?void 0:g.cancel,B=g===null||g===void 0?void 0:g.pull,W=g===null||g===void 0?void 0:g.start,be=g===null||g===void 0?void 0:g.type;return{autoAllocateChunkSize:E===void 0?void 0:Q(E,`${f} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:aH(I,g,`${f} has member 'cancel' that`),pull:B===void 0?void 0:cH(B,g,`${f} has member 'pull' that`),start:W===void 0?void 0:uH(W,g,`${f} has member 'start' that`),type:be===void 0?void 0:dH(be,`${f} has member 'type' that`)}}function aH(u,f,g){return Ae(u,g),(E)=>S(u,f,[E])}function cH(u,f,g){return Ae(u,g),(E)=>S(u,f,[E])}function uH(u,f,g){return Ae(u,g),(E)=>A(u,f,[E])}function dH(u,f){if(u=`${u}`,u!=="bytes")throw TypeError(`${f} '${u}' is not a valid enumeration value for ReadableStreamType`);return u}function lH(u,f){Ee(u,f);let g=u===null||u===void 0?void 0:u.preventCancel;return{preventCancel:Boolean(g)}}function YI(u,f){Ee(u,f);let g=u===null||u===void 0?void 0:u.preventAbort,E=u===null||u===void 0?void 0:u.preventCancel,I=u===null||u===void 0?void 0:u.preventClose,B=u===null||u===void 0?void 0:u.signal;if(B!==void 0)pH(B,`${f} has member 'signal' that`);return{preventAbort:Boolean(g),preventCancel:Boolean(E),preventClose:Boolean(I),signal:B}}function pH(u,f){if(!_7(u))throw TypeError(`${f} is not an AbortSignal.`)}function fH(u,f){Ee(u,f);let g=u===null||u===void 0?void 0:u.readable;q(g,"readable","ReadableWritablePair"),Be(g,`${f} has member 'readable' that`);let E=u===null||u===void 0?void 0:u.writable;return q(E,"writable","ReadableWritablePair"),OI(E,`${f} has member 'writable' that`),{readable:g,writable:E}}class Pr{constructor(u={},f={}){if(u===void 0)u=null;else yt(u,"First parameter");let g=Zm(f,"Second parameter"),E=sH(u,"First parameter");if(Hx(this),E.type==="bytes"){if(g.size!==void 0)throw RangeError("The strategy for a byte stream cannot have a size function");let I=Ll(g,0);a7(this,E,I)}else{let I=Vm(g),B=Ll(g,1);Q7(this,E,B,I)}}get locked(){if(!Ts(this))throw La("locked");return Es(this)}cancel(u=void 0){if(!Ts(this))return l(La("cancel"));if(Es(this))return l(TypeError("Cannot cancel a stream that already has a reader"));return oo(this,u)}getReader(u=void 0){if(!Ts(this))throw La("getReader");if(u7(u,"First parameter").mode===void 0)return bt(this);return PI(this)}pipeThrough(u,f={}){if(!Ts(this))throw La("pipeThrough");ft(u,1,"pipeThrough");let g=fH(u,"First parameter"),E=YI(f,"Second parameter");if(Es(this))throw TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Qc(g.writable))throw TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let I=ZI(this,g.writable,E.preventClose,E.preventAbort,E.preventCancel,E.signal);return _(I),g.readable}pipeTo(u,f={}){if(!Ts(this))return l(La("pipeTo"));if(u===void 0)return l("Parameter 1 is required in 'pipeTo'.");if(!Jc(u))return l(TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let g;try{g=YI(f,"Second parameter")}catch(E){return l(E)}if(Es(this))return l(TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(Qc(u))return l(TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));return ZI(this,u,g.preventClose,g.preventAbort,g.preventCancel,g.signal)}tee(){if(!Ts(this))throw La("tee");let u=X7(this);return Nl(u)}values(u=void 0){if(!Ts(this))throw La("values");let f=lH(u,"First parameter");return Zq(this,f.preventCancel)}[Sx](u){return this.values(u)}static from(u){return nH(u)}}if(Object.defineProperties(Pr,{from:{enumerable:!0}}),Object.defineProperties(Pr.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Pr.from,"from"),o(Pr.prototype.cancel,"cancel"),o(Pr.prototype.getReader,"getReader"),o(Pr.prototype.pipeThrough,"pipeThrough"),o(Pr.prototype.pipeTo,"pipeTo"),o(Pr.prototype.tee,"tee"),o(Pr.prototype.values,"values"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Pr.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0});Object.defineProperty(Pr.prototype,Sx,{value:Pr.prototype.values,writable:!0,configurable:!0});function jl(u,f,g,E=1,I=()=>1){let B=Object.create(Pr.prototype);Hx(B);let W=Object.create(Bo.prototype);return KI(B,W,u,f,g,E,I),B}function JI(u,f,g){let E=Object.create(Pr.prototype);Hx(E);let I=Object.create($o.prototype);return EI(E,I,u,f,g,0,void 0),E}function Hx(u){u._state="readable",u._reader=void 0,u._storedError=void 0,u._disturbed=!1}function Ts(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_readableStreamController"))return!1;return u instanceof Pr}function Es(u){if(u._reader===void 0)return!1;return!0}function oo(u,f){if(u._disturbed=!0,u._state==="closed")return d(void 0);if(u._state==="errored")return l(u._storedError);ql(u);let g=u._reader;if(g!==void 0&&Ma(g)){let I=g._readIntoRequests;g._readIntoRequests=new P,I.forEach((B)=>{B._closeSteps(void 0)})}let E=u._readableStreamController[N](f);return x(E,t)}function ql(u){u._state="closed";let f=u._reader;if(f===void 0)return;if(Y(f),_s(f)){let g=f._readRequests;f._readRequests=new P,g.forEach((E)=>{E._closeSteps()})}}function QI(u,f){u._state="errored",u._storedError=f;let g=u._reader;if(g===void 0)return;if(z(g,f),_s(g))iI(g,f);else RI(g,f)}function La(u){return TypeError(`ReadableStream.prototype.${u} can only be used on a ReadableStream`)}function XI(u,f){Ee(u,f);let g=u===null||u===void 0?void 0:u.highWaterMark;return q(g,"highWaterMark","QueuingStrategyInit"),{highWaterMark:ne(g)}}let ek=(u)=>u.byteLength;o(ek,"size");class Hl{constructor(u){ft(u,1,"ByteLengthQueuingStrategy"),u=XI(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!rk(this))throw tk("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!rk(this))throw tk("size");return ek}}if(Object.defineProperties(Hl.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Hl.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function tk(u){return TypeError(`ByteLengthQueuingStrategy.prototype.${u} can only be used on a ByteLengthQueuingStrategy`)}function rk(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_byteLengthQueuingStrategyHighWaterMark"))return!1;return u instanceof Hl}let nk=()=>1;o(nk,"size");class Gl{constructor(u){ft(u,1,"CountQueuingStrategy"),u=XI(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!ik(this))throw ok("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ik(this))throw ok("size");return nk}}if(Object.defineProperties(Gl.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Gl.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function ok(u){return TypeError(`CountQueuingStrategy.prototype.${u} can only be used on a CountQueuingStrategy`)}function ik(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_countQueuingStrategyHighWaterMark"))return!1;return u instanceof Gl}function mH(u,f){Ee(u,f);let g=u===null||u===void 0?void 0:u.cancel,E=u===null||u===void 0?void 0:u.flush,I=u===null||u===void 0?void 0:u.readableType,B=u===null||u===void 0?void 0:u.start,W=u===null||u===void 0?void 0:u.transform,be=u===null||u===void 0?void 0:u.writableType;return{cancel:g===void 0?void 0:bH(g,u,`${f} has member 'cancel' that`),flush:E===void 0?void 0:hH(E,u,`${f} has member 'flush' that`),readableType:I,start:B===void 0?void 0:gH(B,u,`${f} has member 'start' that`),transform:W===void 0?void 0:yH(W,u,`${f} has member 'transform' that`),writableType:be}}function hH(u,f,g){return Ae(u,g),(E)=>S(u,f,[E])}function gH(u,f,g){return Ae(u,g),(E)=>A(u,f,[E])}function yH(u,f,g){return Ae(u,g),(E,I)=>S(u,f,[E,I])}function bH(u,f,g){return Ae(u,g),(E)=>S(u,f,[E])}class Vl{constructor(u={},f={},g={}){if(u===void 0)u=null;let E=Zm(f,"Second parameter"),I=Zm(g,"Third parameter"),B=mH(u,"First parameter");if(B.readableType!==void 0)throw RangeError("Invalid readableType specified");if(B.writableType!==void 0)throw RangeError("Invalid writableType specified");let W=Ll(I,0),be=Vm(I),Oe=Ll(E,1),Ue=Vm(E),Ge,rt=c((It)=>{Ge=It});if(xH(this,rt,Oe,Ue,W,be),wH(this,B),B.start!==void 0)Ge(B.start(this._transformStreamController));else Ge(void 0)}get readable(){if(!sk(this))throw dk("readable");return this._readable}get writable(){if(!sk(this))throw dk("writable");return this._writable}}if(Object.defineProperties(Vl.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Vl.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function xH(u,f,g,E,I,B){function W(){return f}function be(It){return TH(u,It)}function Oe(It){return EH(u,It)}function Ue(){return PH(u)}u._writable=v7(W,be,Ue,Oe,g,E);function Ge(){return AH(u)}function rt(It){return IH(u,It)}u._readable=jl(W,Ge,rt,I,B),u._backpressure=void 0,u._backpressureChangePromise=void 0,u._backpressureChangePromise_resolve=void 0,oh(u,!0),u._transformStreamController=void 0}function sk(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_transformStreamController"))return!1;return u instanceof Vl}function ak(u,f){no(u._readable._readableStreamController,f),Gx(u,f)}function Gx(u,f){sh(u._transformStreamController),Dl(u._writable._writableStreamController,f),Vx(u)}function Vx(u){if(u._backpressure)oh(u,!1)}function oh(u,f){if(u._backpressureChangePromise!==void 0)u._backpressureChangePromise_resolve();u._backpressureChangePromise=c((g)=>{u._backpressureChangePromise_resolve=g}),u._backpressure=f}class bi{constructor(){throw TypeError("Illegal constructor")}get desiredSize(){if(!ih(this))throw ah("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return qx(u)}enqueue(u=void 0){if(!ih(this))throw ah("enqueue");ck(this,u)}error(u=void 0){if(!ih(this))throw ah("error");SH(this,u)}terminate(){if(!ih(this))throw ah("terminate");vH(this)}}if(Object.defineProperties(bi.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(bi.prototype.enqueue,"enqueue"),o(bi.prototype.error,"error"),o(bi.prototype.terminate,"terminate"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(bi.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ih(u){if(!r(u))return!1;if(!Object.prototype.hasOwnProperty.call(u,"_controlledTransformStream"))return!1;return u instanceof bi}function _H(u,f,g,E,I){f._controlledTransformStream=u,u._transformStreamController=f,f._transformAlgorithm=g,f._flushAlgorithm=E,f._cancelAlgorithm=I,f._finishPromise=void 0,f._finishPromise_resolve=void 0,f._finishPromise_reject=void 0}function wH(u,f){let g=Object.create(bi.prototype),E,I,B;if(f.transform!==void 0)E=(W)=>f.transform(W,g);else E=(W)=>{try{return ck(g,W),d(void 0)}catch(be){return l(be)}};if(f.flush!==void 0)I=()=>f.flush(g);else I=()=>d(void 0);if(f.cancel!==void 0)B=(W)=>f.cancel(W);else B=()=>d(void 0);_H(u,g,E,I,B)}function sh(u){u._transformAlgorithm=void 0,u._flushAlgorithm=void 0,u._cancelAlgorithm=void 0}function ck(u,f){let g=u._controlledTransformStream,E=g._readable._readableStreamController;if(!eu(E))throw TypeError("Readable side is not in a state that permits enqueue");try{Xc(E,f)}catch(B){throw Gx(g,B),g._readable._storedError}if(J7(E)!==g._backpressure)oh(g,!0)}function SH(u,f){ak(u._controlledTransformStream,f)}function uk(u,f){let g=u._transformAlgorithm(f);return x(g,void 0,(E)=>{throw ak(u._controlledTransformStream,E),E})}function vH(u){let f=u._controlledTransformStream,g=f._readable._readableStreamController;Ba(g);let E=TypeError("TransformStream terminated");Gx(f,E)}function TH(u,f){let g=u._transformStreamController;if(u._backpressure){let E=u._backpressureChangePromise;return x(E,()=>{let I=u._writable;if(I._state==="erroring")throw I._storedError;return uk(g,f)})}return uk(g,f)}function EH(u,f){let g=u._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let E=u._readable;g._finishPromise=c((B,W)=>{g._finishPromise_resolve=B,g._finishPromise_reject=W});let I=g._cancelAlgorithm(f);return sh(g),m(I,()=>{if(E._state==="errored")tu(g,E._storedError);else no(E._readableStreamController,f),Zx(g);return null},(B)=>(no(E._readableStreamController,B),tu(g,B),null)),g._finishPromise}function PH(u){let f=u._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let g=u._readable;f._finishPromise=c((I,B)=>{f._finishPromise_resolve=I,f._finishPromise_reject=B});let E=f._flushAlgorithm();return sh(f),m(E,()=>{if(g._state==="errored")tu(f,g._storedError);else Ba(g._readableStreamController),Zx(f);return null},(I)=>(no(g._readableStreamController,I),tu(f,I),null)),f._finishPromise}function AH(u){return oh(u,!1),u._backpressureChangePromise}function IH(u,f){let g=u._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let E=u._writable;g._finishPromise=c((B,W)=>{g._finishPromise_resolve=B,g._finishPromise_reject=W});let I=g._cancelAlgorithm(f);return sh(g),m(I,()=>{if(E._state==="errored")tu(g,E._storedError);else Dl(E._writableStreamController,f),Vx(u),Zx(g);return null},(B)=>(Dl(E._writableStreamController,B),Vx(u),tu(g,B),null)),g._finishPromise}function ah(u){return TypeError(`TransformStreamDefaultController.prototype.${u} can only be used on a TransformStreamDefaultController`)}function Zx(u){if(u._finishPromise_resolve===void 0)return;u._finishPromise_resolve(),u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function tu(u,f){if(u._finishPromise_reject===void 0)return;_(u._finishPromise),u._finishPromise_reject(f),u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function dk(u){return TypeError(`TransformStream.prototype.${u} can only be used on a TransformStream`)}e.ByteLengthQueuingStrategy=Hl,e.CountQueuingStrategy=Gl,e.ReadableByteStreamController=$o,e.ReadableStream=Pr,e.ReadableStreamBYOBReader=gi,e.ReadableStreamBYOBRequest=vs,e.ReadableStreamDefaultController=Bo,e.ReadableStreamDefaultReader=Hr,e.TransformStream=Vl,e.TransformStreamDefaultController=bi,e.WritableStream=yi,e.WritableStreamDefaultController=Na,e.WritableStreamDefaultWriter=zo})});var gk=ie(function(){if(!globalThis.ReadableStream)try{let e=Lt("node:process"),{emitWarning:t}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,Lt("node:stream/web")),e.emitWarning=t}catch(r){throw e.emitWarning=t,r}}catch(e){Object.assign(globalThis,hk())}try{let{Blob:e}=Lt("buffer");if(e&&!e.prototype.stream)e.prototype.stream=function(r){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(i){let a=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();if(n+=a.byteLength,i.enqueue(new Uint8Array(a)),n===o.size)i.close()}})}}catch(e){}});async function*Yx(e,t=!0){for(let r of e)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(t){let n=r.byteOffset,o=r.byteOffset+r.byteLength;while(n!==o){let i=Math.min(o-n,yk),s=r.buffer.slice(n,n+i);n+=s.byteLength,yield new Uint8Array(s)}}else yield r;else{let n=0,o=r;while(n!==o.size){let s=await o.slice(n,Math.min(o.size,n+yk)).arrayBuffer();n+=s.byteLength,yield new Uint8Array(s)}}}var vpe,yk=65536,bk,UH,Si;var Zl=V(()=>{vpe=Vr(gk(),1);/*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */bk=class e{#e=[];#t="";#r=0;#n="transparent";constructor(t=[],r={}){if(typeof t!=="object"||t===null)throw TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!=="function")throw TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof r!=="object"&&typeof r!=="function")throw TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");if(r===null)r={};let n=new TextEncoder;for(let i of t){let s;if(ArrayBuffer.isView(i))s=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength));else if(i instanceof ArrayBuffer)s=new Uint8Array(i.slice(0));else if(i instanceof e)s=i;else s=n.encode(`${i}`);this.#r+=ArrayBuffer.isView(s)?s.byteLength:s.size,this.#e.push(s)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let o=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let t=new TextDecoder,r="";for await(let n of Yx(this.#e,!1))r+=t.decode(n,{stream:!0});return r+=t.decode(),r}async arrayBuffer(){let t=new Uint8Array(this.size),r=0;for await(let n of Yx(this.#e,!1))t.set(n,r),r+=n.length;return t.buffer}stream(){let t=Yx(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let n=await t.next();n.done?r.close():r.enqueue(n.value)},async cancel(){await t.return()}})}slice(t=0,r=this.size,n=""){let{size:o}=this,i=t<0?Math.max(o+t,0):Math.min(t,o),s=r<0?Math.max(o+r,0):Math.min(r,o),a=Math.max(s-i,0),c=this.#e,d=[],l=0;for(let m of c){if(l>=a)break;let h=ArrayBuffer.isView(m)?m.byteLength:m.size;if(i&&h<=i)i-=h,s-=h;else{let y;if(ArrayBuffer.isView(m))y=m.subarray(i,Math.min(h,s)),l+=y.byteLength;else y=m.slice(i,Math.min(h,s)),l+=y.size;s-=h,d.push(y),i=0}}let p=new e([],{type:String(n).toLowerCase()});return p.#r=a,p.#e=d,p}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](t){return t&&typeof t==="object"&&typeof t.constructor==="function"&&(typeof t.stream==="function"||typeof t.arrayBuffer==="function")&&/^(Blob|File)$/.test(t[Symbol.toStringTag])}};Object.defineProperties(bk.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});UH=bk,Si=UH});var FH,jH,su;var Jx=V(()=>{Zl();FH=class extends Si{#e=0;#t="";constructor(t,r,n={}){if(arguments.length<2)throw TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,n);if(n===null)n={};let o=n.lastModified===void 0?Date.now():Number(n.lastModified);if(!Number.isNaN(o))this.#e=o;this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Si&&/^(File)$/.test(t[Symbol.toStringTag])}},jH=FH,su=jH});function wk(e,t=Si){var r=`${xk()}${xk()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${r}\r
|
|
3
3
|
Content-Disposition: form-data; name="`;return e.forEach((i,s)=>typeof i=="string"?n.push(o+Qx(s)+`"\r
|
|
4
4
|
\r
|
|
5
5
|
${i.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
|
|
@@ -20,7 +20,7 @@ Content-Type: ${i.type||"application/octet-stream"}\r
|
|
|
20
20
|
`:""},this._extScope=e,this._scope=new mo.Scope({parent:e}),this._nodes=[new tC]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){let o=this._scope.toName(t);if(r!==void 0&&n)this._constants[o.str]=r;return this._leafNode(new KO(e,o,r)),o}const(e,t,r){return this._def(mo.varKinds.const,e,t,r)}let(e,t,r){return this._def(mo.varKinds.let,e,t,r)}var(e,t,r){return this._def(mo.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new vS(e,t,r))}add(e,t){return this._leafNode(new YO(e,ln.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==ct.nil)this._leafNode(new eC(e));return this}object(...e){let t=["{"];for(let[r,n]of e){if(t.length>1)t.push(",");if(t.push(r),r!==n||this.opts.es5)t.push(":"),ct.addCodeArg(t,n)}return t.push("}"),new ct._Code(t)}if(e,t,r){if(this._blockNode(new $i(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new $i(e))}else(){return this._elseNode(new Jp)}endIf(){return this._endBlockNode($i,Jp)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new rC(e),t)}forRange(e,t,r,n,o=this.opts.es5?mo.varKinds.var:mo.varKinds.let){let i=this._scope.toName(e);return this._for(new nC(o,i,t,r),()=>n(i))}forOf(e,t,r,n=mo.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=t instanceof ct.Name?t:this.var("_arr",t);return this.forRange("_i",0,ct._`${i}.length`,(s)=>{this.var(o,ct._`${i}[${s}]`),r(o)})}return this._for(new wS("of",n,o,t),()=>r(o))}forIn(e,t,r,n=this.opts.es5?mo.varKinds.var:mo.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,ct._`Object.keys(${t})`,r);let o=this._scope.toName(e);return this._for(new wS("in",n,o,t),()=>r(o))}endFor(){return this._endBlockNode(Lu)}label(e){return this._leafNode(new JO(e))}break(e){return this._leafNode(new QO(e))}return(e){let t=new qg;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(qg)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let n=new oC;if(this._blockNode(n),this.code(e),t){let o=this.name("e");this._currNode=n.catch=new Hg(o),t(o)}if(r)this._currNode=n.finally=new Gg,this.code(r);return this._endBlockNode(Hg,Gg)}throw(e){return this._leafNode(new XO(e))}block(e,t){if(this._blockStarts.push(this._nodes.length),e)this.code(e).endBlock(t);return this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=ct.nil,r,n){if(this._blockNode(new jg(e,t,r)),n)this.code(n).endFunc();return this}endFunc(){return this._endBlockNode(jg)}optimize(e=1){while(e-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof $i))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}}ln.CodeGen=iC;function oc(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Vg(e,t){return t instanceof ct._CodeOrName?oc(e,t.names):e}function Du(e,t,r){if(e instanceof ct.Name)return n(e);if(!o(e))return e;return new ct._Code(e._items.reduce((i,s)=>{if(s instanceof ct.Name)s=n(s);if(s instanceof ct._Code)i.push(...s._items);else i.push(s);return i},[]));function n(i){let s=r[i.str];if(s===void 0||t[i.str]!==1)return i;return delete t[i.str],s}function o(i){return i instanceof ct._Code&&i._items.some((s)=>s instanceof ct.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function pJ(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function sC(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:ct._`!${SS(e)}`}ln.not=sC;var fJ=aC(ln.operators.AND);function mJ(...e){return e.reduce(fJ)}ln.and=mJ;var hJ=aC(ln.operators.OR);function gJ(...e){return e.reduce(hJ)}ln.or=gJ;function aC(e){return(t,r)=>t===ct.nil?r:r===ct.nil?t:ct._`${SS(t)} ${e} ${SS(r)}`}function SS(e){return e instanceof ct.Name?e:ct._`(${e})`}});var lt=ie(function(gC){Object.defineProperty(gC,"__esModule",{value:!0});gC.checkStrictMode=gC.getErrorPath=gC.Type=gC.useFunc=gC.setEvaluated=gC.evaluatedPropsToName=gC.mergeEvaluated=gC.eachItem=gC.unescapeJsonPointer=gC.escapeJsonPointer=gC.escapeFragment=gC.unescapeFragment=gC.schemaRefOrVal=gC.schemaHasRulesButRef=gC.schemaHasRules=gC.checkUnknownRules=gC.alwaysValidSchema=gC.toHash=void 0;var Rt=Ye(),_J=Yp();function wJ(e){let t={};for(let r of e)t[r]=!0;return t}gC.toHash=wJ;function SJ(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return lC(e,t),!pC(t,e.self.RULES.all)}gC.alwaysValidSchema=SJ;function lC(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema)return;if(typeof t==="boolean")return;let o=n.RULES.keywords;for(let i in t)if(!o[i])hC(e,`unknown keyword: "${i}"`)}gC.checkUnknownRules=lC;function pC(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}gC.schemaHasRules=pC;function vJ(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}gC.schemaHasRulesButRef=vJ;function TJ({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return Rt._`${r}`}return Rt._`${e}${t}${Rt.getProperty(n)}`}gC.schemaRefOrVal=TJ;function EJ(e){return fC(decodeURIComponent(e))}gC.unescapeFragment=EJ;function PJ(e){return encodeURIComponent(ES(e))}gC.escapeFragment=PJ;function ES(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}gC.escapeJsonPointer=ES;function fC(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}gC.unescapeJsonPointer=fC;function AJ(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}gC.eachItem=AJ;function uC({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof Rt.Name?(i instanceof Rt.Name?e(o,i,s):t(o,i,s),s):i instanceof Rt.Name?(t(o,s,i),i):r(i,s);return a===Rt.Name&&!(c instanceof Rt.Name)?n(o,c):c}}gC.mergeEvaluated={props:uC({mergeNames:(e,t,r)=>e.if(Rt._`${r} !== true && ${t} !== undefined`,()=>{e.if(Rt._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,Rt._`${r} || {}`).code(Rt._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(Rt._`${r} !== true`,()=>{if(t===!0)e.assign(r,!0);else e.assign(r,Rt._`${r} || {}`),PS(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:mC}),items:uC({mergeNames:(e,t,r)=>e.if(Rt._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,Rt._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(Rt._`${r} !== true`,()=>e.assign(r,t===!0?!0:Rt._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function mC(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",Rt._`{}`);if(t!==void 0)PS(e,r,t);return r}gC.evaluatedPropsToName=mC;function PS(e,t,r){Object.keys(r).forEach((n)=>e.assign(Rt._`${t}${Rt.getProperty(n)}`,!0))}gC.setEvaluated=PS;var dC={};function IJ(e,t){return e.scopeValue("func",{ref:t,code:dC[t.code]||(dC[t.code]=new _J._Code(t.code))})}gC.useFunc=IJ;var TS;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(TS||(gC.Type=TS={}));function kJ(e,t,r){if(e instanceof Rt.Name){let n=t===TS.Num;return r?n?Rt._`"[" + ${e} + "]"`:Rt._`"['" + ${e} + "']"`:n?Rt._`"/" + ${e}`:Rt._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?Rt.getProperty(e).toString():"/"+ES(e)}gC.getErrorPath=kJ;function hC(e,t,r=e.opts.strictSchema){if(!r)return;if(t=`strict mode: ${t}`,r===!0)throw Error(t);e.self.logger.warn(t)}gC.checkStrictMode=hC});var Ni=ie(function(bC){Object.defineProperty(bC,"__esModule",{value:!0});var Lr=Ye(),ZJ={data:new Lr.Name("data"),valCxt:new Lr.Name("valCxt"),instancePath:new Lr.Name("instancePath"),parentData:new Lr.Name("parentData"),parentDataProperty:new Lr.Name("parentDataProperty"),rootData:new Lr.Name("rootData"),dynamicAnchors:new Lr.Name("dynamicAnchors"),vErrors:new Lr.Name("vErrors"),errors:new Lr.Name("errors"),this:new Lr.Name("this"),self:new Lr.Name("self"),scope:new Lr.Name("scope"),json:new Lr.Name("json"),jsonPos:new Lr.Name("jsonPos"),jsonLen:new Lr.Name("jsonLen"),jsonPart:new Lr.Name("jsonPart")};bC.default=ZJ});var Qp=ie(function(SC){Object.defineProperty(SC,"__esModule",{value:!0});SC.extendErrors=SC.resetErrorsCount=SC.reportExtraError=SC.reportError=SC.keyword$DataError=SC.keywordError=void 0;var pt=Ye(),Yg=lt(),Qr=Ni();SC.keywordError={message:({keyword:e})=>pt.str`must pass "${e}" keyword validation`};SC.keyword$DataError={message:({keyword:e,schemaType:t})=>t?pt.str`"${e}" keyword must be ${t} ($data)`:pt.str`"${e}" keyword is invalid ($data)`};function KJ(e,t=SC.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=wC(e,t,r);if(n!==null&&n!==void 0?n:s||a)xC(i,c);else _C(o,pt._`[${c}]`)}SC.reportError=KJ;function YJ(e,t=SC.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=wC(e,t,r);if(xC(o,a),!(i||s))_C(n,Qr.default.vErrors)}SC.reportExtraError=YJ;function JJ(e,t){e.assign(Qr.default.errors,t),e.if(pt._`${Qr.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(pt._`${Qr.default.vErrors}.length`,t),()=>e.assign(Qr.default.vErrors,null)))}SC.resetErrorsCount=JJ;function QJ({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,Qr.default.errors,(a)=>{if(e.const(s,pt._`${Qr.default.vErrors}[${a}]`),e.if(pt._`${s}.instancePath === undefined`,()=>e.assign(pt._`${s}.instancePath`,pt.strConcat(Qr.default.instancePath,i.errorPath))),e.assign(pt._`${s}.schemaPath`,pt.str`${i.errSchemaPath}/${t}`),i.opts.verbose)e.assign(pt._`${s}.schema`,r),e.assign(pt._`${s}.data`,n)})}SC.extendErrors=QJ;function xC(e,t){let r=e.const("err",t);e.if(pt._`${Qr.default.vErrors} === null`,()=>e.assign(Qr.default.vErrors,pt._`[${r}]`),pt._`${Qr.default.vErrors}.push(${r})`),e.code(pt._`${Qr.default.errors}++`)}function _C(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;if(o.$async)r.throw(pt._`new ${e.ValidationError}(${t})`);else r.assign(pt._`${n}.errors`,t),r.return(!1)}var ic={keyword:new pt.Name("keyword"),schemaPath:new pt.Name("schemaPath"),params:new pt.Name("params"),propertyName:new pt.Name("propertyName"),message:new pt.Name("message"),schema:new pt.Name("schema"),parentSchema:new pt.Name("parentSchema")};function wC(e,t,r){let{createErrors:n}=e.it;if(n===!1)return pt._`{}`;return XJ(e,t,r)}function XJ(e,t,r={}){let{gen:n,it:o}=e,i=[eQ(o,r),tQ(e,r)];return rQ(e,t,i),n.object(...i)}function eQ({errorPath:e},{instancePath:t}){let r=t?pt.str`${e}${Yg.getErrorPath(t,Yg.Type.Str)}`:e;return[Qr.default.instancePath,pt.strConcat(Qr.default.instancePath,r)]}function tQ({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:pt.str`${t}/${e}`;if(r)o=pt.str`${o}${Yg.getErrorPath(r,Yg.Type.Str)}`;return[ic.schemaPath,o]}function rQ(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:d,topSchemaRef:l,schemaPath:p}=a;if(n.push([ic.keyword,o],[ic.params,typeof t=="function"?t(e):t||pt._`{}`]),c.messages)n.push([ic.message,typeof r=="function"?r(e):r]);if(c.verbose)n.push([ic.schema,s],[ic.parentSchema,pt._`${l}${p}`],[Qr.default.data,i]);if(d)n.push([ic.propertyName,d])}});var AC=ie(function(EC){Object.defineProperty(EC,"__esModule",{value:!0});EC.boolOrEmptySchema=EC.topBoolOrEmptySchema=void 0;var aQ=Qp(),cQ=Ye(),uQ=Ni(),dQ={message:"boolean schema is false"};function lQ(e){let{gen:t,schema:r,validateName:n}=e;if(r===!1)TC(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(uQ.default.data);else t.assign(cQ._`${n}.errors`,null),t.return(!0)}EC.topBoolOrEmptySchema=lQ;function pQ(e,t){let{gen:r,schema:n}=e;if(n===!1)r.var(t,!1),TC(e);else r.var(t,!0)}EC.boolOrEmptySchema=pQ;function TC(e,t){let{gen:r,data:n}=e;aQ.reportError({gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e},dQ,void 0,t)}});var IS=ie(function(IC){Object.defineProperty(IC,"__esModule",{value:!0});IC.getRules=IC.isJSONType=void 0;var mQ=["string","number","integer","boolean","null","object","array"],hQ=new Set(mQ);function gQ(e){return typeof e=="string"&&hQ.has(e)}IC.isJSONType=gQ;function yQ(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}IC.getRules=yQ});var kS=ie(function(CC){Object.defineProperty(CC,"__esModule",{value:!0});CC.shouldUseRule=CC.shouldUseGroup=CC.schemaHasRulesForType=void 0;function xQ({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&RC(e,n)}CC.schemaHasRulesForType=xQ;function RC(e,t){return t.rules.some((r)=>OC(e,r))}CC.shouldUseGroup=RC;function OC(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some((n)=>e[n]!==void 0))}CC.shouldUseRule=OC});var Xp=ie(function(BC){Object.defineProperty(BC,"__esModule",{value:!0});BC.reportTypeError=BC.checkDataTypes=BC.checkDataType=BC.coerceAndCheckDataType=BC.getJSONTypes=BC.getSchemaTypes=BC.DataType=void 0;var SQ=IS(),vQ=kS(),TQ=Qp(),Ke=Ye(),$C=lt(),Uu;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Uu||(BC.DataType=Uu={}));function EQ(e){let t=NC(e.type);if(t.includes("null")){if(e.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(e.nullable===!0)t.push("null")}return t}BC.getSchemaTypes=EQ;function NC(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(SQ.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}BC.getJSONTypes=NC;function PQ(e,t){let{gen:r,data:n,opts:o}=e,i=AQ(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&vQ.schemaHasRulesForType(e,t[0]));if(s){let a=OS(t,n,o.strictNumbers,Uu.Wrong);r.if(a,()=>{if(i.length)IQ(e,t,i);else CS(e)})}return s}BC.coerceAndCheckDataType=PQ;var zC=new Set(["string","number","integer","boolean","null"]);function AQ(e,t){return t?e.filter((r)=>zC.has(r)||t==="array"&&r==="array"):[]}function IQ(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",Ke._`typeof ${o}`),a=n.let("coerced",Ke._`undefined`);if(i.coerceTypes==="array")n.if(Ke._`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,Ke._`${o}[0]`).assign(s,Ke._`typeof ${o}`).if(OS(t,o,i.strictNumbers),()=>n.assign(a,o)));n.if(Ke._`${a} !== undefined`);for(let d of r)if(zC.has(d)||d==="array"&&i.coerceTypes==="array")c(d);n.else(),CS(e),n.endIf(),n.if(Ke._`${a} !== undefined`,()=>{n.assign(o,a),kQ(e,a)});function c(d){switch(d){case"string":n.elseIf(Ke._`${s} == "number" || ${s} == "boolean"`).assign(a,Ke._`"" + ${o}`).elseIf(Ke._`${o} === null`).assign(a,Ke._`""`);return;case"number":n.elseIf(Ke._`${s} == "boolean" || ${o} === null
|
|
21
21
|
|| (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,Ke._`+${o}`);return;case"integer":n.elseIf(Ke._`${s} === "boolean" || ${o} === null
|
|
22
22
|
|| (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,Ke._`+${o}`);return;case"boolean":n.elseIf(Ke._`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf(Ke._`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf(Ke._`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf(Ke._`${s} === "string" || ${s} === "number"
|
|
23
|
-
|| ${s} === "boolean" || ${o} === null`).assign(a,Ke._`[${o}]`)}}}function kQ({gen:e,parentData:t,parentDataProperty:r},n){e.if(Ke._`${t} !== undefined`,()=>e.assign(Ke._`${t}[${r}]`,n))}function RS(e,t,r,n=Uu.Correct){let o=n===Uu.Correct?Ke.operators.EQ:Ke.operators.NEQ,i;switch(e){case"null":return Ke._`${t} ${o} null`;case"array":i=Ke._`Array.isArray(${t})`;break;case"object":i=Ke._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s(Ke._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return Ke._`typeof ${t} ${o} ${e}`}return n===Uu.Correct?i:Ke.not(i);function s(a=Ke.nil){return Ke.and(Ke._`typeof ${t} == "number"`,a,r?Ke._`isFinite(${t})`:Ke.nil)}}BC.checkDataType=RS;function OS(e,t,r,n){if(e.length===1)return RS(e[0],t,r,n);let o,i=$C.toHash(e);if(i.array&&i.object){let s=Ke._`typeof ${t} != "object"`;o=i.null?s:Ke._`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=Ke.nil;if(i.number)delete i.integer;for(let s in i)o=Ke.and(o,RS(s,t,r,n));return o}BC.checkDataTypes=OS;var RQ={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?Ke._`{type: ${e}}`:Ke._`{type: ${t}}`};function CS(e){let t=OQ(e);TQ.reportError(t,RQ)}BC.reportTypeError=CS;function OQ(e){let{gen:t,data:r,schema:n}=e,o=$C.schemaRefOrVal(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var jC=ie(function(UC){Object.defineProperty(UC,"__esModule",{value:!0});UC.assignDefaults=void 0;var Fu=Ye(),LQ=lt();function DQ(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)DC(e,o,r[o].default);else if(t==="array"&&Array.isArray(n))n.forEach((o,i)=>DC(e,i,o.default))}UC.assignDefaults=DQ;function DC(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=Fu._`${i}${Fu.getProperty(t)}`;if(o){LQ.checkStrictMode(e,`default is ignored for: ${a}`);return}let c=Fu._`${a} === undefined`;if(s.useDefaults==="empty")c=Fu._`${c} || ${a} === null || ${a} === ""`;n.if(c,Fu._`${a} = ${Fu.stringify(r)}`)}});var Gn=ie(function(GC){Object.defineProperty(GC,"__esModule",{value:!0});GC.validateUnion=GC.validateArray=GC.usePattern=GC.callValidateCode=GC.schemaProperties=GC.allSchemaProperties=GC.noPropertyInData=GC.propertyInData=GC.isOwnProperty=GC.hasPropFunc=GC.reportMissingProp=GC.checkMissingProp=GC.checkReportMissingProp=void 0;var Ut=Ye(),MS=lt(),Ws=Ni(),UQ=lt();function FQ(e,t){let{gen:r,data:n,it:o}=e;r.if(NS(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:Ut._`${t}`},!0),e.error()})}GC.checkReportMissingProp=FQ;function jQ({gen:e,data:t,it:{opts:r}},n,o){return Ut.or(...n.map((i)=>Ut.and(NS(e,t,i,r.ownProperties),Ut._`${o} = ${i}`)))}GC.checkMissingProp=jQ;function qQ(e,t){e.setParams({missingProperty:t},!0),e.error()}GC.reportMissingProp=qQ;function qC(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Ut._`Object.prototype.hasOwnProperty`})}GC.hasPropFunc=qC;function $S(e,t,r){return Ut._`${qC(e)}.call(${t}, ${r})`}GC.isOwnProperty=$S;function HQ(e,t,r,n){let o=Ut._`${t}${Ut.getProperty(r)} !== undefined`;return n?Ut._`${o} && ${$S(e,t,r)}`:o}GC.propertyInData=HQ;function NS(e,t,r,n){let o=Ut._`${t}${Ut.getProperty(r)} === undefined`;return n?Ut.or(o,Ut.not($S(e,t,r))):o}GC.noPropertyInData=NS;function HC(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}GC.allSchemaProperties=HC;function GQ(e,t){return HC(t).filter((r)=>!MS.alwaysValidSchema(e,t[r]))}GC.schemaProperties=GQ;function VQ({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,d){let l=d?Ut._`${e}, ${t}, ${n}${o}`:t,p=[[Ws.default.instancePath,Ut.strConcat(Ws.default.instancePath,i)],[Ws.default.parentData,s.parentData],[Ws.default.parentDataProperty,s.parentDataProperty],[Ws.default.rootData,Ws.default.rootData]];if(s.opts.dynamicRef)p.push([Ws.default.dynamicAnchors,Ws.default.dynamicAnchors]);let m=Ut._`${l}, ${r.object(...p)}`;return c!==Ut.nil?Ut._`${a}.call(${c}, ${m})`:Ut._`${a}(${m})`}GC.callValidateCode=VQ;var ZQ=Ut._`new RegExp`;function WQ({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:Ut._`${o.code==="new RegExp"?ZQ:UQ.useFunc(e,o)}(${r}, ${n})`})}GC.usePattern=WQ;function KQ(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",Ut._`${r}.length`);t.forRange("i",0,c,(d)=>{e.subschema({keyword:n,dataProp:d,dataPropType:MS.Type.Num},i),t.if(Ut.not(i),a)})}}GC.validateArray=KQ;function YQ(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((c)=>MS.alwaysValidSchema(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,d)=>{let l=e.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);if(t.assign(s,Ut._`${s} || ${a}`),!e.mergeValidEvaluated(l,a))t.if(Ut.not(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}GC.validateUnion=YQ});var JC=ie(function(KC){Object.defineProperty(KC,"__esModule",{value:!0});KC.validateKeywordUsage=KC.validSchemaType=KC.funcKeywordCode=KC.macroKeywordCode=void 0;var Xr=Ye(),sc=Ni(),uX=Gn(),dX=Qp();function lX(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=WC(r,n,a);if(s.opts.validateSchema!==!1)s.self.validateSchema(a,!0);let d=r.name("valid");e.subschema({schema:a,schemaPath:Xr.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}KC.macroKeywordCode=lX;function pX(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;mX(c,t);let d=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,l=WC(n,o,d),p=n.let("valid");e.block$data(p,m),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function m(){if(t.errors===!1){if(x(),t.modifying)ZC(e);_(()=>e.error())}else{let w=t.async?h():y();if(t.modifying)ZC(e);_(()=>fX(e,w))}}function h(){let w=n.let("ruleErrs",null);return n.try(()=>x(Xr._`await `),(A)=>n.assign(p,!1).if(Xr._`${A} instanceof ${c.ValidationError}`,()=>n.assign(w,Xr._`${A}.errors`),()=>n.throw(A))),w}function y(){let w=Xr._`${l}.errors`;return n.assign(w,null),x(Xr.nil),w}function x(w=t.async?Xr._`await `:Xr.nil){let A=c.opts.passContext?sc.default.this:sc.default.self,S=!(("compile"in t)&&!a||t.schema===!1);n.assign(p,Xr._`${w}${uX.callValidateCode(e,l,A,S)}`,t.modifying)}function _(w){var A;n.if(Xr.not((A=t.valid)!==null&&A!==void 0?A:p),w)}}KC.funcKeywordCode=pX;function ZC(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,Xr._`${n.parentData}[${n.parentDataProperty}]`))}function fX(e,t){let{gen:r}=e;r.if(Xr._`Array.isArray(${t})`,()=>{r.assign(sc.default.vErrors,Xr._`${sc.default.vErrors} === null ? ${t} : ${sc.default.vErrors}.concat(${t})`).assign(sc.default.errors,Xr._`${sc.default.vErrors}.length`),dX.extendErrors(e)},()=>e.error())}function mX({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function WC(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:Xr.stringify(r)})}function hX(e,t,r=!1){return!t.length||t.some((n)=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}KC.validSchemaType=hX;function gX({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw Error("ajv implementation error");let s=o.dependencies;if(s===null||s===void 0?void 0:s.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema){if(!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw Error(c)}}}KC.validateKeywordUsage=gX});var tM=ie(function(XC){Object.defineProperty(XC,"__esModule",{value:!0});XC.extendSubschemaMode=XC.extendSubschemaData=XC.getSubschema=void 0;var Vo=Ye(),QC=lt();function _X(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:Vo._`${e.schemaPath}${Vo.getProperty(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Vo._`${e.schemaPath}${Vo.getProperty(t)}${Vo.getProperty(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${QC.escapeFragment(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw Error('either "keyword" or "schema" must be passed')}XC.getSubschema=_X;function wX(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:d,dataPathArr:l,opts:p}=t,m=a.let("data",Vo._`${t.data}${Vo.getProperty(r)}`,!0);c(m),e.errorPath=Vo.str`${d}${QC.getErrorPath(r,n,p.jsPropertySyntax)}`,e.parentDataProperty=Vo._`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){let d=o instanceof Vo.Name?o:a.let("data",o,!0);if(c(d),s!==void 0)e.propertyName=s}if(i)e.dataTypes=i;function c(d){e.data=d,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,d]}}XC.extendSubschemaData=wX;function SX(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){if(n!==void 0)e.compositeRule=n;if(o!==void 0)e.createErrors=o;if(i!==void 0)e.allErrors=i;e.jtdDiscriminator=t,e.jtdMetadata=r}XC.extendSubschemaMode=SX});var zS=ie(function(xxe,rM){rM.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var oM=ie(function(_xe,nM){var Ks=nM.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Jg(t,n,o,e,"",e)};Ks.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ks.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ks.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ks.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Jg(e,t,r,n,o,i,s,a,c,d){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,d);for(var l in n){var p=n[l];if(Array.isArray(p)){if(l in Ks.arrayKeywords)for(var m=0;m<p.length;m++)Jg(e,t,r,p[m],o+"/"+l+"/"+m,i,o,l,n,m)}else if(l in Ks.propsKeywords){if(p&&typeof p=="object")for(var h in p)Jg(e,t,r,p[h],o+"/"+l+"/"+EX(h),i,o,l,n,h)}else if(l in Ks.keywords||e.allKeys&&!(l in Ks.skipKeywords))Jg(e,t,r,p,o+"/"+l,i,o,l,n)}r(n,o,i,s,a,c,d)}}function EX(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ef=ie(function(cM){Object.defineProperty(cM,"__esModule",{value:!0});cM.getSchemaRefs=cM.resolveUrl=cM.normalizeId=cM._getFullPath=cM.getFullPath=cM.inlineRef=void 0;var PX=lt(),AX=zS(),IX=oM(),kX=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function RX(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!BS(e);if(!t)return!1;return iM(e)<=t}cM.inlineRef=RX;var OX=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function BS(e){for(let t in e){if(OX.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(BS))return!0;if(typeof r=="object"&&BS(r))return!0}return!1}function iM(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,kX.has(r))continue;if(typeof e[r]=="object")PX.eachItem(e[r],(n)=>t+=iM(n));if(t===1/0)return 1/0}return t}function sM(e,t="",r){if(r!==!1)t=ju(t);let n=e.parse(t);return aM(e,n)}cM.getFullPath=sM;function aM(e,t){return e.serialize(t).split("#")[0]+"#"}cM._getFullPath=aM;var CX=/#\/?$/;function ju(e){return e?e.replace(CX,""):""}cM.normalizeId=ju;function MX(e,t,r){return r=ju(r),e.resolve(t,r)}cM.resolveUrl=MX;var $X=/^[a-z_][-a-z0-9._]*$/i;function NX(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=ju(e[r]||t),i={"":o},s=sM(n,o,!1),a={},c=new Set;return IX(e,{allKeys:!0},(p,m,h,y)=>{if(y===void 0)return;let x=s+m,_=i[y];if(typeof p[r]=="string")_=w.call(this,p[r]);A.call(this,p.$anchor),A.call(this,p.$dynamicAnchor),i[m]=_;function w(S){let v=this.opts.uriResolver.resolve;if(S=ju(_?v(_,S):S),c.has(S))throw l(S);c.add(S);let P=this.refs[S];if(typeof P=="string")P=this.refs[P];if(typeof P=="object")d(p,P.schema,S);else if(S!==ju(x))if(S[0]==="#")d(p,a[S],S),a[S]=p;else this.refs[S]=x;return S}function A(S){if(typeof S=="string"){if(!$X.test(S))throw Error(`invalid anchor "${S}"`);w.call(this,`#${S}`)}}}),a;function d(p,m,h){if(m!==void 0&&!AX(p,m))throw l(h)}function l(p){return Error(`reference "${p}" resolves to more than one schema`)}}cM.getSchemaRefs=NX});var nf=ie(function(TM){Object.defineProperty(TM,"__esModule",{value:!0});TM.getData=TM.KeywordCxt=TM.validateFunctionCode=void 0;var fM=AC(),mM=Xp(),LS=kS(),Qg=Xp(),FX=jC(),tf=JC(),DS=tM(),Ae=Ye(),je=Ni(),jX=ef(),zi=lt(),rf=Qp();function qX(e){if(yM(e)){if(bM(e),gM(e)){VX(e);return}}hM(e,()=>fM.topBoolOrEmptySchema(e))}TM.validateFunctionCode=qX;function hM({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){if(o.code.es5)e.func(t,Ae._`${je.default.data}, ${je.default.valCxt}`,n.$async,()=>{e.code(Ae._`"use strict"; ${dM(r,o)}`),GX(e,o),e.code(i)});else e.func(t,Ae._`${je.default.data}, ${HX(o)}`,n.$async,()=>e.code(dM(r,o)).code(i))}function HX(e){return Ae._`{${je.default.instancePath}="", ${je.default.parentData}, ${je.default.parentDataProperty}, ${je.default.rootData}=${je.default.data}${e.dynamicRef?Ae._`, ${je.default.dynamicAnchors}={}`:Ae.nil}}={}`}function GX(e,t){e.if(je.default.valCxt,()=>{if(e.var(je.default.instancePath,Ae._`${je.default.valCxt}.${je.default.instancePath}`),e.var(je.default.parentData,Ae._`${je.default.valCxt}.${je.default.parentData}`),e.var(je.default.parentDataProperty,Ae._`${je.default.valCxt}.${je.default.parentDataProperty}`),e.var(je.default.rootData,Ae._`${je.default.valCxt}.${je.default.rootData}`),t.dynamicRef)e.var(je.default.dynamicAnchors,Ae._`${je.default.valCxt}.${je.default.dynamicAnchors}`)},()=>{if(e.var(je.default.instancePath,Ae._`""`),e.var(je.default.parentData,Ae._`undefined`),e.var(je.default.parentDataProperty,Ae._`undefined`),e.var(je.default.rootData,je.default.data),t.dynamicRef)e.var(je.default.dynamicAnchors,Ae._`{}`)})}function VX(e){let{schema:t,opts:r,gen:n}=e;hM(e,()=>{if(r.$comment&&t.$comment)_M(e);if(JX(e),n.let(je.default.vErrors,null),n.let(je.default.errors,0),r.unevaluated)ZX(e);xM(e),eee(e)});return}function ZX(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",Ae._`${r}.evaluated`),t.if(Ae._`${e.evaluated}.dynamicProps`,()=>t.assign(Ae._`${e.evaluated}.props`,Ae._`undefined`)),t.if(Ae._`${e.evaluated}.dynamicItems`,()=>t.assign(Ae._`${e.evaluated}.items`,Ae._`undefined`))}function dM(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?Ae._`/*# sourceURL=${r} */`:Ae.nil}function WX(e,t){if(yM(e)){if(bM(e),gM(e)){KX(e,t);return}}fM.boolOrEmptySchema(e,t)}function gM({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function yM(e){return typeof e.schema!="boolean"}function KX(e,t){let{schema:r,gen:n,opts:o}=e;if(o.$comment&&r.$comment)_M(e);QX(e),XX(e);let i=n.const("_errs",je.default.errors);xM(e,i),n.var(t,Ae._`${i} === ${je.default.errors}`)}function bM(e){zi.checkUnknownRules(e),YX(e)}function xM(e,t){if(e.opts.jtd)return lM(e,[],!1,t);let r=mM.getSchemaTypes(e.schema),n=mM.coerceAndCheckDataType(e,r);lM(e,r,!n,t)}function YX(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;if(t.$ref&&n.ignoreKeywordsWithRef&&zi.schemaHasRulesButRef(t,o.RULES))o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function JX(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)zi.checkStrictMode(e,"default is ignored in the schema root")}function QX(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=jX.resolveUrl(e.opts.uriResolver,e.baseId,t)}function XX(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function _M({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code(Ae._`${je.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=Ae.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(Ae._`${je.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function eee(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;if(r.$async)t.if(Ae._`${je.default.errors} === 0`,()=>t.return(je.default.data),()=>t.throw(Ae._`new ${o}(${je.default.vErrors})`));else{if(t.assign(Ae._`${n}.errors`,je.default.vErrors),i.unevaluated)tee(e);t.return(Ae._`${je.default.errors} === 0`)}}function tee({gen:e,evaluated:t,props:r,items:n}){if(r instanceof Ae.Name)e.assign(Ae._`${t}.props`,r);if(n instanceof Ae.Name)e.assign(Ae._`${t}.items`,n)}function lM(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:d}=e,{RULES:l}=d;if(i.$ref&&(c.ignoreKeywordsWithRef||!zi.schemaHasRulesButRef(i,l))){o.block(()=>SM(e,"$ref",l.all.$ref.definition));return}if(!c.jtd)ree(e,t);o.block(()=>{for(let m of l.rules)p(m);p(l.post)});function p(m){if(!LS.shouldUseGroup(i,m))return;if(m.type){if(o.if(Qg.checkDataType(m.type,s,c.strictNumbers)),pM(e,m),t.length===1&&t[0]===m.type&&r)o.else(),Qg.reportTypeError(e);o.endIf()}else pM(e,m);if(!a)o.if(Ae._`${je.default.errors} === ${n||0}`)}}function pM(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;if(o)FX.assignDefaults(e,t.type);r.block(()=>{for(let i of t.rules)if(LS.shouldUseRule(n,i))SM(e,i.keyword,i.definition,t.type)})}function ree(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(nee(e,t),!e.opts.allowUnionTypes)oee(e,t);iee(e,e.dataTypes)}function nee(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!wM(e.dataTypes,r))US(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),aee(e,t)}function oee(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))US(e,"use allowUnionTypes to allow union type keyword")}function iee(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&LS.shouldUseRule(e.schema,o)){let{type:i}=o.definition;if(i.length&&!i.some((s)=>see(t,s)))US(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function see(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function wM(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function aee(e,t){let r=[];for(let n of e.dataTypes)if(wM(t,n))r.push(n);else if(t.includes("integer")&&n==="number")r.push("integer");e.dataTypes=r}function US(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,zi.checkStrictMode(e,t,e.opts.strictTypes)}class FS{constructor(e,t,r){if(tf.validateKeywordUsage(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=zi.schemaRefOrVal(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",vM(this.$data,e));else if(this.schemaCode=this.schemaValue,!tf.validSchemaType(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",je.default.errors)}result(e,t,r){this.failResult(Ae.not(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult(Ae.not(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(Ae._`${t} !== undefined && (${Ae.or(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?rf.reportExtraError:rf.reportError)(this,this.def.error,t)}$dataError(){rf.reportError(this,this.def.$dataError||rf.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');rf.resetErrorsCount(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,r=Ae.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=Ae.nil,t=Ae.nil){if(!this.$data)return;let{gen:r,schemaCode:n,schemaType:o,def:i}=this;if(r.if(Ae.or(Ae._`${n} === undefined`,t)),e!==Ae.nil)r.assign(e,!0);if(o.length||i.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==Ae.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:n,it:o}=this;return Ae.or(i(),s());function i(){if(r.length){if(!(t instanceof Ae.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return Ae._`${Qg.checkDataTypes(a,t,o.opts.strictNumbers,Qg.DataType.Wrong)}`}return Ae.nil}function s(){if(n.validateSchema){let a=e.scopeValue("validate$data",{ref:n.validateSchema});return Ae._`!${a}(${t})`}return Ae.nil}}subschema(e,t){let r=DS.getSubschema(this.it,e);DS.extendSubschemaData(r,this.it,e),DS.extendSubschemaMode(r,e);let n={...this.it,...r,items:void 0,props:void 0};return WX(n,t),n}mergeEvaluated(e,t){let{it:r,gen:n}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=zi.mergeEvaluated.props(n,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=zi.mergeEvaluated.items(n,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:n}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return n.if(t,()=>this.mergeEvaluated(e,Ae.Name)),!0}}TM.KeywordCxt=FS;function SM(e,t,r,n){let o=new FS(e,r,t);if("code"in r)r.code(o,n);else if(o.$data&&r.validate)tf.funcKeywordCode(o,r);else if("macro"in r)tf.macroKeywordCode(o,r);else if(r.compile||r.validate)tf.funcKeywordCode(o,r)}var cee=/^\/(?:[^~]|~0|~1)*$/,uee=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function vM(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return je.default.rootData;if(e[0]==="/"){if(!cee.test(e))throw Error(`Invalid JSON-pointer: ${e}`);o=e,i=je.default.rootData}else{let d=uee.exec(e);if(!d)throw Error(`Invalid JSON-pointer: ${e}`);let l=+d[1];if(o=d[2],o==="#"){if(l>=t)throw Error(c("property/index",l));return n[t-l]}if(l>t)throw Error(c("data",l));if(i=r[t-l],!o)return i}let s=i,a=o.split("/");for(let d of a)if(d)i=Ae._`${i}${Ae.getProperty(zi.unescapeJsonPointer(d))}`,s=Ae._`${s} && ${i}`;return s;function c(d,l){return`Cannot access ${d} ${l} levels up, current level is ${t}`}}TM.getData=vM});var Xg=ie(function(AM){Object.defineProperty(AM,"__esModule",{value:!0});class PM extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}AM.default=PM});var of=ie(function(kM){Object.defineProperty(kM,"__esModule",{value:!0});var jS=ef();class IM extends Error{constructor(e,t,r,n){super(n||`can't resolve reference ${r} from id ${t}`);this.missingRef=jS.resolveUrl(e,t,r),this.missingSchema=jS.normalizeId(jS.getFullPath(e,this.missingRef))}}kM.default=IM});var t0=ie(function(CM){Object.defineProperty(CM,"__esModule",{value:!0});CM.resolveSchema=CM.getCompilingSchema=CM.resolveRef=CM.compileSchema=CM.SchemaEnv=void 0;var ho=Ye(),mee=Xg(),ac=Ni(),go=ef(),RM=lt(),hee=nf();class sf{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:go.normalizeId(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}CM.SchemaEnv=sf;function HS(e){let t=OM.call(this,e);if(t)return t;let r=go.getFullPath(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new ho.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;if(e.$async)a=s.scopeValue("Error",{ref:mee.default,code:ho._`require("ajv/dist/runtime/validation_error").default`});let c=s.scopeName("validate");e.validateName=c;let d={gen:s,allErrors:this.opts.allErrors,data:ac.default.data,parentData:ac.default.parentData,parentDataProperty:ac.default.parentDataProperty,dataNames:[ac.default.data],dataPathArr:[ho.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:ho.stringify(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:ho.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:ho._`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),hee.validateFunctionCode(d),s.optimize(this.opts.code.optimize);let p=s.toString();if(l=`${s.scopeRefs(ac.default.scope)}return ${p}`,this.opts.code.process)l=this.opts.code.process(l,e);let h=Function(`${ac.default.self}`,`${ac.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=e.schema,h.schemaEnv=e,e.$async)h.$async=!0;if(this.opts.code.source===!0)h.source={validateName:c,validateCode:p,scopeValues:s._values};if(this.opts.unevaluated){let{props:y,items:x}=d;if(h.evaluated={props:y instanceof ho.Name?void 0:y,items:x instanceof ho.Name?void 0:x,dynamicProps:y instanceof ho.Name,dynamicItems:x instanceof ho.Name},h.source)h.source.evaluated=ho.stringify(h.evaluated)}return e.validate=h,e}catch(p){if(delete e.validate,delete e.validateName,l)this.logger.error("Error compiling schema, function code:",l);throw p}finally{this._compilations.delete(e)}}CM.compileSchema=HS;function gee(e,t,r){var n;r=go.resolveUrl(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=xee.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;if(s)i=new sf({schema:s,schemaId:a,root:e,baseId:t})}if(i===void 0)return;return e.refs[r]=yee.call(this,i)}CM.resolveRef=gee;function yee(e){if(go.inlineRef(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:HS.call(this,e)}function OM(e){for(let t of this._compilations)if(bee(t,e))return t}CM.getCompilingSchema=OM;function bee(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function xee(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||e0.call(this,e,t)}function e0(e,t){let r=this.opts.uriResolver.parse(t),n=go._getFullPath(this.opts.uriResolver,r),o=go.getFullPath(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return qS.call(this,r,e);let i=go.normalizeId(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=e0.call(this,e,s);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return qS.call(this,r,a)}if(typeof(s===null||s===void 0?void 0:s.schema)!=="object")return;if(!s.validate)HS.call(this,s);if(i===go.normalizeId(t)){let{schema:a}=s,{schemaId:c}=this.opts,d=a[c];if(d)o=go.resolveUrl(this.opts.uriResolver,o,d);return new sf({schema:a,schemaId:c,root:e,baseId:o})}return qS.call(this,r,s)}CM.resolveSchema=e0;var _ee=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qS(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let c=r[RM.unescapeFragment(a)];if(c===void 0)return;r=c;let d=typeof r==="object"&&r[this.opts.schemaId];if(!_ee.has(a)&&d)t=go.resolveUrl(this.opts.uriResolver,t,d)}let i;if(typeof r!="boolean"&&r.$ref&&!RM.schemaHasRulesButRef(r,this.RULES)){let a=go.resolveUrl(this.opts.uriResolver,t,r.$ref);i=e0.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new sf({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i;return}});var $M=ie(function(Pxe,Eee){Eee.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var ZS=ie(function(Axe,UM){var Pee=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zM=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),GS=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),BM=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Aee=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function VS(e){let t="",r=0,n=0;for(n=0;n<e.length;n++){if(r=e[n].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var Iee=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function NM(e){return e.length=0,!0}function kee(e,t,r){if(e.length){let n=VS(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function Ree(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=kee;for(let c=0;c<e.length;c++){let d=e[c];if(d==="["||d==="]")continue;if(d===":"){if(i===!0)s=!0;if(!a(o,n,r))break;if(++t>7){r.error=!0;break}if(c>0&&e[c-1]===":")i=!0;n.push(":");continue}else if(d==="%"){if(!a(o,n,r))break;a=NM}else{o.push(d);continue}}if(o.length)if(a===NM)r.zone=o.join("");else if(s)n.push(o.join(""));else n.push(VS(o));return r.address=n.join(""),r}function LM(e){if(Oee(e,":")<2)return{host:e,isIPV6:!1};let t=Ree(e);if(!t.error){let{address:r,address:n}=t;if(t.zone)r+="%"+t.zone,n+="%25"+t.zone;return{host:r,isIPV6:!0,escapedHost:n}}else return{host:e,isIPV6:!1}}function Oee(e,t){let r=0;for(let n=0;n<e.length;n++)if(e[n]===t)r++;return r}function Cee(e){let t=e,r=[],n=-1,o=0;while(o=t.length){if(o===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(o===2){if(t[0]==="."){if(t[1]===".")break;else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."||t[1]==="/"){r.push("/");break}}}else if(o===3){if(t==="/.."){if(r.length!==0)r.pop();r.push("/");break}}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."){if(t[3]==="/"){if(t=t.slice(3),r.length!==0)r.pop();continue}}}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var Mee={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},$ee=/[@/?#:]/g,Nee=/[@/?#]/g;function DM(e,t){let r=t?Nee:$ee;return r.lastIndex=0,e.replace(r,(n)=>Mee[n])}function zee(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(GS(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));if(t&&BM(s))r+=s;else r+="%"+i;n+=2;continue}}r+=e[n]}return r}function Bee(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(GS(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));if(i!=="."&&BM(i))t+=i;else t+="%"+o;r+=2;continue}}if(Aee(e[r]))t+=e[r];else t+=escape(e[r])}return t}function Lee(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(GS(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Dee(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let r=unescape(e.host);if(!zM(r)){let n=LM(r);if(n.isIPV6===!0)r=`[${n.escapedHost}]`;else r=DM(r,!1)}t.push(r)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}UM.exports={nonSimpleDomain:Iee,recomposeAuthority:Dee,reescapeHostDelimiters:DM,normalizePercentEncoding:zee,normalizePathEncoding:Bee,escapePreservingEscapes:Lee,removeDotSegments:Cee,isIPv4:zM,isUUID:Pee,normalizeIPv6:LM,stringArrayToHexStripped:VS}});var GM=ie(function(Ixe,HM){var{isUUID:Uee}=ZS(),Fee=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,jee=["http","https","ws","wss","urn","urn:uuid"];function qee(e){return jee.indexOf(e)!==-1}function WS(e){if(e.secure===!0)return!0;else if(e.secure===!1)return!1;else if(e.scheme)return e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S");else return!1}function FM(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function jM(e){let t=String(e.scheme).toLowerCase()==="https";if(e.port===(t?443:80)||e.port==="")e.port=void 0;if(!e.path)e.path="/";return e}function Hee(e){return e.secure=WS(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Gee(e){if(e.port===(WS(e)?443:80)||e.port==="")e.port=void 0;if(typeof e.secure==="boolean")e.scheme=e.secure?"wss":"ws",e.secure=void 0;if(e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function Vee(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Fee);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,i=KS(o);if(e.path=void 0,i)e=i.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function Zee(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,i=KS(o);if(i)e=i.serialize(e,t);let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function Wee(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Uee(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function Kee(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var qM={scheme:"http",domainHost:!0,parse:FM,serialize:jM},Yee={scheme:"https",domainHost:qM.domainHost,parse:FM,serialize:jM},r0={scheme:"ws",domainHost:!0,parse:Hee,serialize:Gee},Jee={scheme:"wss",domainHost:r0.domainHost,parse:r0.parse,serialize:r0.serialize},Qee={scheme:"urn",parse:Vee,serialize:Zee,skipNormalize:!0},Xee={scheme:"urn:uuid",parse:Wee,serialize:Kee,skipNormalize:!0},n0={http:qM,https:Yee,ws:r0,wss:Jee,urn:Qee,"urn:uuid":Xee};Object.setPrototypeOf(n0,null);function KS(e){return e&&(n0[e]||n0[e.toLowerCase()])||void 0}HM.exports={wsIsSecure:WS,SCHEMES:n0,isValidSchemeName:qee,getSchemeHandler:KS}});var JM=ie(function(kxe,o0){var{normalizeIPv6:ete,removeDotSegments:af,recomposeAuthority:tte,normalizePercentEncoding:rte,normalizePathEncoding:nte,escapePreservingEscapes:ote,reescapeHostDelimiters:ite,isIPv4:ste,nonSimpleDomain:ate}=ZS(),{SCHEMES:cte,getSchemeHandler:ZM}=GM();function ute(e,t){if(typeof e==="string")e=mte(e,t);else if(typeof e==="object")e=qu(cc(e,t),t);return e}function dte(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=WM(qu(e,n),qu(t,n),n,!0);return n.skipEscape=!0,cc(o,n)}function WM(e,t,r,n){let o={};if(!n)e=qu(cc(e,r),r),t=qu(cc(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=af(t.path||""),o.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=af(t.path||""),o.query=t.query;else{if(!t.path)if(o.path=e.path,t.query!==void 0)o.query=t.query;else o.query=e.query;else{if(t.path[0]==="/")o.path=af(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)o.path="/"+t.path;else if(!e.path)o.path=t.path;else o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;o.path=af(o.path)}o.query=t.query}o.userinfo=e.userinfo,o.host=e.host,o.port=e.port}o.scheme=e.scheme}return o.fragment=t.fragment,o}function lte(e,t,r){let n=VM(e,r),o=VM(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function cc(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[],i=ZM(n.scheme||r.scheme);if(i&&i.serialize)i.serialize(r,n);if(r.path!==void 0)if(!n.skipEscape){if(r.path=ote(r.path),r.scheme!==void 0)r.path=r.path.split("%3A").join(":")}else r.path=rte(r.path);if(n.reference!=="suffix"&&r.scheme)o.push(r.scheme,":");let s=tte(r);if(s!==void 0){if(n.reference!=="suffix")o.push("//");if(o.push(s),r.path&&r.path[0]!=="/")o.push("/")}if(r.path!==void 0){let a=r.path;if(!n.absolutePath&&(!i||!i.absolutePath))a=af(a);if(s===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);o.push(a)}if(r.query!==void 0)o.push("?",r.query);if(r.fragment!==void 0)o.push("#",r.fragment);return o.join("")}var pte=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function fte(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port==="number"&&(e.port<0||e.port>65535))return"URI port is malformed.";return}function KM(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let s=e.match(pte);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port))n.port=s[5];let a=fte(n,s);if(a!==void 0)n.error=n.error||a,o=!0;if(n.host)if(ste(n.host)===!1){let l=ete(n.host);n.host=l.host.toLowerCase(),i=l.isIPV6}else i=!0;if(n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path)n.reference="same-document";else if(n.scheme===void 0)n.reference="relative";else if(n.fragment===void 0)n.reference="absolute";else n.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==n.reference)n.error=n.error||"URI is not a "+r.reference+" reference.";let c=ZM(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)){if(n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&ate(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}}if(!c||c&&!c.skipNormalize){if(e.indexOf("%")!==-1){if(n.scheme!==void 0)n.scheme=unescape(n.scheme);if(n.host!==void 0)n.host=ite(unescape(n.host),i)}if(n.path)n.path=nte(n.path);if(n.fragment)try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}}if(c&&c.parse)c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function qu(e,t){return KM(e,t).parsed}function mte(e,t){return YM(e,t).normalized}function YM(e,t){let{parsed:r,malformedAuthorityOrPort:n}=KM(e,t);return{normalized:n?e:cc(r,t),malformedAuthorityOrPort:n}}function VM(e,t){if(typeof e==="string"){let{normalized:r,malformedAuthorityOrPort:n}=YM(e,t);return n?void 0:r}if(typeof e==="object")return cc(e,t)}var YS={SCHEMES:cte,normalize:ute,resolve:dte,resolveComponent:WM,equal:lte,serialize:cc,parse:qu};o0.exports=YS;o0.exports.default=YS;o0.exports.fastUri=YS});var e$=ie(function(XM){Object.defineProperty(XM,"__esModule",{value:!0});var QM=JM();QM.code='require("ajv/dist/runtime/uri").default';XM.default=QM});var c$=ie(function(Bi){Object.defineProperty(Bi,"__esModule",{value:!0});Bi.CodeGen=Bi.Name=Bi.nil=Bi.stringify=Bi.str=Bi._=Bi.KeywordCxt=void 0;var gte=nf();Object.defineProperty(Bi,"KeywordCxt",{enumerable:!0,get:function(){return gte.KeywordCxt}});var Hu=Ye();Object.defineProperty(Bi,"_",{enumerable:!0,get:function(){return Hu._}});Object.defineProperty(Bi,"str",{enumerable:!0,get:function(){return Hu.str}});Object.defineProperty(Bi,"stringify",{enumerable:!0,get:function(){return Hu.stringify}});Object.defineProperty(Bi,"nil",{enumerable:!0,get:function(){return Hu.nil}});Object.defineProperty(Bi,"Name",{enumerable:!0,get:function(){return Hu.Name}});Object.defineProperty(Bi,"CodeGen",{enumerable:!0,get:function(){return Hu.CodeGen}});var yte=Xg(),i$=of(),bte=IS(),uf=t0(),xte=Ye(),cf=ef(),i0=Xp(),QS=lt(),t$=$M(),_te=e$(),s$=(e,t)=>new RegExp(e,t);s$.code="new RegExp";var wte=["removeAdditional","useDefaults","coerceTypes"],Ste=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vte={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Tte={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},r$=200;function Ete(e){var t,r,n,o,i,s,a,c,d,l,p,m,h,y,x,_,w,A,S,v,P,k,O,N,j;let R=e.strict,K=(t=e.code)===null||t===void 0?void 0:t.optimize,Z=K===!0||K===void 0?1:K||0,re=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:s$,pe=(o=e.uriResolver)!==null&&o!==void 0?o:_te.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:R)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:R)!==null&&c!==void 0?c:!0,strictTypes:(l=(d=e.strictTypes)!==null&&d!==void 0?d:R)!==null&&l!==void 0?l:"log",strictTuples:(m=(p=e.strictTuples)!==null&&p!==void 0?p:R)!==null&&m!==void 0?m:"log",strictRequired:(y=(h=e.strictRequired)!==null&&h!==void 0?h:R)!==null&&y!==void 0?y:!1,code:e.code?{...e.code,optimize:Z,regExp:re}:{optimize:Z,regExp:re},loopRequired:(x=e.loopRequired)!==null&&x!==void 0?x:r$,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:r$,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(A=e.messages)!==null&&A!==void 0?A:!0,inlineRefs:(S=e.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(v=e.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(P=e.addUsedSchema)!==null&&P!==void 0?P:!0,validateSchema:(k=e.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(O=e.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(N=e.unicodeRegExp)!==null&&N!==void 0?N:!0,int32range:(j=e.int32range)!==null&&j!==void 0?j:!0,uriResolver:pe}}class s0{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Ete(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new xte.ValueScope({scope:{},prefixes:Ste,es5:t,lines:r}),this.logger=Ote(e.logger);let n=e.validateFormats;if(e.validateFormats=!1,this.RULES=bte.getRules(),n$.call(this,vte,e,"NOT SUPPORTED"),n$.call(this,Tte,e,"DEPRECATED","warn"),this._metaOpts=kte.call(this),e.formats)Ate.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)Ite.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);Pte.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,n=t$;if(r==="id")n={...t$},n.id=n.$id,delete n.$id;if(t&&e)this.addMetaSchema(n,n[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let n=r(t);if(!("$async"in r))this.errors=r.errors;return n}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(d,l){await o.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function o(d){if(d&&!this.getSchema(d))await n.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof i$.default))throw l;return s.call(this,l),await a.call(this,l.missingSchema),i.call(this,d)}}function s({missingSchema:d,missingRef:l}){if(this.refs[d])throw Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function a(d){let l=await c.call(this,d);if(!this.refs[d])await o.call(this,l.$schema);if(!this.refs[d])this.addSchema(l,d,t)}async function c(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=r(d))}finally{delete this._loading[d]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,n);return this}let o;if(typeof e==="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw Error(`schema ${i} must be string`)}return t=cf.normalizeId(t||o),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(r,e);if(!n&&t){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw Error(o)}return n}getSchema(e){let t;while(typeof(t=o$.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,n=new uf.SchemaEnv({schema:{},schemaId:r});if(t=uf.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=o$.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];if(r)r=cf.normalizeId(r),delete this.schemas[r],delete this.refs[r];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(Mte.call(this,r,t),!t)return QS.eachItem(r,(o)=>JS.call(this,o)),this;Nte.call(this,t);let n={...t,type:i0.getJSONTypes(t.type),schemaType:i0.getJSONTypes(t.schemaType)};return QS.eachItem(r,n.type.length===0?(o)=>JS.call(this,o,n):(o)=>n.type.forEach((i)=>JS.call(this,o,n,i))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let n=r.rules.findIndex((o)=>o.keyword===e);if(n>=0)r.rules.splice(n,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((n)=>`${r}${n.instancePath} ${n.message}`).reduce((n,o)=>n+t+o)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let o=n.split("/").slice(1),i=e;for(let s of o)i=i[s];for(let s in r){let a=r[s];if(typeof a!="object")continue;let{$data:c}=a.definition,d=i[s];if(c&&d)i[s]=a$(d)}}return e}_removeAllSchemas(e,t){for(let r in e){let n=e[r];if(!t||t.test(r)){if(typeof n=="string")delete e[r];else if(n&&!n.meta)this._cache.delete(n.schema),delete e[r]}}}_addSchema(e,t,r,n=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:s}=this.opts;if(typeof e=="object")i=e[s];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;r=cf.normalizeId(i||r);let c=cf.getSchemaRefs.call(this,e,r);if(a=new uf.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:r,localRefs:c}),this._cache.set(a.schema,a),o&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(n)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else uf.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{uf.compileSchema.call(this,e)}finally{this.opts=t}}}s0.ValidationError=yte.default;s0.MissingRefError=i$.default;Bi.default=s0;function n$(e,t,r,n="error"){for(let o in e){let i=o;if(i in t)this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function o$(e){return e=cf.normalizeId(e),this.schemas[e]||this.refs[e]}function Pte(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function Ate(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function Ite(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function kte(){let e={...this.opts};for(let t of wte)delete e[t];return e}var Rte={log(){},warn(){},error(){}};function Ote(e){if(e===!1)return Rte;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var Cte=/^[a-z_$][a-z0-9_$:-]*$/i;function Mte(e,t){let{RULES:r}=this;if(QS.eachItem(e,(n)=>{if(r.keywords[n])throw Error(`Keyword ${n} is already defined`);if(!Cte.test(n))throw Error(`Keyword ${n} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function JS(e,t,r){var n;let o=t===null||t===void 0?void 0:t.post;if(r&&o)throw Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(!s)s={type:r,rules:[]},i.rules.push(s);if(i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:i0.getJSONTypes(t.type),schemaType:i0.getJSONTypes(t.schemaType)}};if(t.before)$te.call(this,s,a,t.before);else s.rules.push(a);i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach((c)=>this.addKeyword(c))}function $te(e,t,r){let n=e.rules.findIndex((o)=>o.keyword===r);if(n>=0)e.rules.splice(n,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function Nte(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=a$(t);e.validateSchema=this.compile(t,!0)}var zte={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function a$(e){return{anyOf:[e,zte]}}});var d$=ie(function(u$){Object.defineProperty(u$,"__esModule",{value:!0});var Dte={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};u$.default=Dte});var g$=ie(function(m$){Object.defineProperty(m$,"__esModule",{value:!0});m$.callRef=m$.getValidate=void 0;var Fte=of(),l$=Gn(),pn=Ye(),Gu=Ni(),p$=t0(),a0=lt(),jte={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:d}=i;if((r==="#"||r==="#/")&&o===d.baseId)return p();let l=p$.resolveRef.call(c,d,o,r);if(l===void 0)throw new Fte.default(n.opts.uriResolver,o,r);if(l instanceof p$.SchemaEnv)return m(l);return h(l);function p(){if(i===d)return c0(e,s,i,i.$async);let y=t.scopeValue("root",{ref:d});return c0(e,pn._`${y}.validate`,d,d.$async)}function m(y){let x=f$(e,y);c0(e,x,y,y.$async)}function h(y){let x=t.scopeValue("schema",a.code.source===!0?{ref:y,code:pn.stringify(y)}:{ref:y}),_=t.name("valid"),w=e.subschema({schema:y,dataTypes:[],schemaPath:pn.nil,topSchemaRef:x,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function f$(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):pn._`${r.scopeValue("wrapper",{ref:t})}.validate`}m$.getValidate=f$;function c0(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,d=c.passContext?Gu.default.this:pn.nil;if(n)l();else p();function l(){if(!a.$async)throw Error("async schema referenced by sync schema");let y=o.let("valid");o.try(()=>{if(o.code(pn._`await ${l$.callValidateCode(e,t,d)}`),h(t),!s)o.assign(y,!0)},(x)=>{if(o.if(pn._`!(${x} instanceof ${i.ValidationError})`,()=>o.throw(x)),m(x),!s)o.assign(y,!1)}),e.ok(y)}function p(){e.result(l$.callValidateCode(e,t,d),()=>h(t),()=>m(t))}function m(y){let x=pn._`${y}.errors`;o.assign(Gu.default.vErrors,pn._`${Gu.default.vErrors} === null ? ${x} : ${Gu.default.vErrors}.concat(${x})`),o.assign(Gu.default.errors,pn._`${Gu.default.vErrors}.length`)}function h(y){var x;if(!i.opts.unevaluated)return;let _=(x=r===null||r===void 0?void 0:r.validate)===null||x===void 0?void 0:x.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps){if(_.props!==void 0)i.props=a0.mergeEvaluated.props(o,_.props,i.props)}else{let w=o.var("props",pn._`${y}.evaluated.props`);i.props=a0.mergeEvaluated.props(o,w,i.props,pn.Name)}if(i.items!==!0)if(_&&!_.dynamicItems){if(_.items!==void 0)i.items=a0.mergeEvaluated.items(o,_.items,i.items)}else{let w=o.var("items",pn._`${y}.evaluated.items`);i.items=a0.mergeEvaluated.items(o,w,i.items,pn.Name)}}}m$.callRef=c0;m$.default=jte});var b$=ie(function(y$){Object.defineProperty(y$,"__esModule",{value:!0});var Gte=d$(),Vte=g$(),Zte=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Gte.default,Vte.default];y$.default=Zte});var _$=ie(function(x$){Object.defineProperty(x$,"__esModule",{value:!0});var d0=Ye(),Ys=d0.operators,u0={maximum:{okStr:"<=",ok:Ys.LTE,fail:Ys.GT},minimum:{okStr:">=",ok:Ys.GTE,fail:Ys.LT},exclusiveMaximum:{okStr:"<",ok:Ys.LT,fail:Ys.GTE},exclusiveMinimum:{okStr:">",ok:Ys.GT,fail:Ys.LTE}},Kte={message:({keyword:e,schemaCode:t})=>d0.str`must be ${u0[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>d0._`{comparison: ${u0[e].okStr}, limit: ${t}}`},Yte={keyword:Object.keys(u0),type:"number",schemaType:"number",$data:!0,error:Kte,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data(d0._`${r} ${u0[t].fail} ${n} || isNaN(${r})`)}};x$.default=Yte});var S$=ie(function(w$){Object.defineProperty(w$,"__esModule",{value:!0});var df=Ye(),Qte={message:({schemaCode:e})=>df.str`must be multiple of ${e}`,params:({schemaCode:e})=>df._`{multipleOf: ${e}}`},Xte={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Qte,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?df._`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:df._`${s} !== parseInt(${s})`;e.fail$data(df._`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};w$.default=Xte});var E$=ie(function(T$){Object.defineProperty(T$,"__esModule",{value:!0});function v$(e){let t=e.length,r=0,n=0,o;while(n<t)if(r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t){if(o=e.charCodeAt(n),(o&64512)===56320)n++}return r}T$.default=v$;v$.code='require("ajv/dist/runtime/ucs2length").default'});var A$=ie(function(P$){Object.defineProperty(P$,"__esModule",{value:!0});var uc=Ye(),rre=lt(),nre=E$(),ore={message({keyword:e,schemaCode:t}){return uc.str`must NOT have ${e==="maxLength"?"more":"fewer"} than ${t} characters`},params:({schemaCode:e})=>uc._`{limit: ${e}}`},ire={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ore,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?uc.operators.GT:uc.operators.LT,s=o.opts.unicode===!1?uc._`${r}.length`:uc._`${rre.useFunc(e.gen,nre.default)}(${r})`;e.fail$data(uc._`${s} ${i} ${n}`)}};P$.default=ire});var k$=ie(function(I$){Object.defineProperty(I$,"__esModule",{value:!0});var are=Gn(),cre=lt(),Vu=Ye(),ure={message:({schemaCode:e})=>Vu.str`must match pattern "${e}"`,params:({schemaCode:e})=>Vu._`{pattern: ${e}}`},dre={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ure,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,d=c.code==="new RegExp"?Vu._`new RegExp`:cre.useFunc(t,c),l=t.let("valid");t.try(()=>t.assign(l,Vu._`${d}(${i}, ${a}).test(${r})`),()=>t.assign(l,!1)),e.fail$data(Vu._`!${l}`)}else{let c=are.usePattern(e,o);e.fail$data(Vu._`!${c}.test(${r})`)}}};I$.default=dre});var O$=ie(function(R$){Object.defineProperty(R$,"__esModule",{value:!0});var lf=Ye(),pre={message({keyword:e,schemaCode:t}){return lf.str`must NOT have ${e==="maxProperties"?"more":"fewer"} than ${t} properties`},params:({schemaCode:e})=>lf._`{limit: ${e}}`},fre={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:pre,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?lf.operators.GT:lf.operators.LT;e.fail$data(lf._`Object.keys(${r}).length ${o} ${n}`)}};R$.default=fre});var M$=ie(function(C$){Object.defineProperty(C$,"__esModule",{value:!0});var ff=Gn(),pf=Ye(),hre=lt(),gre={message:({params:{missingProperty:e}})=>pf.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>pf._`{missingProperty: ${e}}`},yre={keyword:"required",type:"object",schemaType:"array",$data:!0,error:gre,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors)d();else l();if(a.strictRequired){let h=e.parentSchema.properties,{definedProperties:y}=e.it;for(let x of r)if((h===null||h===void 0?void 0:h[x])===void 0&&!y.has(x)){let _=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${x}" is not defined at "${_}" (strictRequired)`;hre.checkStrictMode(s,w,s.opts.strictRequired)}}function d(){if(c||i)e.block$data(pf.nil,p);else for(let h of r)ff.checkReportMissingProp(e,h)}function l(){let h=t.let("missing");if(c||i){let y=t.let("valid",!0);e.block$data(y,()=>m(h,y)),e.ok(y)}else t.if(ff.checkMissingProp(e,r,h)),ff.reportMissingProp(e,h),t.else()}function p(){t.forOf("prop",n,(h)=>{e.setParams({missingProperty:h}),t.if(ff.noPropertyInData(t,o,h,a.ownProperties),()=>e.error())})}function m(h,y){e.setParams({missingProperty:h}),t.forOf(h,n,()=>{t.assign(y,ff.propertyInData(t,o,h,a.ownProperties)),t.if(pf.not(y),()=>{e.error(),t.break()})},pf.nil)}}};C$.default=yre});var N$=ie(function($$){Object.defineProperty($$,"__esModule",{value:!0});var mf=Ye(),xre={message({keyword:e,schemaCode:t}){return mf.str`must NOT have ${e==="maxItems"?"more":"fewer"} than ${t} items`},params:({schemaCode:e})=>mf._`{limit: ${e}}`},_re={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:xre,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?mf.operators.GT:mf.operators.LT;e.fail$data(mf._`${r}.length ${o} ${n}`)}};$$.default=_re});var l0=ie(function(B$){Object.defineProperty(B$,"__esModule",{value:!0});var z$=zS();z$.code='require("ajv/dist/runtime/equal").default';B$.default=z$});var D$=ie(function(L$){Object.defineProperty(L$,"__esModule",{value:!0});var XS=Xp(),Rr=Ye(),vre=lt(),Tre=l0(),Ere={message:({params:{i:e,j:t}})=>Rr.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>Rr._`{i: ${e}, j: ${t}}`},Pre={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Ere,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),d=i.items?XS.getSchemaTypes(i.items):[];e.block$data(c,l,Rr._`${s} === false`),e.ok(c);function l(){let y=t.let("i",Rr._`${r}.length`),x=t.let("j");e.setParams({i:y,j:x}),t.assign(c,!0),t.if(Rr._`${y} > 1`,()=>(p()?m:h)(y,x))}function p(){return d.length>0&&!d.some((y)=>y==="object"||y==="array")}function m(y,x){let _=t.name("item"),w=XS.checkDataTypes(d,_,a.opts.strictNumbers,XS.DataType.Wrong),A=t.const("indices",Rr._`{}`);t.for(Rr._`;${y}--;`,()=>{if(t.let(_,Rr._`${r}[${y}]`),t.if(w,Rr._`continue`),d.length>1)t.if(Rr._`typeof ${_} == "string"`,Rr._`${_} += "_"`);t.if(Rr._`typeof ${A}[${_}] == "number"`,()=>{t.assign(x,Rr._`${A}[${_}]`),e.error(),t.assign(c,!1).break()}).code(Rr._`${A}[${_}] = ${y}`)})}function h(y,x){let _=vre.useFunc(t,Tre.default),w=t.name("outer");t.label(w).for(Rr._`;${y}--;`,()=>t.for(Rr._`${x} = ${y}; ${x}--;`,()=>t.if(Rr._`${_}(${r}[${y}], ${r}[${x}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};L$.default=Pre});var F$=ie(function(U$){Object.defineProperty(U$,"__esModule",{value:!0});var ev=Ye(),Ire=lt(),kre=l0(),Rre={message:"must be equal to constant",params:({schemaCode:e})=>ev._`{allowedValue: ${e}}`},Ore={keyword:"const",$data:!0,error:Rre,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;if(n||i&&typeof i=="object")e.fail$data(ev._`!${Ire.useFunc(t,kre.default)}(${r}, ${o})`);else e.fail(ev._`${i} !== ${r}`)}};U$.default=Ore});var q$=ie(function(j$){Object.defineProperty(j$,"__esModule",{value:!0});var hf=Ye(),Mre=lt(),$re=l0(),Nre={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>hf._`{allowedValues: ${e}}`},zre={keyword:"enum",schemaType:"array",$data:!0,error:Nre,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,d=()=>c!==null&&c!==void 0?c:c=Mre.useFunc(t,$re.default),l;if(a||n)l=t.let("valid"),e.block$data(l,p);else{if(!Array.isArray(o))throw Error("ajv implementation error");let h=t.const("vSchema",i);l=hf.or(...o.map((y,x)=>m(h,x)))}e.pass(l);function p(){t.assign(l,!1),t.forOf("v",i,(h)=>t.if(hf._`${d()}(${r}, ${h})`,()=>t.assign(l,!0).break()))}function m(h,y){let x=o[y];return typeof x==="object"&&x!==null?hf._`${d()}(${r}, ${h}[${y}])`:hf._`${r} === ${x}`}}};j$.default=zre});var G$=ie(function(H$){Object.defineProperty(H$,"__esModule",{value:!0});var Lre=_$(),Dre=S$(),Ure=A$(),Fre=k$(),jre=O$(),qre=M$(),Hre=N$(),Gre=D$(),Vre=F$(),Zre=q$(),Wre=[Lre.default,Dre.default,Ure.default,Fre.default,jre.default,qre.default,Hre.default,Gre.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Vre.default,Zre.default];H$.default=Wre});var rv=ie(function(Z$){Object.defineProperty(Z$,"__esModule",{value:!0});Z$.validateAdditionalItems=void 0;var dc=Ye(),tv=lt(),Yre={message:({params:{len:e}})=>dc.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>dc._`{limit: ${e}}`},Jre={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Yre,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){tv.checkStrictMode(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}V$(e,n)}};function V$(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",dc._`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass(dc._`${a} <= ${t.length}`);else if(typeof n=="object"&&!tv.alwaysValidSchema(s,n)){let d=r.var("valid",dc._`${a} <= ${t.length}`);r.if(dc.not(d),()=>c(d)),e.ok(d)}function c(d){r.forRange("i",t.length,a,(l)=>{if(e.subschema({keyword:i,dataProp:l,dataPropType:tv.Type.Num},d),!s.allErrors)r.if(dc.not(d),()=>r.break())})}}Z$.validateAdditionalItems=V$;Z$.default=Jre});var nv=ie(function(J$){Object.defineProperty(J$,"__esModule",{value:!0});J$.validateTuple=void 0;var K$=Ye(),p0=lt(),Xre=Gn(),ene={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Y$(e,"additionalItems",t);if(r.items=!0,p0.alwaysValidSchema(r,t))return;e.ok(Xre.validateArray(e))}};function Y$(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;if(l(o),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=p0.mergeEvaluated.items(n,r.length,a.items);let c=n.name("valid"),d=n.const("len",K$._`${i}.length`);r.forEach((p,m)=>{if(p0.alwaysValidSchema(a,p))return;n.if(K$._`${d} > ${m}`,()=>e.subschema({keyword:s,schemaProp:m,dataProp:m},c)),e.ok(c)});function l(p){let{opts:m,errSchemaPath:h}=a,y=r.length,x=y===p.minItems&&(y===p.maxItems||p[t]===!1);if(m.strictTuples&&!x){let _=`"${s}" is ${y}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;p0.checkStrictMode(a,_,m.strictTuples)}}}J$.validateTuple=Y$;J$.default=ene});var eN=ie(function(X$){Object.defineProperty(X$,"__esModule",{value:!0});var rne=nv(),nne={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>rne.validateTuple(e,"items")};X$.default=nne});var nN=ie(function(rN){Object.defineProperty(rN,"__esModule",{value:!0});var tN=Ye(),ine=lt(),sne=Gn(),ane=rv(),cne={message:({params:{len:e}})=>tN.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>tN._`{limit: ${e}}`},une={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:cne,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;if(n.items=!0,ine.alwaysValidSchema(n,t))return;if(o)ane.validateAdditionalItems(e,o);else e.ok(sne.validateArray(e))}};rN.default=une});var iN=ie(function(oN){Object.defineProperty(oN,"__esModule",{value:!0});var Vn=Ye(),f0=lt(),lne={message:({params:{min:e,max:t}})=>t===void 0?Vn.str`must contain at least ${e} valid item(s)`:Vn.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Vn._`{minContains: ${e}}`:Vn._`{minContains: ${e}, maxContains: ${t}}`},pne={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lne,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:d}=n;if(i.opts.next)s=c===void 0?1:c,a=d;else s=1;let l=t.const("len",Vn._`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){f0.checkStrictMode(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){f0.checkStrictMode(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if(f0.alwaysValidSchema(i,r)){let x=Vn._`${l} >= ${s}`;if(a!==void 0)x=Vn._`${x} && ${l} <= ${a}`;e.pass(x);return}i.items=!0;let p=t.name("valid");if(a===void 0&&s===1)h(p,()=>t.if(p,()=>t.break()));else if(s===0){if(t.let(p,!0),a!==void 0)t.if(Vn._`${o}.length > 0`,m)}else t.let(p,!1),m();e.result(p,()=>e.reset());function m(){let x=t.name("_valid"),_=t.let("count",0);h(x,()=>t.if(x,()=>y(_)))}function h(x,_){t.forRange("i",0,l,(w)=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:f0.Type.Num,compositeRule:!0},x),_()})}function y(x){if(t.code(Vn._`${x}++`),a===void 0)t.if(Vn._`${x} >= ${s}`,()=>t.assign(p,!0).break());else if(t.if(Vn._`${x} > ${a}`,()=>t.assign(p,!1).break()),s===1)t.assign(p,!0);else t.if(Vn._`${x} >= ${s}`,()=>t.assign(p,!0))}}};oN.default=pne});var lN=ie(function(cN){Object.defineProperty(cN,"__esModule",{value:!0});cN.validateSchemaDeps=cN.validatePropertyDeps=cN.error=void 0;var ov=Ye(),mne=lt(),gf=Gn();cN.error={message:({params:{property:e,depsCount:t,deps:r}})=>ov.str`must have ${t===1?"property":"properties"} ${r} when property ${e} is present`,params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>ov._`{property: ${e},
|
|
23
|
+
|| ${s} === "boolean" || ${o} === null`).assign(a,Ke._`[${o}]`)}}}function kQ({gen:e,parentData:t,parentDataProperty:r},n){e.if(Ke._`${t} !== undefined`,()=>e.assign(Ke._`${t}[${r}]`,n))}function RS(e,t,r,n=Uu.Correct){let o=n===Uu.Correct?Ke.operators.EQ:Ke.operators.NEQ,i;switch(e){case"null":return Ke._`${t} ${o} null`;case"array":i=Ke._`Array.isArray(${t})`;break;case"object":i=Ke._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s(Ke._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return Ke._`typeof ${t} ${o} ${e}`}return n===Uu.Correct?i:Ke.not(i);function s(a=Ke.nil){return Ke.and(Ke._`typeof ${t} == "number"`,a,r?Ke._`isFinite(${t})`:Ke.nil)}}BC.checkDataType=RS;function OS(e,t,r,n){if(e.length===1)return RS(e[0],t,r,n);let o,i=$C.toHash(e);if(i.array&&i.object){let s=Ke._`typeof ${t} != "object"`;o=i.null?s:Ke._`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=Ke.nil;if(i.number)delete i.integer;for(let s in i)o=Ke.and(o,RS(s,t,r,n));return o}BC.checkDataTypes=OS;var RQ={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?Ke._`{type: ${e}}`:Ke._`{type: ${t}}`};function CS(e){let t=OQ(e);TQ.reportError(t,RQ)}BC.reportTypeError=CS;function OQ(e){let{gen:t,data:r,schema:n}=e,o=$C.schemaRefOrVal(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var jC=ie(function(UC){Object.defineProperty(UC,"__esModule",{value:!0});UC.assignDefaults=void 0;var Fu=Ye(),LQ=lt();function DQ(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)DC(e,o,r[o].default);else if(t==="array"&&Array.isArray(n))n.forEach((o,i)=>DC(e,i,o.default))}UC.assignDefaults=DQ;function DC(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=Fu._`${i}${Fu.getProperty(t)}`;if(o){LQ.checkStrictMode(e,`default is ignored for: ${a}`);return}let c=Fu._`${a} === undefined`;if(s.useDefaults==="empty")c=Fu._`${c} || ${a} === null || ${a} === ""`;n.if(c,Fu._`${a} = ${Fu.stringify(r)}`)}});var Gn=ie(function(GC){Object.defineProperty(GC,"__esModule",{value:!0});GC.validateUnion=GC.validateArray=GC.usePattern=GC.callValidateCode=GC.schemaProperties=GC.allSchemaProperties=GC.noPropertyInData=GC.propertyInData=GC.isOwnProperty=GC.hasPropFunc=GC.reportMissingProp=GC.checkMissingProp=GC.checkReportMissingProp=void 0;var Ut=Ye(),MS=lt(),Ws=Ni(),UQ=lt();function FQ(e,t){let{gen:r,data:n,it:o}=e;r.if(NS(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:Ut._`${t}`},!0),e.error()})}GC.checkReportMissingProp=FQ;function jQ({gen:e,data:t,it:{opts:r}},n,o){return Ut.or(...n.map((i)=>Ut.and(NS(e,t,i,r.ownProperties),Ut._`${o} = ${i}`)))}GC.checkMissingProp=jQ;function qQ(e,t){e.setParams({missingProperty:t},!0),e.error()}GC.reportMissingProp=qQ;function qC(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Ut._`Object.prototype.hasOwnProperty`})}GC.hasPropFunc=qC;function $S(e,t,r){return Ut._`${qC(e)}.call(${t}, ${r})`}GC.isOwnProperty=$S;function HQ(e,t,r,n){let o=Ut._`${t}${Ut.getProperty(r)} !== undefined`;return n?Ut._`${o} && ${$S(e,t,r)}`:o}GC.propertyInData=HQ;function NS(e,t,r,n){let o=Ut._`${t}${Ut.getProperty(r)} === undefined`;return n?Ut.or(o,Ut.not($S(e,t,r))):o}GC.noPropertyInData=NS;function HC(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}GC.allSchemaProperties=HC;function GQ(e,t){return HC(t).filter((r)=>!MS.alwaysValidSchema(e,t[r]))}GC.schemaProperties=GQ;function VQ({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,d){let l=d?Ut._`${e}, ${t}, ${n}${o}`:t,p=[[Ws.default.instancePath,Ut.strConcat(Ws.default.instancePath,i)],[Ws.default.parentData,s.parentData],[Ws.default.parentDataProperty,s.parentDataProperty],[Ws.default.rootData,Ws.default.rootData]];if(s.opts.dynamicRef)p.push([Ws.default.dynamicAnchors,Ws.default.dynamicAnchors]);let m=Ut._`${l}, ${r.object(...p)}`;return c!==Ut.nil?Ut._`${a}.call(${c}, ${m})`:Ut._`${a}(${m})`}GC.callValidateCode=VQ;var ZQ=Ut._`new RegExp`;function WQ({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:Ut._`${o.code==="new RegExp"?ZQ:UQ.useFunc(e,o)}(${r}, ${n})`})}GC.usePattern=WQ;function KQ(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",Ut._`${r}.length`);t.forRange("i",0,c,(d)=>{e.subschema({keyword:n,dataProp:d,dataPropType:MS.Type.Num},i),t.if(Ut.not(i),a)})}}GC.validateArray=KQ;function YQ(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((c)=>MS.alwaysValidSchema(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,d)=>{let l=e.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);if(t.assign(s,Ut._`${s} || ${a}`),!e.mergeValidEvaluated(l,a))t.if(Ut.not(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}GC.validateUnion=YQ});var JC=ie(function(KC){Object.defineProperty(KC,"__esModule",{value:!0});KC.validateKeywordUsage=KC.validSchemaType=KC.funcKeywordCode=KC.macroKeywordCode=void 0;var Xr=Ye(),sc=Ni(),uX=Gn(),dX=Qp();function lX(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=WC(r,n,a);if(s.opts.validateSchema!==!1)s.self.validateSchema(a,!0);let d=r.name("valid");e.subschema({schema:a,schemaPath:Xr.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}KC.macroKeywordCode=lX;function pX(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;mX(c,t);let d=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,l=WC(n,o,d),p=n.let("valid");e.block$data(p,m),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function m(){if(t.errors===!1){if(x(),t.modifying)ZC(e);_(()=>e.error())}else{let w=t.async?h():y();if(t.modifying)ZC(e);_(()=>fX(e,w))}}function h(){let w=n.let("ruleErrs",null);return n.try(()=>x(Xr._`await `),(A)=>n.assign(p,!1).if(Xr._`${A} instanceof ${c.ValidationError}`,()=>n.assign(w,Xr._`${A}.errors`),()=>n.throw(A))),w}function y(){let w=Xr._`${l}.errors`;return n.assign(w,null),x(Xr.nil),w}function x(w=t.async?Xr._`await `:Xr.nil){let A=c.opts.passContext?sc.default.this:sc.default.self,S=!(("compile"in t)&&!a||t.schema===!1);n.assign(p,Xr._`${w}${uX.callValidateCode(e,l,A,S)}`,t.modifying)}function _(w){var A;n.if(Xr.not((A=t.valid)!==null&&A!==void 0?A:p),w)}}KC.funcKeywordCode=pX;function ZC(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,Xr._`${n.parentData}[${n.parentDataProperty}]`))}function fX(e,t){let{gen:r}=e;r.if(Xr._`Array.isArray(${t})`,()=>{r.assign(sc.default.vErrors,Xr._`${sc.default.vErrors} === null ? ${t} : ${sc.default.vErrors}.concat(${t})`).assign(sc.default.errors,Xr._`${sc.default.vErrors}.length`),dX.extendErrors(e)},()=>e.error())}function mX({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function WC(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:Xr.stringify(r)})}function hX(e,t,r=!1){return!t.length||t.some((n)=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}KC.validSchemaType=hX;function gX({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw Error("ajv implementation error");let s=o.dependencies;if(s===null||s===void 0?void 0:s.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema){if(!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw Error(c)}}}KC.validateKeywordUsage=gX});var tM=ie(function(XC){Object.defineProperty(XC,"__esModule",{value:!0});XC.extendSubschemaMode=XC.extendSubschemaData=XC.getSubschema=void 0;var Vo=Ye(),QC=lt();function _X(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:Vo._`${e.schemaPath}${Vo.getProperty(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Vo._`${e.schemaPath}${Vo.getProperty(t)}${Vo.getProperty(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${QC.escapeFragment(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw Error('either "keyword" or "schema" must be passed')}XC.getSubschema=_X;function wX(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:d,dataPathArr:l,opts:p}=t,m=a.let("data",Vo._`${t.data}${Vo.getProperty(r)}`,!0);c(m),e.errorPath=Vo.str`${d}${QC.getErrorPath(r,n,p.jsPropertySyntax)}`,e.parentDataProperty=Vo._`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){let d=o instanceof Vo.Name?o:a.let("data",o,!0);if(c(d),s!==void 0)e.propertyName=s}if(i)e.dataTypes=i;function c(d){e.data=d,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,d]}}XC.extendSubschemaData=wX;function SX(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){if(n!==void 0)e.compositeRule=n;if(o!==void 0)e.createErrors=o;if(i!==void 0)e.allErrors=i;e.jtdDiscriminator=t,e.jtdMetadata=r}XC.extendSubschemaMode=SX});var zS=ie(function(xxe,rM){rM.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var oM=ie(function(_xe,nM){var Ks=nM.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Jg(t,n,o,e,"",e)};Ks.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ks.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ks.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ks.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Jg(e,t,r,n,o,i,s,a,c,d){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,d);for(var l in n){var p=n[l];if(Array.isArray(p)){if(l in Ks.arrayKeywords)for(var m=0;m<p.length;m++)Jg(e,t,r,p[m],o+"/"+l+"/"+m,i,o,l,n,m)}else if(l in Ks.propsKeywords){if(p&&typeof p=="object")for(var h in p)Jg(e,t,r,p[h],o+"/"+l+"/"+EX(h),i,o,l,n,h)}else if(l in Ks.keywords||e.allKeys&&!(l in Ks.skipKeywords))Jg(e,t,r,p,o+"/"+l,i,o,l,n)}r(n,o,i,s,a,c,d)}}function EX(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ef=ie(function(cM){Object.defineProperty(cM,"__esModule",{value:!0});cM.getSchemaRefs=cM.resolveUrl=cM.normalizeId=cM._getFullPath=cM.getFullPath=cM.inlineRef=void 0;var PX=lt(),AX=zS(),IX=oM(),kX=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function RX(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!BS(e);if(!t)return!1;return iM(e)<=t}cM.inlineRef=RX;var OX=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function BS(e){for(let t in e){if(OX.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(BS))return!0;if(typeof r=="object"&&BS(r))return!0}return!1}function iM(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,kX.has(r))continue;if(typeof e[r]=="object")PX.eachItem(e[r],(n)=>t+=iM(n));if(t===1/0)return 1/0}return t}function sM(e,t="",r){if(r!==!1)t=ju(t);let n=e.parse(t);return aM(e,n)}cM.getFullPath=sM;function aM(e,t){return e.serialize(t).split("#")[0]+"#"}cM._getFullPath=aM;var CX=/#\/?$/;function ju(e){return e?e.replace(CX,""):""}cM.normalizeId=ju;function MX(e,t,r){return r=ju(r),e.resolve(t,r)}cM.resolveUrl=MX;var $X=/^[a-z_][-a-z0-9._]*$/i;function NX(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=ju(e[r]||t),i={"":o},s=sM(n,o,!1),a={},c=new Set;return IX(e,{allKeys:!0},(p,m,h,y)=>{if(y===void 0)return;let x=s+m,_=i[y];if(typeof p[r]=="string")_=w.call(this,p[r]);A.call(this,p.$anchor),A.call(this,p.$dynamicAnchor),i[m]=_;function w(S){let v=this.opts.uriResolver.resolve;if(S=ju(_?v(_,S):S),c.has(S))throw l(S);c.add(S);let P=this.refs[S];if(typeof P=="string")P=this.refs[P];if(typeof P=="object")d(p,P.schema,S);else if(S!==ju(x))if(S[0]==="#")d(p,a[S],S),a[S]=p;else this.refs[S]=x;return S}function A(S){if(typeof S=="string"){if(!$X.test(S))throw Error(`invalid anchor "${S}"`);w.call(this,`#${S}`)}}}),a;function d(p,m,h){if(m!==void 0&&!AX(p,m))throw l(h)}function l(p){return Error(`reference "${p}" resolves to more than one schema`)}}cM.getSchemaRefs=NX});var nf=ie(function(TM){Object.defineProperty(TM,"__esModule",{value:!0});TM.getData=TM.KeywordCxt=TM.validateFunctionCode=void 0;var fM=AC(),mM=Xp(),LS=kS(),Qg=Xp(),FX=jC(),tf=JC(),DS=tM(),Ie=Ye(),je=Ni(),jX=ef(),zi=lt(),rf=Qp();function qX(e){if(yM(e)){if(bM(e),gM(e)){VX(e);return}}hM(e,()=>fM.topBoolOrEmptySchema(e))}TM.validateFunctionCode=qX;function hM({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){if(o.code.es5)e.func(t,Ie._`${je.default.data}, ${je.default.valCxt}`,n.$async,()=>{e.code(Ie._`"use strict"; ${dM(r,o)}`),GX(e,o),e.code(i)});else e.func(t,Ie._`${je.default.data}, ${HX(o)}`,n.$async,()=>e.code(dM(r,o)).code(i))}function HX(e){return Ie._`{${je.default.instancePath}="", ${je.default.parentData}, ${je.default.parentDataProperty}, ${je.default.rootData}=${je.default.data}${e.dynamicRef?Ie._`, ${je.default.dynamicAnchors}={}`:Ie.nil}}={}`}function GX(e,t){e.if(je.default.valCxt,()=>{if(e.var(je.default.instancePath,Ie._`${je.default.valCxt}.${je.default.instancePath}`),e.var(je.default.parentData,Ie._`${je.default.valCxt}.${je.default.parentData}`),e.var(je.default.parentDataProperty,Ie._`${je.default.valCxt}.${je.default.parentDataProperty}`),e.var(je.default.rootData,Ie._`${je.default.valCxt}.${je.default.rootData}`),t.dynamicRef)e.var(je.default.dynamicAnchors,Ie._`${je.default.valCxt}.${je.default.dynamicAnchors}`)},()=>{if(e.var(je.default.instancePath,Ie._`""`),e.var(je.default.parentData,Ie._`undefined`),e.var(je.default.parentDataProperty,Ie._`undefined`),e.var(je.default.rootData,je.default.data),t.dynamicRef)e.var(je.default.dynamicAnchors,Ie._`{}`)})}function VX(e){let{schema:t,opts:r,gen:n}=e;hM(e,()=>{if(r.$comment&&t.$comment)_M(e);if(JX(e),n.let(je.default.vErrors,null),n.let(je.default.errors,0),r.unevaluated)ZX(e);xM(e),eee(e)});return}function ZX(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",Ie._`${r}.evaluated`),t.if(Ie._`${e.evaluated}.dynamicProps`,()=>t.assign(Ie._`${e.evaluated}.props`,Ie._`undefined`)),t.if(Ie._`${e.evaluated}.dynamicItems`,()=>t.assign(Ie._`${e.evaluated}.items`,Ie._`undefined`))}function dM(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?Ie._`/*# sourceURL=${r} */`:Ie.nil}function WX(e,t){if(yM(e)){if(bM(e),gM(e)){KX(e,t);return}}fM.boolOrEmptySchema(e,t)}function gM({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function yM(e){return typeof e.schema!="boolean"}function KX(e,t){let{schema:r,gen:n,opts:o}=e;if(o.$comment&&r.$comment)_M(e);QX(e),XX(e);let i=n.const("_errs",je.default.errors);xM(e,i),n.var(t,Ie._`${i} === ${je.default.errors}`)}function bM(e){zi.checkUnknownRules(e),YX(e)}function xM(e,t){if(e.opts.jtd)return lM(e,[],!1,t);let r=mM.getSchemaTypes(e.schema),n=mM.coerceAndCheckDataType(e,r);lM(e,r,!n,t)}function YX(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;if(t.$ref&&n.ignoreKeywordsWithRef&&zi.schemaHasRulesButRef(t,o.RULES))o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function JX(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)zi.checkStrictMode(e,"default is ignored in the schema root")}function QX(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=jX.resolveUrl(e.opts.uriResolver,e.baseId,t)}function XX(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function _M({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code(Ie._`${je.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=Ie.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(Ie._`${je.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function eee(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;if(r.$async)t.if(Ie._`${je.default.errors} === 0`,()=>t.return(je.default.data),()=>t.throw(Ie._`new ${o}(${je.default.vErrors})`));else{if(t.assign(Ie._`${n}.errors`,je.default.vErrors),i.unevaluated)tee(e);t.return(Ie._`${je.default.errors} === 0`)}}function tee({gen:e,evaluated:t,props:r,items:n}){if(r instanceof Ie.Name)e.assign(Ie._`${t}.props`,r);if(n instanceof Ie.Name)e.assign(Ie._`${t}.items`,n)}function lM(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:d}=e,{RULES:l}=d;if(i.$ref&&(c.ignoreKeywordsWithRef||!zi.schemaHasRulesButRef(i,l))){o.block(()=>SM(e,"$ref",l.all.$ref.definition));return}if(!c.jtd)ree(e,t);o.block(()=>{for(let m of l.rules)p(m);p(l.post)});function p(m){if(!LS.shouldUseGroup(i,m))return;if(m.type){if(o.if(Qg.checkDataType(m.type,s,c.strictNumbers)),pM(e,m),t.length===1&&t[0]===m.type&&r)o.else(),Qg.reportTypeError(e);o.endIf()}else pM(e,m);if(!a)o.if(Ie._`${je.default.errors} === ${n||0}`)}}function pM(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;if(o)FX.assignDefaults(e,t.type);r.block(()=>{for(let i of t.rules)if(LS.shouldUseRule(n,i))SM(e,i.keyword,i.definition,t.type)})}function ree(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(nee(e,t),!e.opts.allowUnionTypes)oee(e,t);iee(e,e.dataTypes)}function nee(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!wM(e.dataTypes,r))US(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),aee(e,t)}function oee(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))US(e,"use allowUnionTypes to allow union type keyword")}function iee(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&LS.shouldUseRule(e.schema,o)){let{type:i}=o.definition;if(i.length&&!i.some((s)=>see(t,s)))US(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function see(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function wM(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function aee(e,t){let r=[];for(let n of e.dataTypes)if(wM(t,n))r.push(n);else if(t.includes("integer")&&n==="number")r.push("integer");e.dataTypes=r}function US(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,zi.checkStrictMode(e,t,e.opts.strictTypes)}class FS{constructor(e,t,r){if(tf.validateKeywordUsage(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=zi.schemaRefOrVal(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",vM(this.$data,e));else if(this.schemaCode=this.schemaValue,!tf.validSchemaType(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",je.default.errors)}result(e,t,r){this.failResult(Ie.not(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult(Ie.not(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(Ie._`${t} !== undefined && (${Ie.or(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?rf.reportExtraError:rf.reportError)(this,this.def.error,t)}$dataError(){rf.reportError(this,this.def.$dataError||rf.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');rf.resetErrorsCount(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,r=Ie.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=Ie.nil,t=Ie.nil){if(!this.$data)return;let{gen:r,schemaCode:n,schemaType:o,def:i}=this;if(r.if(Ie.or(Ie._`${n} === undefined`,t)),e!==Ie.nil)r.assign(e,!0);if(o.length||i.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==Ie.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:n,it:o}=this;return Ie.or(i(),s());function i(){if(r.length){if(!(t instanceof Ie.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return Ie._`${Qg.checkDataTypes(a,t,o.opts.strictNumbers,Qg.DataType.Wrong)}`}return Ie.nil}function s(){if(n.validateSchema){let a=e.scopeValue("validate$data",{ref:n.validateSchema});return Ie._`!${a}(${t})`}return Ie.nil}}subschema(e,t){let r=DS.getSubschema(this.it,e);DS.extendSubschemaData(r,this.it,e),DS.extendSubschemaMode(r,e);let n={...this.it,...r,items:void 0,props:void 0};return WX(n,t),n}mergeEvaluated(e,t){let{it:r,gen:n}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=zi.mergeEvaluated.props(n,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=zi.mergeEvaluated.items(n,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:n}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return n.if(t,()=>this.mergeEvaluated(e,Ie.Name)),!0}}TM.KeywordCxt=FS;function SM(e,t,r,n){let o=new FS(e,r,t);if("code"in r)r.code(o,n);else if(o.$data&&r.validate)tf.funcKeywordCode(o,r);else if("macro"in r)tf.macroKeywordCode(o,r);else if(r.compile||r.validate)tf.funcKeywordCode(o,r)}var cee=/^\/(?:[^~]|~0|~1)*$/,uee=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function vM(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return je.default.rootData;if(e[0]==="/"){if(!cee.test(e))throw Error(`Invalid JSON-pointer: ${e}`);o=e,i=je.default.rootData}else{let d=uee.exec(e);if(!d)throw Error(`Invalid JSON-pointer: ${e}`);let l=+d[1];if(o=d[2],o==="#"){if(l>=t)throw Error(c("property/index",l));return n[t-l]}if(l>t)throw Error(c("data",l));if(i=r[t-l],!o)return i}let s=i,a=o.split("/");for(let d of a)if(d)i=Ie._`${i}${Ie.getProperty(zi.unescapeJsonPointer(d))}`,s=Ie._`${s} && ${i}`;return s;function c(d,l){return`Cannot access ${d} ${l} levels up, current level is ${t}`}}TM.getData=vM});var Xg=ie(function(AM){Object.defineProperty(AM,"__esModule",{value:!0});class PM extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}AM.default=PM});var of=ie(function(kM){Object.defineProperty(kM,"__esModule",{value:!0});var jS=ef();class IM extends Error{constructor(e,t,r,n){super(n||`can't resolve reference ${r} from id ${t}`);this.missingRef=jS.resolveUrl(e,t,r),this.missingSchema=jS.normalizeId(jS.getFullPath(e,this.missingRef))}}kM.default=IM});var t0=ie(function(CM){Object.defineProperty(CM,"__esModule",{value:!0});CM.resolveSchema=CM.getCompilingSchema=CM.resolveRef=CM.compileSchema=CM.SchemaEnv=void 0;var ho=Ye(),mee=Xg(),ac=Ni(),go=ef(),RM=lt(),hee=nf();class sf{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:go.normalizeId(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}CM.SchemaEnv=sf;function HS(e){let t=OM.call(this,e);if(t)return t;let r=go.getFullPath(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new ho.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;if(e.$async)a=s.scopeValue("Error",{ref:mee.default,code:ho._`require("ajv/dist/runtime/validation_error").default`});let c=s.scopeName("validate");e.validateName=c;let d={gen:s,allErrors:this.opts.allErrors,data:ac.default.data,parentData:ac.default.parentData,parentDataProperty:ac.default.parentDataProperty,dataNames:[ac.default.data],dataPathArr:[ho.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:ho.stringify(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:ho.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:ho._`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),hee.validateFunctionCode(d),s.optimize(this.opts.code.optimize);let p=s.toString();if(l=`${s.scopeRefs(ac.default.scope)}return ${p}`,this.opts.code.process)l=this.opts.code.process(l,e);let h=Function(`${ac.default.self}`,`${ac.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=e.schema,h.schemaEnv=e,e.$async)h.$async=!0;if(this.opts.code.source===!0)h.source={validateName:c,validateCode:p,scopeValues:s._values};if(this.opts.unevaluated){let{props:y,items:x}=d;if(h.evaluated={props:y instanceof ho.Name?void 0:y,items:x instanceof ho.Name?void 0:x,dynamicProps:y instanceof ho.Name,dynamicItems:x instanceof ho.Name},h.source)h.source.evaluated=ho.stringify(h.evaluated)}return e.validate=h,e}catch(p){if(delete e.validate,delete e.validateName,l)this.logger.error("Error compiling schema, function code:",l);throw p}finally{this._compilations.delete(e)}}CM.compileSchema=HS;function gee(e,t,r){var n;r=go.resolveUrl(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=xee.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;if(s)i=new sf({schema:s,schemaId:a,root:e,baseId:t})}if(i===void 0)return;return e.refs[r]=yee.call(this,i)}CM.resolveRef=gee;function yee(e){if(go.inlineRef(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:HS.call(this,e)}function OM(e){for(let t of this._compilations)if(bee(t,e))return t}CM.getCompilingSchema=OM;function bee(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function xee(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||e0.call(this,e,t)}function e0(e,t){let r=this.opts.uriResolver.parse(t),n=go._getFullPath(this.opts.uriResolver,r),o=go.getFullPath(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return qS.call(this,r,e);let i=go.normalizeId(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=e0.call(this,e,s);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return qS.call(this,r,a)}if(typeof(s===null||s===void 0?void 0:s.schema)!=="object")return;if(!s.validate)HS.call(this,s);if(i===go.normalizeId(t)){let{schema:a}=s,{schemaId:c}=this.opts,d=a[c];if(d)o=go.resolveUrl(this.opts.uriResolver,o,d);return new sf({schema:a,schemaId:c,root:e,baseId:o})}return qS.call(this,r,s)}CM.resolveSchema=e0;var _ee=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qS(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let c=r[RM.unescapeFragment(a)];if(c===void 0)return;r=c;let d=typeof r==="object"&&r[this.opts.schemaId];if(!_ee.has(a)&&d)t=go.resolveUrl(this.opts.uriResolver,t,d)}let i;if(typeof r!="boolean"&&r.$ref&&!RM.schemaHasRulesButRef(r,this.RULES)){let a=go.resolveUrl(this.opts.uriResolver,t,r.$ref);i=e0.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new sf({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i;return}});var $M=ie(function(Pxe,Eee){Eee.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var ZS=ie(function(Axe,UM){var Pee=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zM=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),GS=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),BM=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Aee=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function VS(e){let t="",r=0,n=0;for(n=0;n<e.length;n++){if(r=e[n].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var Iee=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function NM(e){return e.length=0,!0}function kee(e,t,r){if(e.length){let n=VS(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function Ree(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=kee;for(let c=0;c<e.length;c++){let d=e[c];if(d==="["||d==="]")continue;if(d===":"){if(i===!0)s=!0;if(!a(o,n,r))break;if(++t>7){r.error=!0;break}if(c>0&&e[c-1]===":")i=!0;n.push(":");continue}else if(d==="%"){if(!a(o,n,r))break;a=NM}else{o.push(d);continue}}if(o.length)if(a===NM)r.zone=o.join("");else if(s)n.push(o.join(""));else n.push(VS(o));return r.address=n.join(""),r}function LM(e){if(Oee(e,":")<2)return{host:e,isIPV6:!1};let t=Ree(e);if(!t.error){let{address:r,address:n}=t;if(t.zone)r+="%"+t.zone,n+="%25"+t.zone;return{host:r,isIPV6:!0,escapedHost:n}}else return{host:e,isIPV6:!1}}function Oee(e,t){let r=0;for(let n=0;n<e.length;n++)if(e[n]===t)r++;return r}function Cee(e){let t=e,r=[],n=-1,o=0;while(o=t.length){if(o===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(o===2){if(t[0]==="."){if(t[1]===".")break;else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."||t[1]==="/"){r.push("/");break}}}else if(o===3){if(t==="/.."){if(r.length!==0)r.pop();r.push("/");break}}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."){if(t[3]==="/"){if(t=t.slice(3),r.length!==0)r.pop();continue}}}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var Mee={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},$ee=/[@/?#:]/g,Nee=/[@/?#]/g;function DM(e,t){let r=t?Nee:$ee;return r.lastIndex=0,e.replace(r,(n)=>Mee[n])}function zee(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(GS(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));if(t&&BM(s))r+=s;else r+="%"+i;n+=2;continue}}r+=e[n]}return r}function Bee(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(GS(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));if(i!=="."&&BM(i))t+=i;else t+="%"+o;r+=2;continue}}if(Aee(e[r]))t+=e[r];else t+=escape(e[r])}return t}function Lee(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(GS(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Dee(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let r=unescape(e.host);if(!zM(r)){let n=LM(r);if(n.isIPV6===!0)r=`[${n.escapedHost}]`;else r=DM(r,!1)}t.push(r)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}UM.exports={nonSimpleDomain:Iee,recomposeAuthority:Dee,reescapeHostDelimiters:DM,normalizePercentEncoding:zee,normalizePathEncoding:Bee,escapePreservingEscapes:Lee,removeDotSegments:Cee,isIPv4:zM,isUUID:Pee,normalizeIPv6:LM,stringArrayToHexStripped:VS}});var GM=ie(function(Ixe,HM){var{isUUID:Uee}=ZS(),Fee=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,jee=["http","https","ws","wss","urn","urn:uuid"];function qee(e){return jee.indexOf(e)!==-1}function WS(e){if(e.secure===!0)return!0;else if(e.secure===!1)return!1;else if(e.scheme)return e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S");else return!1}function FM(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function jM(e){let t=String(e.scheme).toLowerCase()==="https";if(e.port===(t?443:80)||e.port==="")e.port=void 0;if(!e.path)e.path="/";return e}function Hee(e){return e.secure=WS(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Gee(e){if(e.port===(WS(e)?443:80)||e.port==="")e.port=void 0;if(typeof e.secure==="boolean")e.scheme=e.secure?"wss":"ws",e.secure=void 0;if(e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function Vee(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Fee);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,i=KS(o);if(e.path=void 0,i)e=i.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function Zee(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,i=KS(o);if(i)e=i.serialize(e,t);let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function Wee(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Uee(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function Kee(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var qM={scheme:"http",domainHost:!0,parse:FM,serialize:jM},Yee={scheme:"https",domainHost:qM.domainHost,parse:FM,serialize:jM},r0={scheme:"ws",domainHost:!0,parse:Hee,serialize:Gee},Jee={scheme:"wss",domainHost:r0.domainHost,parse:r0.parse,serialize:r0.serialize},Qee={scheme:"urn",parse:Vee,serialize:Zee,skipNormalize:!0},Xee={scheme:"urn:uuid",parse:Wee,serialize:Kee,skipNormalize:!0},n0={http:qM,https:Yee,ws:r0,wss:Jee,urn:Qee,"urn:uuid":Xee};Object.setPrototypeOf(n0,null);function KS(e){return e&&(n0[e]||n0[e.toLowerCase()])||void 0}HM.exports={wsIsSecure:WS,SCHEMES:n0,isValidSchemeName:qee,getSchemeHandler:KS}});var JM=ie(function(kxe,o0){var{normalizeIPv6:ete,removeDotSegments:af,recomposeAuthority:tte,normalizePercentEncoding:rte,normalizePathEncoding:nte,escapePreservingEscapes:ote,reescapeHostDelimiters:ite,isIPv4:ste,nonSimpleDomain:ate}=ZS(),{SCHEMES:cte,getSchemeHandler:ZM}=GM();function ute(e,t){if(typeof e==="string")e=mte(e,t);else if(typeof e==="object")e=qu(cc(e,t),t);return e}function dte(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=WM(qu(e,n),qu(t,n),n,!0);return n.skipEscape=!0,cc(o,n)}function WM(e,t,r,n){let o={};if(!n)e=qu(cc(e,r),r),t=qu(cc(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=af(t.path||""),o.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=af(t.path||""),o.query=t.query;else{if(!t.path)if(o.path=e.path,t.query!==void 0)o.query=t.query;else o.query=e.query;else{if(t.path[0]==="/")o.path=af(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)o.path="/"+t.path;else if(!e.path)o.path=t.path;else o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;o.path=af(o.path)}o.query=t.query}o.userinfo=e.userinfo,o.host=e.host,o.port=e.port}o.scheme=e.scheme}return o.fragment=t.fragment,o}function lte(e,t,r){let n=VM(e,r),o=VM(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function cc(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[],i=ZM(n.scheme||r.scheme);if(i&&i.serialize)i.serialize(r,n);if(r.path!==void 0)if(!n.skipEscape){if(r.path=ote(r.path),r.scheme!==void 0)r.path=r.path.split("%3A").join(":")}else r.path=rte(r.path);if(n.reference!=="suffix"&&r.scheme)o.push(r.scheme,":");let s=tte(r);if(s!==void 0){if(n.reference!=="suffix")o.push("//");if(o.push(s),r.path&&r.path[0]!=="/")o.push("/")}if(r.path!==void 0){let a=r.path;if(!n.absolutePath&&(!i||!i.absolutePath))a=af(a);if(s===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);o.push(a)}if(r.query!==void 0)o.push("?",r.query);if(r.fragment!==void 0)o.push("#",r.fragment);return o.join("")}var pte=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function fte(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port==="number"&&(e.port<0||e.port>65535))return"URI port is malformed.";return}function KM(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let s=e.match(pte);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port))n.port=s[5];let a=fte(n,s);if(a!==void 0)n.error=n.error||a,o=!0;if(n.host)if(ste(n.host)===!1){let l=ete(n.host);n.host=l.host.toLowerCase(),i=l.isIPV6}else i=!0;if(n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path)n.reference="same-document";else if(n.scheme===void 0)n.reference="relative";else if(n.fragment===void 0)n.reference="absolute";else n.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==n.reference)n.error=n.error||"URI is not a "+r.reference+" reference.";let c=ZM(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)){if(n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&ate(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}}if(!c||c&&!c.skipNormalize){if(e.indexOf("%")!==-1){if(n.scheme!==void 0)n.scheme=unescape(n.scheme);if(n.host!==void 0)n.host=ite(unescape(n.host),i)}if(n.path)n.path=nte(n.path);if(n.fragment)try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}}if(c&&c.parse)c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function qu(e,t){return KM(e,t).parsed}function mte(e,t){return YM(e,t).normalized}function YM(e,t){let{parsed:r,malformedAuthorityOrPort:n}=KM(e,t);return{normalized:n?e:cc(r,t),malformedAuthorityOrPort:n}}function VM(e,t){if(typeof e==="string"){let{normalized:r,malformedAuthorityOrPort:n}=YM(e,t);return n?void 0:r}if(typeof e==="object")return cc(e,t)}var YS={SCHEMES:cte,normalize:ute,resolve:dte,resolveComponent:WM,equal:lte,serialize:cc,parse:qu};o0.exports=YS;o0.exports.default=YS;o0.exports.fastUri=YS});var e$=ie(function(XM){Object.defineProperty(XM,"__esModule",{value:!0});var QM=JM();QM.code='require("ajv/dist/runtime/uri").default';XM.default=QM});var c$=ie(function(Bi){Object.defineProperty(Bi,"__esModule",{value:!0});Bi.CodeGen=Bi.Name=Bi.nil=Bi.stringify=Bi.str=Bi._=Bi.KeywordCxt=void 0;var gte=nf();Object.defineProperty(Bi,"KeywordCxt",{enumerable:!0,get:function(){return gte.KeywordCxt}});var Hu=Ye();Object.defineProperty(Bi,"_",{enumerable:!0,get:function(){return Hu._}});Object.defineProperty(Bi,"str",{enumerable:!0,get:function(){return Hu.str}});Object.defineProperty(Bi,"stringify",{enumerable:!0,get:function(){return Hu.stringify}});Object.defineProperty(Bi,"nil",{enumerable:!0,get:function(){return Hu.nil}});Object.defineProperty(Bi,"Name",{enumerable:!0,get:function(){return Hu.Name}});Object.defineProperty(Bi,"CodeGen",{enumerable:!0,get:function(){return Hu.CodeGen}});var yte=Xg(),i$=of(),bte=IS(),uf=t0(),xte=Ye(),cf=ef(),i0=Xp(),QS=lt(),t$=$M(),_te=e$(),s$=(e,t)=>new RegExp(e,t);s$.code="new RegExp";var wte=["removeAdditional","useDefaults","coerceTypes"],Ste=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vte={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Tte={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},r$=200;function Ete(e){var t,r,n,o,i,s,a,c,d,l,p,m,h,y,x,_,w,A,S,v,P,k,O,N,j;let R=e.strict,K=(t=e.code)===null||t===void 0?void 0:t.optimize,Z=K===!0||K===void 0?1:K||0,re=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:s$,pe=(o=e.uriResolver)!==null&&o!==void 0?o:_te.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:R)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:R)!==null&&c!==void 0?c:!0,strictTypes:(l=(d=e.strictTypes)!==null&&d!==void 0?d:R)!==null&&l!==void 0?l:"log",strictTuples:(m=(p=e.strictTuples)!==null&&p!==void 0?p:R)!==null&&m!==void 0?m:"log",strictRequired:(y=(h=e.strictRequired)!==null&&h!==void 0?h:R)!==null&&y!==void 0?y:!1,code:e.code?{...e.code,optimize:Z,regExp:re}:{optimize:Z,regExp:re},loopRequired:(x=e.loopRequired)!==null&&x!==void 0?x:r$,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:r$,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(A=e.messages)!==null&&A!==void 0?A:!0,inlineRefs:(S=e.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(v=e.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(P=e.addUsedSchema)!==null&&P!==void 0?P:!0,validateSchema:(k=e.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(O=e.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(N=e.unicodeRegExp)!==null&&N!==void 0?N:!0,int32range:(j=e.int32range)!==null&&j!==void 0?j:!0,uriResolver:pe}}class s0{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Ete(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new xte.ValueScope({scope:{},prefixes:Ste,es5:t,lines:r}),this.logger=Ote(e.logger);let n=e.validateFormats;if(e.validateFormats=!1,this.RULES=bte.getRules(),n$.call(this,vte,e,"NOT SUPPORTED"),n$.call(this,Tte,e,"DEPRECATED","warn"),this._metaOpts=kte.call(this),e.formats)Ate.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)Ite.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);Pte.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,n=t$;if(r==="id")n={...t$},n.id=n.$id,delete n.$id;if(t&&e)this.addMetaSchema(n,n[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let n=r(t);if(!("$async"in r))this.errors=r.errors;return n}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(d,l){await o.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function o(d){if(d&&!this.getSchema(d))await n.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof i$.default))throw l;return s.call(this,l),await a.call(this,l.missingSchema),i.call(this,d)}}function s({missingSchema:d,missingRef:l}){if(this.refs[d])throw Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function a(d){let l=await c.call(this,d);if(!this.refs[d])await o.call(this,l.$schema);if(!this.refs[d])this.addSchema(l,d,t)}async function c(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=r(d))}finally{delete this._loading[d]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,n);return this}let o;if(typeof e==="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw Error(`schema ${i} must be string`)}return t=cf.normalizeId(t||o),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(r,e);if(!n&&t){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw Error(o)}return n}getSchema(e){let t;while(typeof(t=o$.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,n=new uf.SchemaEnv({schema:{},schemaId:r});if(t=uf.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=o$.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];if(r)r=cf.normalizeId(r),delete this.schemas[r],delete this.refs[r];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(Mte.call(this,r,t),!t)return QS.eachItem(r,(o)=>JS.call(this,o)),this;Nte.call(this,t);let n={...t,type:i0.getJSONTypes(t.type),schemaType:i0.getJSONTypes(t.schemaType)};return QS.eachItem(r,n.type.length===0?(o)=>JS.call(this,o,n):(o)=>n.type.forEach((i)=>JS.call(this,o,n,i))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let n=r.rules.findIndex((o)=>o.keyword===e);if(n>=0)r.rules.splice(n,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((n)=>`${r}${n.instancePath} ${n.message}`).reduce((n,o)=>n+t+o)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let o=n.split("/").slice(1),i=e;for(let s of o)i=i[s];for(let s in r){let a=r[s];if(typeof a!="object")continue;let{$data:c}=a.definition,d=i[s];if(c&&d)i[s]=a$(d)}}return e}_removeAllSchemas(e,t){for(let r in e){let n=e[r];if(!t||t.test(r)){if(typeof n=="string")delete e[r];else if(n&&!n.meta)this._cache.delete(n.schema),delete e[r]}}}_addSchema(e,t,r,n=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:s}=this.opts;if(typeof e=="object")i=e[s];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;r=cf.normalizeId(i||r);let c=cf.getSchemaRefs.call(this,e,r);if(a=new uf.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:r,localRefs:c}),this._cache.set(a.schema,a),o&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(n)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else uf.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{uf.compileSchema.call(this,e)}finally{this.opts=t}}}s0.ValidationError=yte.default;s0.MissingRefError=i$.default;Bi.default=s0;function n$(e,t,r,n="error"){for(let o in e){let i=o;if(i in t)this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function o$(e){return e=cf.normalizeId(e),this.schemas[e]||this.refs[e]}function Pte(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function Ate(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function Ite(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function kte(){let e={...this.opts};for(let t of wte)delete e[t];return e}var Rte={log(){},warn(){},error(){}};function Ote(e){if(e===!1)return Rte;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var Cte=/^[a-z_$][a-z0-9_$:-]*$/i;function Mte(e,t){let{RULES:r}=this;if(QS.eachItem(e,(n)=>{if(r.keywords[n])throw Error(`Keyword ${n} is already defined`);if(!Cte.test(n))throw Error(`Keyword ${n} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function JS(e,t,r){var n;let o=t===null||t===void 0?void 0:t.post;if(r&&o)throw Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(!s)s={type:r,rules:[]},i.rules.push(s);if(i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:i0.getJSONTypes(t.type),schemaType:i0.getJSONTypes(t.schemaType)}};if(t.before)$te.call(this,s,a,t.before);else s.rules.push(a);i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach((c)=>this.addKeyword(c))}function $te(e,t,r){let n=e.rules.findIndex((o)=>o.keyword===r);if(n>=0)e.rules.splice(n,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function Nte(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=a$(t);e.validateSchema=this.compile(t,!0)}var zte={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function a$(e){return{anyOf:[e,zte]}}});var d$=ie(function(u$){Object.defineProperty(u$,"__esModule",{value:!0});var Dte={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};u$.default=Dte});var g$=ie(function(m$){Object.defineProperty(m$,"__esModule",{value:!0});m$.callRef=m$.getValidate=void 0;var Fte=of(),l$=Gn(),pn=Ye(),Gu=Ni(),p$=t0(),a0=lt(),jte={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:d}=i;if((r==="#"||r==="#/")&&o===d.baseId)return p();let l=p$.resolveRef.call(c,d,o,r);if(l===void 0)throw new Fte.default(n.opts.uriResolver,o,r);if(l instanceof p$.SchemaEnv)return m(l);return h(l);function p(){if(i===d)return c0(e,s,i,i.$async);let y=t.scopeValue("root",{ref:d});return c0(e,pn._`${y}.validate`,d,d.$async)}function m(y){let x=f$(e,y);c0(e,x,y,y.$async)}function h(y){let x=t.scopeValue("schema",a.code.source===!0?{ref:y,code:pn.stringify(y)}:{ref:y}),_=t.name("valid"),w=e.subschema({schema:y,dataTypes:[],schemaPath:pn.nil,topSchemaRef:x,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function f$(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):pn._`${r.scopeValue("wrapper",{ref:t})}.validate`}m$.getValidate=f$;function c0(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,d=c.passContext?Gu.default.this:pn.nil;if(n)l();else p();function l(){if(!a.$async)throw Error("async schema referenced by sync schema");let y=o.let("valid");o.try(()=>{if(o.code(pn._`await ${l$.callValidateCode(e,t,d)}`),h(t),!s)o.assign(y,!0)},(x)=>{if(o.if(pn._`!(${x} instanceof ${i.ValidationError})`,()=>o.throw(x)),m(x),!s)o.assign(y,!1)}),e.ok(y)}function p(){e.result(l$.callValidateCode(e,t,d),()=>h(t),()=>m(t))}function m(y){let x=pn._`${y}.errors`;o.assign(Gu.default.vErrors,pn._`${Gu.default.vErrors} === null ? ${x} : ${Gu.default.vErrors}.concat(${x})`),o.assign(Gu.default.errors,pn._`${Gu.default.vErrors}.length`)}function h(y){var x;if(!i.opts.unevaluated)return;let _=(x=r===null||r===void 0?void 0:r.validate)===null||x===void 0?void 0:x.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps){if(_.props!==void 0)i.props=a0.mergeEvaluated.props(o,_.props,i.props)}else{let w=o.var("props",pn._`${y}.evaluated.props`);i.props=a0.mergeEvaluated.props(o,w,i.props,pn.Name)}if(i.items!==!0)if(_&&!_.dynamicItems){if(_.items!==void 0)i.items=a0.mergeEvaluated.items(o,_.items,i.items)}else{let w=o.var("items",pn._`${y}.evaluated.items`);i.items=a0.mergeEvaluated.items(o,w,i.items,pn.Name)}}}m$.callRef=c0;m$.default=jte});var b$=ie(function(y$){Object.defineProperty(y$,"__esModule",{value:!0});var Gte=d$(),Vte=g$(),Zte=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Gte.default,Vte.default];y$.default=Zte});var _$=ie(function(x$){Object.defineProperty(x$,"__esModule",{value:!0});var d0=Ye(),Ys=d0.operators,u0={maximum:{okStr:"<=",ok:Ys.LTE,fail:Ys.GT},minimum:{okStr:">=",ok:Ys.GTE,fail:Ys.LT},exclusiveMaximum:{okStr:"<",ok:Ys.LT,fail:Ys.GTE},exclusiveMinimum:{okStr:">",ok:Ys.GT,fail:Ys.LTE}},Kte={message:({keyword:e,schemaCode:t})=>d0.str`must be ${u0[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>d0._`{comparison: ${u0[e].okStr}, limit: ${t}}`},Yte={keyword:Object.keys(u0),type:"number",schemaType:"number",$data:!0,error:Kte,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data(d0._`${r} ${u0[t].fail} ${n} || isNaN(${r})`)}};x$.default=Yte});var S$=ie(function(w$){Object.defineProperty(w$,"__esModule",{value:!0});var df=Ye(),Qte={message:({schemaCode:e})=>df.str`must be multiple of ${e}`,params:({schemaCode:e})=>df._`{multipleOf: ${e}}`},Xte={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Qte,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?df._`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:df._`${s} !== parseInt(${s})`;e.fail$data(df._`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};w$.default=Xte});var E$=ie(function(T$){Object.defineProperty(T$,"__esModule",{value:!0});function v$(e){let t=e.length,r=0,n=0,o;while(n<t)if(r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t){if(o=e.charCodeAt(n),(o&64512)===56320)n++}return r}T$.default=v$;v$.code='require("ajv/dist/runtime/ucs2length").default'});var A$=ie(function(P$){Object.defineProperty(P$,"__esModule",{value:!0});var uc=Ye(),rre=lt(),nre=E$(),ore={message({keyword:e,schemaCode:t}){return uc.str`must NOT have ${e==="maxLength"?"more":"fewer"} than ${t} characters`},params:({schemaCode:e})=>uc._`{limit: ${e}}`},ire={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ore,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?uc.operators.GT:uc.operators.LT,s=o.opts.unicode===!1?uc._`${r}.length`:uc._`${rre.useFunc(e.gen,nre.default)}(${r})`;e.fail$data(uc._`${s} ${i} ${n}`)}};P$.default=ire});var k$=ie(function(I$){Object.defineProperty(I$,"__esModule",{value:!0});var are=Gn(),cre=lt(),Vu=Ye(),ure={message:({schemaCode:e})=>Vu.str`must match pattern "${e}"`,params:({schemaCode:e})=>Vu._`{pattern: ${e}}`},dre={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ure,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,d=c.code==="new RegExp"?Vu._`new RegExp`:cre.useFunc(t,c),l=t.let("valid");t.try(()=>t.assign(l,Vu._`${d}(${i}, ${a}).test(${r})`),()=>t.assign(l,!1)),e.fail$data(Vu._`!${l}`)}else{let c=are.usePattern(e,o);e.fail$data(Vu._`!${c}.test(${r})`)}}};I$.default=dre});var O$=ie(function(R$){Object.defineProperty(R$,"__esModule",{value:!0});var lf=Ye(),pre={message({keyword:e,schemaCode:t}){return lf.str`must NOT have ${e==="maxProperties"?"more":"fewer"} than ${t} properties`},params:({schemaCode:e})=>lf._`{limit: ${e}}`},fre={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:pre,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?lf.operators.GT:lf.operators.LT;e.fail$data(lf._`Object.keys(${r}).length ${o} ${n}`)}};R$.default=fre});var M$=ie(function(C$){Object.defineProperty(C$,"__esModule",{value:!0});var ff=Gn(),pf=Ye(),hre=lt(),gre={message:({params:{missingProperty:e}})=>pf.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>pf._`{missingProperty: ${e}}`},yre={keyword:"required",type:"object",schemaType:"array",$data:!0,error:gre,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors)d();else l();if(a.strictRequired){let h=e.parentSchema.properties,{definedProperties:y}=e.it;for(let x of r)if((h===null||h===void 0?void 0:h[x])===void 0&&!y.has(x)){let _=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${x}" is not defined at "${_}" (strictRequired)`;hre.checkStrictMode(s,w,s.opts.strictRequired)}}function d(){if(c||i)e.block$data(pf.nil,p);else for(let h of r)ff.checkReportMissingProp(e,h)}function l(){let h=t.let("missing");if(c||i){let y=t.let("valid",!0);e.block$data(y,()=>m(h,y)),e.ok(y)}else t.if(ff.checkMissingProp(e,r,h)),ff.reportMissingProp(e,h),t.else()}function p(){t.forOf("prop",n,(h)=>{e.setParams({missingProperty:h}),t.if(ff.noPropertyInData(t,o,h,a.ownProperties),()=>e.error())})}function m(h,y){e.setParams({missingProperty:h}),t.forOf(h,n,()=>{t.assign(y,ff.propertyInData(t,o,h,a.ownProperties)),t.if(pf.not(y),()=>{e.error(),t.break()})},pf.nil)}}};C$.default=yre});var N$=ie(function($$){Object.defineProperty($$,"__esModule",{value:!0});var mf=Ye(),xre={message({keyword:e,schemaCode:t}){return mf.str`must NOT have ${e==="maxItems"?"more":"fewer"} than ${t} items`},params:({schemaCode:e})=>mf._`{limit: ${e}}`},_re={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:xre,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?mf.operators.GT:mf.operators.LT;e.fail$data(mf._`${r}.length ${o} ${n}`)}};$$.default=_re});var l0=ie(function(B$){Object.defineProperty(B$,"__esModule",{value:!0});var z$=zS();z$.code='require("ajv/dist/runtime/equal").default';B$.default=z$});var D$=ie(function(L$){Object.defineProperty(L$,"__esModule",{value:!0});var XS=Xp(),Rr=Ye(),vre=lt(),Tre=l0(),Ere={message:({params:{i:e,j:t}})=>Rr.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>Rr._`{i: ${e}, j: ${t}}`},Pre={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Ere,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),d=i.items?XS.getSchemaTypes(i.items):[];e.block$data(c,l,Rr._`${s} === false`),e.ok(c);function l(){let y=t.let("i",Rr._`${r}.length`),x=t.let("j");e.setParams({i:y,j:x}),t.assign(c,!0),t.if(Rr._`${y} > 1`,()=>(p()?m:h)(y,x))}function p(){return d.length>0&&!d.some((y)=>y==="object"||y==="array")}function m(y,x){let _=t.name("item"),w=XS.checkDataTypes(d,_,a.opts.strictNumbers,XS.DataType.Wrong),A=t.const("indices",Rr._`{}`);t.for(Rr._`;${y}--;`,()=>{if(t.let(_,Rr._`${r}[${y}]`),t.if(w,Rr._`continue`),d.length>1)t.if(Rr._`typeof ${_} == "string"`,Rr._`${_} += "_"`);t.if(Rr._`typeof ${A}[${_}] == "number"`,()=>{t.assign(x,Rr._`${A}[${_}]`),e.error(),t.assign(c,!1).break()}).code(Rr._`${A}[${_}] = ${y}`)})}function h(y,x){let _=vre.useFunc(t,Tre.default),w=t.name("outer");t.label(w).for(Rr._`;${y}--;`,()=>t.for(Rr._`${x} = ${y}; ${x}--;`,()=>t.if(Rr._`${_}(${r}[${y}], ${r}[${x}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};L$.default=Pre});var F$=ie(function(U$){Object.defineProperty(U$,"__esModule",{value:!0});var ev=Ye(),Ire=lt(),kre=l0(),Rre={message:"must be equal to constant",params:({schemaCode:e})=>ev._`{allowedValue: ${e}}`},Ore={keyword:"const",$data:!0,error:Rre,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;if(n||i&&typeof i=="object")e.fail$data(ev._`!${Ire.useFunc(t,kre.default)}(${r}, ${o})`);else e.fail(ev._`${i} !== ${r}`)}};U$.default=Ore});var q$=ie(function(j$){Object.defineProperty(j$,"__esModule",{value:!0});var hf=Ye(),Mre=lt(),$re=l0(),Nre={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>hf._`{allowedValues: ${e}}`},zre={keyword:"enum",schemaType:"array",$data:!0,error:Nre,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,d=()=>c!==null&&c!==void 0?c:c=Mre.useFunc(t,$re.default),l;if(a||n)l=t.let("valid"),e.block$data(l,p);else{if(!Array.isArray(o))throw Error("ajv implementation error");let h=t.const("vSchema",i);l=hf.or(...o.map((y,x)=>m(h,x)))}e.pass(l);function p(){t.assign(l,!1),t.forOf("v",i,(h)=>t.if(hf._`${d()}(${r}, ${h})`,()=>t.assign(l,!0).break()))}function m(h,y){let x=o[y];return typeof x==="object"&&x!==null?hf._`${d()}(${r}, ${h}[${y}])`:hf._`${r} === ${x}`}}};j$.default=zre});var G$=ie(function(H$){Object.defineProperty(H$,"__esModule",{value:!0});var Lre=_$(),Dre=S$(),Ure=A$(),Fre=k$(),jre=O$(),qre=M$(),Hre=N$(),Gre=D$(),Vre=F$(),Zre=q$(),Wre=[Lre.default,Dre.default,Ure.default,Fre.default,jre.default,qre.default,Hre.default,Gre.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Vre.default,Zre.default];H$.default=Wre});var rv=ie(function(Z$){Object.defineProperty(Z$,"__esModule",{value:!0});Z$.validateAdditionalItems=void 0;var dc=Ye(),tv=lt(),Yre={message:({params:{len:e}})=>dc.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>dc._`{limit: ${e}}`},Jre={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Yre,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){tv.checkStrictMode(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}V$(e,n)}};function V$(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",dc._`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass(dc._`${a} <= ${t.length}`);else if(typeof n=="object"&&!tv.alwaysValidSchema(s,n)){let d=r.var("valid",dc._`${a} <= ${t.length}`);r.if(dc.not(d),()=>c(d)),e.ok(d)}function c(d){r.forRange("i",t.length,a,(l)=>{if(e.subschema({keyword:i,dataProp:l,dataPropType:tv.Type.Num},d),!s.allErrors)r.if(dc.not(d),()=>r.break())})}}Z$.validateAdditionalItems=V$;Z$.default=Jre});var nv=ie(function(J$){Object.defineProperty(J$,"__esModule",{value:!0});J$.validateTuple=void 0;var K$=Ye(),p0=lt(),Xre=Gn(),ene={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Y$(e,"additionalItems",t);if(r.items=!0,p0.alwaysValidSchema(r,t))return;e.ok(Xre.validateArray(e))}};function Y$(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;if(l(o),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=p0.mergeEvaluated.items(n,r.length,a.items);let c=n.name("valid"),d=n.const("len",K$._`${i}.length`);r.forEach((p,m)=>{if(p0.alwaysValidSchema(a,p))return;n.if(K$._`${d} > ${m}`,()=>e.subschema({keyword:s,schemaProp:m,dataProp:m},c)),e.ok(c)});function l(p){let{opts:m,errSchemaPath:h}=a,y=r.length,x=y===p.minItems&&(y===p.maxItems||p[t]===!1);if(m.strictTuples&&!x){let _=`"${s}" is ${y}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;p0.checkStrictMode(a,_,m.strictTuples)}}}J$.validateTuple=Y$;J$.default=ene});var eN=ie(function(X$){Object.defineProperty(X$,"__esModule",{value:!0});var rne=nv(),nne={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>rne.validateTuple(e,"items")};X$.default=nne});var nN=ie(function(rN){Object.defineProperty(rN,"__esModule",{value:!0});var tN=Ye(),ine=lt(),sne=Gn(),ane=rv(),cne={message:({params:{len:e}})=>tN.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>tN._`{limit: ${e}}`},une={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:cne,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;if(n.items=!0,ine.alwaysValidSchema(n,t))return;if(o)ane.validateAdditionalItems(e,o);else e.ok(sne.validateArray(e))}};rN.default=une});var iN=ie(function(oN){Object.defineProperty(oN,"__esModule",{value:!0});var Vn=Ye(),f0=lt(),lne={message:({params:{min:e,max:t}})=>t===void 0?Vn.str`must contain at least ${e} valid item(s)`:Vn.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Vn._`{minContains: ${e}}`:Vn._`{minContains: ${e}, maxContains: ${t}}`},pne={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lne,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:d}=n;if(i.opts.next)s=c===void 0?1:c,a=d;else s=1;let l=t.const("len",Vn._`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){f0.checkStrictMode(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){f0.checkStrictMode(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if(f0.alwaysValidSchema(i,r)){let x=Vn._`${l} >= ${s}`;if(a!==void 0)x=Vn._`${x} && ${l} <= ${a}`;e.pass(x);return}i.items=!0;let p=t.name("valid");if(a===void 0&&s===1)h(p,()=>t.if(p,()=>t.break()));else if(s===0){if(t.let(p,!0),a!==void 0)t.if(Vn._`${o}.length > 0`,m)}else t.let(p,!1),m();e.result(p,()=>e.reset());function m(){let x=t.name("_valid"),_=t.let("count",0);h(x,()=>t.if(x,()=>y(_)))}function h(x,_){t.forRange("i",0,l,(w)=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:f0.Type.Num,compositeRule:!0},x),_()})}function y(x){if(t.code(Vn._`${x}++`),a===void 0)t.if(Vn._`${x} >= ${s}`,()=>t.assign(p,!0).break());else if(t.if(Vn._`${x} > ${a}`,()=>t.assign(p,!1).break()),s===1)t.assign(p,!0);else t.if(Vn._`${x} >= ${s}`,()=>t.assign(p,!0))}}};oN.default=pne});var lN=ie(function(cN){Object.defineProperty(cN,"__esModule",{value:!0});cN.validateSchemaDeps=cN.validatePropertyDeps=cN.error=void 0;var ov=Ye(),mne=lt(),gf=Gn();cN.error={message:({params:{property:e,depsCount:t,deps:r}})=>ov.str`must have ${t===1?"property":"properties"} ${r} when property ${e} is present`,params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>ov._`{property: ${e},
|
|
24
24
|
missingProperty: ${n},
|
|
25
25
|
depsCount: ${t},
|
|
26
26
|
deps: ${r}}`};var hne={keyword:"dependencies",type:"object",schemaType:"object",error:cN.error,code(e){let[t,r]=gne(e);sN(e,t),aN(e,r)}};function gne({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function sN(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=gf.propertyInData(r,n,s,o.opts.ownProperties);if(e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors)r.if(c,()=>{for(let d of a)gf.checkReportMissingProp(e,d)});else r.if(ov._`${c} && (${gf.checkMissingProp(e,a,i)})`),gf.reportMissingProp(e,i),r.else()}}cN.validatePropertyDeps=sN;function aN(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t){if(mne.alwaysValidSchema(i,t[a]))continue;r.if(gf.propertyInData(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s)}}cN.validateSchemaDeps=aN;cN.default=hne});var mN=ie(function(fN){Object.defineProperty(fN,"__esModule",{value:!0});var pN=Ye(),xne=lt(),_ne={message:"property name must be valid",params:({params:e})=>pN._`{propertyName: ${e.propertyName}}`},wne={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:_ne,code(e){let{gen:t,schema:r,data:n,it:o}=e;if(xne.alwaysValidSchema(o,r))return;let i=t.name("valid");t.forIn("key",n,(s)=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if(pN.not(i),()=>{if(e.error(!0),!o.allErrors)t.break()})}),e.ok(i)}};fN.default=wne});var iv=ie(function(hN){Object.defineProperty(hN,"__esModule",{value:!0});var m0=Gn(),yo=Ye(),vne=Ni(),h0=lt(),Tne={message:"must NOT have additional properties",params:({params:e})=>yo._`{additionalProperty: ${e.additionalProperty}}`},Ene={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Tne,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&h0.alwaysValidSchema(s,r))return;let d=m0.allSchemaProperties(n.properties),l=m0.allSchemaProperties(n.patternProperties);p(),e.ok(yo._`${i} === ${vne.default.errors}`);function p(){t.forIn("key",o,(_)=>{if(!d.length&&!l.length)y(_);else t.if(m(_),()=>y(_))})}function m(_){let w;if(d.length>8){let A=h0.schemaRefOrVal(s,n.properties,"properties");w=m0.isOwnProperty(t,A,_)}else if(d.length)w=yo.or(...d.map((A)=>yo._`${_} === ${A}`));else w=yo.nil;if(l.length)w=yo.or(w,...l.map((A)=>yo._`${m0.usePattern(e,A)}.test(${_})`));return yo.not(w)}function h(_){t.code(yo._`delete ${o}[${_}]`)}function y(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(_);return}if(r===!1){if(e.setParams({additionalProperty:_}),e.error(),!a)t.break();return}if(typeof r=="object"&&!h0.alwaysValidSchema(s,r)){let w=t.name("valid");if(c.removeAdditional==="failing")x(_,w,!1),t.if(yo.not(w),()=>{e.reset(),h(_)});else if(x(_,w),!a)t.if(yo.not(w),()=>t.break())}}function x(_,w,A){let S={keyword:"additionalProperties",dataProp:_,dataPropType:h0.Type.Str};if(A===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(S,w)}}};hN.default=Ene});var xN=ie(function(bN){Object.defineProperty(bN,"__esModule",{value:!0});var Ane=nf(),yN=Gn(),sv=lt(),gN=iv(),Ine={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;if(i.opts.removeAdditional==="all"&&n.additionalProperties===void 0)gN.default.code(new Ane.KeywordCxt(i,gN.default,"additionalProperties"));let s=yN.allSchemaProperties(r);for(let p of s)i.definedProperties.add(p);if(i.opts.unevaluated&&s.length&&i.props!==!0)i.props=sv.mergeEvaluated.props(t,sv.toHash(s),i.props);let a=s.filter((p)=>!sv.alwaysValidSchema(i,r[p]));if(a.length===0)return;let c=t.name("valid");for(let p of a){if(d(p))l(p);else{if(t.if(yN.propertyInData(t,o,p,i.opts.ownProperties)),l(p),!i.allErrors)t.else().var(c,!0);t.endIf()}e.it.definedProperties.add(p),e.ok(c)}function d(p){return i.opts.useDefaults&&!i.compositeRule&&r[p].default!==void 0}function l(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};bN.default=Ine});var TN=ie(function(vN){Object.defineProperty(vN,"__esModule",{value:!0});var _N=Gn(),g0=Ye(),wN=lt(),SN=lt(),Rne={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=_N.allSchemaProperties(r),c=a.filter((x)=>wN.alwaysValidSchema(i,r[x]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let d=s.strictSchema&&!s.allowMatchingProperties&&o.properties,l=t.name("valid");if(i.props!==!0&&!(i.props instanceof g0.Name))i.props=SN.evaluatedPropsToName(t,i.props);let{props:p}=i;m();function m(){for(let x of a){if(d)h(x);if(i.allErrors)y(x);else t.var(l,!0),y(x),t.if(l)}}function h(x){for(let _ in d)if(new RegExp(x).test(_))wN.checkStrictMode(i,`property ${_} matches pattern ${x} (use allowMatchingProperties)`)}function y(x){t.forIn("key",n,(_)=>{t.if(g0._`${_N.usePattern(e,x)}.test(${_})`,()=>{let w=c.includes(x);if(!w)e.subschema({keyword:"patternProperties",schemaProp:x,dataProp:_,dataPropType:SN.Type.Str},l);if(i.opts.unevaluated&&p!==!0)t.assign(g0._`${p}[${_}]`,!0);else if(!w&&!i.allErrors)t.if(g0.not(l),()=>t.break())})})}}};vN.default=Rne});var PN=ie(function(EN){Object.defineProperty(EN,"__esModule",{value:!0});var Cne=lt(),Mne={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if(Cne.alwaysValidSchema(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};EN.default=Mne});var IN=ie(function(AN){Object.defineProperty(AN,"__esModule",{value:!0});var Nne=Gn(),zne={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Nne.validateUnion,error:{message:"must match a schema in anyOf"}};AN.default=zne});var RN=ie(function(kN){Object.defineProperty(kN,"__esModule",{value:!0});var y0=Ye(),Lne=lt(),Dne={message:"must match exactly one schema in oneOf",params:({params:e})=>y0._`{passingSchemas: ${e.passing}}`},Une={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Dne,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(d),e.result(s,()=>e.reset(),()=>e.error(!0));function d(){i.forEach((l,p)=>{let m;if(Lne.alwaysValidSchema(o,l))t.var(c,!0);else m=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c);if(p>0)t.if(y0._`${c} && ${s}`).assign(s,!1).assign(a,y0._`[${a}, ${p}]`).else();t.if(c,()=>{if(t.assign(s,!0),t.assign(a,p),m)e.mergeEvaluated(m,y0.Name)})})}}};kN.default=Une});var CN=ie(function(ON){Object.defineProperty(ON,"__esModule",{value:!0});var jne=lt(),qne={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let o=t.name("valid");r.forEach((i,s)=>{if(jne.alwaysValidSchema(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};ON.default=qne});var zN=ie(function(NN){Object.defineProperty(NN,"__esModule",{value:!0});var b0=Ye(),$N=lt(),Gne={message:({params:e})=>b0.str`must match "${e.ifClause}" schema`,params:({params:e})=>b0._`{failingKeyword: ${e.ifClause}}`},Vne={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Gne,code(e){let{gen:t,parentSchema:r,it:n}=e;if(r.then===void 0&&r.else===void 0)$N.checkStrictMode(n,'"if" without "then" and "else" is ignored');let o=MN(n,"then"),i=MN(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,d("then",l),d("else",l))}else if(o)t.if(a,d("then"));else t.if(b0.not(a),d("else"));e.pass(s,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function d(l,p){return()=>{let m=e.subschema({keyword:l},a);if(t.assign(s,a),e.mergeValidEvaluated(m,s),p)t.assign(p,b0._`${l}`);else e.setParams({ifClause:l})}}}};function MN(e,t){let r=e.schema[t];return r!==void 0&&!$N.alwaysValidSchema(e,r)}NN.default=Vne});var LN=ie(function(BN){Object.defineProperty(BN,"__esModule",{value:!0});var Wne=lt(),Kne={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)Wne.checkStrictMode(r,`"${e}" without "if" is ignored`)}};BN.default=Kne});var UN=ie(function(DN){Object.defineProperty(DN,"__esModule",{value:!0});var Jne=rv(),Qne=eN(),Xne=nv(),eoe=nN(),toe=iN(),roe=lN(),noe=mN(),ooe=iv(),ioe=xN(),soe=TN(),aoe=PN(),coe=IN(),uoe=RN(),doe=CN(),loe=zN(),poe=LN();function foe(e=!1){let t=[aoe.default,coe.default,uoe.default,doe.default,loe.default,poe.default,noe.default,ooe.default,roe.default,ioe.default,soe.default];if(e)t.push(Qne.default,eoe.default);else t.push(Jne.default,Xne.default);return t.push(toe.default),t}DN.default=foe});var jN=ie(function(FN){Object.defineProperty(FN,"__esModule",{value:!0});var nr=Ye(),hoe={message:({schemaCode:e})=>nr.str`must match format "${e}"`,params:({schemaCode:e})=>nr._`{format: ${e}}`},goe={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:hoe,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:d,schemaEnv:l,self:p}=a;if(!c.validateFormats)return;if(o)m();else h();function m(){let y=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),x=r.const("fDef",nr._`${y}[${s}]`),_=r.let("fType"),w=r.let("format");r.if(nr._`typeof ${x} == "object" && !(${x} instanceof RegExp)`,()=>r.assign(_,nr._`${x}.type || "string"`).assign(w,nr._`${x}.validate`),()=>r.assign(_,nr._`"string"`).assign(w,x)),e.fail$data(nr.or(A(),S()));function A(){if(c.strictSchema===!1)return nr.nil;return nr._`${s} && !${w}`}function S(){let v=l.$async?nr._`(${x}.async ? await ${w}(${n}) : ${w}(${n}))`:nr._`${w}(${n})`,P=nr._`(typeof ${w} == "function" ? ${v} : ${w}.test(${n}))`;return nr._`${w} && ${w} !== true && ${_} === ${t} && !${P}`}}function h(){let y=p.formats[i];if(!y){A();return}if(y===!0)return;let[x,_,w]=S(y);if(x===t)e.pass(v());function A(){if(c.strictSchema===!1){p.logger.warn(P());return}throw Error(P());function P(){return`unknown format "${i}" ignored in schema at path "${d}"`}}function S(P){let k=P instanceof RegExp?nr.regexpCode(P):c.code.formats?nr._`${c.code.formats}${nr.getProperty(i)}`:void 0,O=r.scopeValue("formats",{key:i,ref:P,code:k});if(typeof P=="object"&&!(P instanceof RegExp))return[P.type||"string",P.validate,nr._`${O}.validate`];return["string",P,O]}function v(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!l.$async)throw Error("async format in sync schema");return nr._`await ${w}(${n})`}return typeof _=="function"?nr._`${w}(${n})`:nr._`${w}.test(${n})`}}}};FN.default=goe});var HN=ie(function(qN){Object.defineProperty(qN,"__esModule",{value:!0});var boe=jN(),xoe=[boe.default];qN.default=xoe});var ZN=ie(function(GN){Object.defineProperty(GN,"__esModule",{value:!0});GN.contentVocabulary=GN.metadataVocabulary=void 0;GN.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];GN.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var YN=ie(function(KN){Object.defineProperty(KN,"__esModule",{value:!0});var Soe=b$(),voe=G$(),Toe=UN(),Eoe=HN(),WN=ZN(),Poe=[Soe.default,voe.default,(0,Toe.default)(),Eoe.default,WN.metadataVocabulary,WN.contentVocabulary];KN.default=Poe});var e4=ie(function(QN){Object.defineProperty(QN,"__esModule",{value:!0});QN.DiscrError=void 0;var JN;(function(e){e.Tag="tag",e.Mapping="mapping"})(JN||(QN.DiscrError=JN={}))});var n4=ie(function(r4){Object.defineProperty(r4,"__esModule",{value:!0});var Zu=Ye(),av=e4(),t4=t0(),Ioe=of(),koe=lt(),Roe={message:({params:{discrError:e,tagName:t}})=>e===av.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Zu._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},Ooe={keyword:"discriminator",type:"object",schemaType:"object",error:Roe,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(n.mapping)throw Error("discriminator: mapping is not supported");if(!s)throw Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),d=t.const("tag",Zu._`${r}${Zu.getProperty(a)}`);t.if(Zu._`typeof ${d} == "string"`,()=>l(),()=>e.error(!1,{discrError:av.DiscrError.Tag,tag:d,tagName:a})),e.ok(c);function l(){let h=m();t.if(!1);for(let y in h)t.elseIf(Zu._`${d} === ${y}`),t.assign(c,p(h[y]));t.else(),e.error(!1,{discrError:av.DiscrError.Mapping,tag:d,tagName:a}),t.endIf()}function p(h){let y=t.name("valid"),x=e.subschema({keyword:"oneOf",schemaProp:h},y);return e.mergeEvaluated(x,Zu.Name),y}function m(){var h;let y={},x=w(o),_=!0;for(let v=0;v<s.length;v++){let P=s[v];if((P===null||P===void 0?void 0:P.$ref)&&!koe.schemaHasRulesButRef(P,i.self.RULES)){let O=P.$ref;if(P=t4.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,O),P instanceof t4.SchemaEnv)P=P.schema;if(P===void 0)throw new Ioe.default(i.opts.uriResolver,i.baseId,O)}let k=(h=P===null||P===void 0?void 0:P.properties)===null||h===void 0?void 0:h[a];if(typeof k!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(x||w(P)),A(k,v)}if(!_)throw Error(`discriminator: "${a}" must be required`);return y;function w({required:v}){return Array.isArray(v)&&v.includes(a)}function A(v,P){if(v.const)S(v.const,P);else if(v.enum)for(let k of v.enum)S(k,P);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(v,P){if(typeof v!="string"||v in y)throw Error(`discriminator: "${a}" values must be unique strings`);y[v]=P}}}};r4.default=Ooe});var o4=ie(function(v1e,Moe){Moe.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var uv=ie(function(fn,cv){Object.defineProperty(fn,"__esModule",{value:!0});fn.MissingRefError=fn.ValidationError=fn.CodeGen=fn.Name=fn.nil=fn.stringify=fn.str=fn._=fn.KeywordCxt=fn.Ajv=void 0;var $oe=c$(),Noe=YN(),zoe=n4(),i4=o4(),Boe=["/properties"],x0="http://json-schema.org/draft-07/schema";class yf extends $oe.default{_addVocabularies(){if(super._addVocabularies(),Noe.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(zoe.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(i4,Boe):i4;this.addMetaSchema(e,x0,!1),this.refs["http://json-schema.org/schema"]=x0}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(x0)?x0:void 0)}}fn.Ajv=yf;cv.exports=fn=yf;cv.exports.Ajv=yf;Object.defineProperty(fn,"__esModule",{value:!0});fn.default=yf;var Loe=nf();Object.defineProperty(fn,"KeywordCxt",{enumerable:!0,get:function(){return Loe.KeywordCxt}});var Wu=Ye();Object.defineProperty(fn,"_",{enumerable:!0,get:function(){return Wu._}});Object.defineProperty(fn,"str",{enumerable:!0,get:function(){return Wu.str}});Object.defineProperty(fn,"stringify",{enumerable:!0,get:function(){return Wu.stringify}});Object.defineProperty(fn,"nil",{enumerable:!0,get:function(){return Wu.nil}});Object.defineProperty(fn,"Name",{enumerable:!0,get:function(){return Wu.Name}});Object.defineProperty(fn,"CodeGen",{enumerable:!0,get:function(){return Wu.CodeGen}});var Doe=Xg();Object.defineProperty(fn,"ValidationError",{enumerable:!0,get:function(){return Doe.default}});var Uoe=of();Object.defineProperty(fn,"MissingRefError",{enumerable:!0,get:function(){return Uoe.default}})});var h4=ie(function(f4){Object.defineProperty(f4,"__esModule",{value:!0});f4.formatNames=f4.fastFormats=f4.fullFormats=void 0;function Zo(e,t){return{validate:e,compare:t}}f4.fullFormats={date:Zo(u4,fv),time:Zo(lv(!0),mv),"date-time":Zo(s4(!0),l4),"iso-time":Zo(lv(),d4),"iso-date-time":Zo(s4(),p4),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Woe,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:tie,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:Koe,int32:{type:"number",validate:Qoe},int64:{type:"number",validate:Xoe},float:{type:"number",validate:c4},double:{type:"number",validate:c4},password:!0,binary:!0};f4.fastFormats={...f4.fullFormats,date:Zo(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,fv),time:Zo(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,mv),"date-time":Zo(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l4),"iso-time":Zo(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,d4),"iso-date-time":Zo(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,p4),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};f4.formatNames=Object.keys(f4.fullFormats);function qoe(e){return e%4===0&&(e%100!==0||e%400===0)}var Hoe=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Goe=[0,31,28,31,30,31,30,31,31,30,31,30,31];function u4(e){let t=Hoe.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&qoe(r)?29:Goe[n])}function fv(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var dv=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function lv(e){return function(r){let n=dv.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,d=+(n[6]||0),l=+(n[7]||0);if(d>23||l>59||e&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let p=i-l*c,m=o-d*c-(p<0?1:0);return(m===23||m===-1)&&(p===59||p===-1)&&s<61}}function mv(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(!(r&&n))return;return r-n}function d4(e,t){if(!(e&&t))return;let r=dv.exec(e),n=dv.exec(t);if(!(r&&n))return;if(e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t)return 1;if(e<t)return-1;return 0}var pv=/t|\s/i;function s4(e){let t=lv(e);return function(n){let o=n.split(pv);return o.length===2&&u4(o[0])&&t(o[1])}}function l4(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(!(r&&n))return;return r-n}function p4(e,t){if(!(e&&t))return;let[r,n]=e.split(pv),[o,i]=t.split(pv),s=fv(r,o);if(s===void 0)return;return s||mv(n,i)}var Voe=/\/|:/,Zoe=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Woe(e){return Voe.test(e)&&Zoe.test(e)}var a4=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Koe(e){return a4.lastIndex=0,a4.test(e)}var Yoe=-2147483648,Joe=2147483647;function Qoe(e){return Number.isInteger(e)&&e<=Joe&&e>=Yoe}function Xoe(e){return Number.isInteger(e)}function c4(){return!0}var eie=/[^\\]\\Z/;function tie(e){if(eie.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var y4=ie(function(g4){Object.defineProperty(g4,"__esModule",{value:!0});g4.formatLimitDefinition=void 0;var nie=uv(),bo=Ye(),Js=bo.operators,_0={formatMaximum:{okStr:"<=",ok:Js.LTE,fail:Js.GT},formatMinimum:{okStr:">=",ok:Js.GTE,fail:Js.LT},formatExclusiveMaximum:{okStr:"<",ok:Js.LT,fail:Js.GTE},formatExclusiveMinimum:{okStr:">",ok:Js.GT,fail:Js.LTE}},oie={message:({keyword:e,schemaCode:t})=>bo.str`should be ${_0[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>bo._`{comparison: ${_0[e].okStr}, limit: ${t}}`};g4.formatLimitDefinition={keyword:Object.keys(_0),type:"string",schemaType:"string",$data:!0,error:oie,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new nie.KeywordCxt(i,a.RULES.all.format.definition,"format");if(c.$data)d();else l();function d(){let m=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),h=t.const("fmt",bo._`${m}[${c.schemaCode}]`);e.fail$data(bo.or(bo._`typeof ${h} != "object"`,bo._`${h} instanceof RegExp`,bo._`typeof ${h}.compare != "function"`,p(h)))}function l(){let m=c.schema,h=a.formats[m];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw Error(`"${o}": format "${m}" does not define "compare" function`);let y=t.scopeValue("formats",{key:m,ref:h,code:s.code.formats?bo._`${s.code.formats}${bo.getProperty(m)}`:void 0});e.fail$data(p(y))}function p(m){return bo._`${m}.compare(${r}, ${n}) ${_0[o].fail} 0`}},dependencies:["format"]};var iie=(e)=>(e.addKeyword(g4.formatLimitDefinition),e);g4.default=iie});var w4=ie(function(bf,_4){Object.defineProperty(bf,"__esModule",{value:!0});var Ku=h4(),aie=y4(),yv=Ye(),b4=new yv.Name("fullFormats"),cie=new yv.Name("fastFormats"),bv=(e,t={keywords:!0})=>{if(Array.isArray(t))return x4(e,t,Ku.fullFormats,b4),e;let[r,n]=t.mode==="fast"?[Ku.fastFormats,cie]:[Ku.fullFormats,b4],o=t.formats||Ku.formatNames;if(x4(e,o,r,n),t.keywords)(0,aie.default)(e);return e};bv.get=(e,t="full")=>{let n=(t==="fast"?Ku.fastFormats:Ku.fullFormats)[e];if(!n)throw Error(`Unknown format "${e}"`);return n};function x4(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=yv._`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}_4.exports=bf=bv;Object.defineProperty(bf,"__esModule",{value:!0});bf.default=bv});import*as Di from"node:crypto";var fc;var J4=V(()=>{fc=Di&&typeof Di==="object"&&"webcrypto"in Di?Di.webcrypto:Di&&typeof Di==="object"&&("randomBytes"in Di)?Di:void 0});function Eie(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function P0(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function mc(e,...t){if(!Eie(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Q4(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");P0(e.outputLen),P0(e.blockLen)}function Yu(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function X4(e,t){mc(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function Ui(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function A0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function _o(e,t){return e<<32-t|e>>>t}function e8(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function wf(e){if(typeof e==="string")e=e8(e);return mc(e),e}function Mv(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];mc(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}class Sf{}function $v(e){let t=(n)=>e().update(wf(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function I0(e=32){if(fc&&typeof fc.getRandomValues==="function")return fc.getRandomValues(new Uint8Array(e));if(fc&&typeof fc.randomBytes==="function")return Uint8Array.from(fc.randomBytes(e));throw Error("crypto.getRandomValues must be defined")}var hc=V(()=>{J4();/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */});function Pie(e,t,r,n){if(typeof e.setBigUint64==="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,d=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+d,a,n)}function t8(e,t,r){return e&t^~e&r}function r8(e,t,r){return e&t^e&r^t&r}var k0,Fi,Or;var n8=V(()=>{hc();k0=class k0 extends Sf{constructor(e,t,r,n){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=A0(this.buffer)}update(e){Yu(this),e=wf(e),mc(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){let a=A0(e);for(;n<=o-i;i+=n)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yu(this),X4(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,Ui(this.buffer.subarray(i)),this.padOffset>n-i)this.process(r,0),i=0;for(let l=i;l<n;l++)t[l]=0;Pie(r,n-8,BigInt(this.length*8),o),this.process(r,0);let s=A0(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");let c=a/4,d=this.get();if(c>d.length)throw Error("_sha2: outputLen bigger than state");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=o,e.length=n,e.pos=s,n%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}};Fi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Or=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function Aie(e,t=!1){if(t)return{h:Number(e&R0),l:Number(e>>o8&R0)};return{h:Number(e>>o8&R0)|0,l:Number(e&R0)|0}}function i8(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}=Aie(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}function Ko(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/4294967296|0)|0,l:o|0}}var R0,o8,Nv=(e,t,r)=>e>>>r,zv=(e,t,r)=>e<<32-r|t>>>r,gc=(e,t,r)=>e>>>r|t<<32-r,yc=(e,t,r)=>e<<32-r|t>>>r,vf=(e,t,r)=>e<<64-r|t>>>r-32,Tf=(e,t,r)=>e>>>r-32|t<<64-r,s8=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),a8=(e,t,r,n)=>t+r+n+(e/4294967296|0)|0,c8=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),u8=(e,t,r,n,o)=>t+r+n+o+(e/4294967296|0)|0,d8=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),l8=(e,t,r,n,o,i)=>t+r+n+o+i+(e/4294967296|0)|0;var p8=V(()=>{R0=BigInt(4294967295),o8=BigInt(32)});var kie,Xs,f8,m8,Rie,Oie,ea,ta,h8,g8,y8;var Bv=V(()=>{n8();p8();hc();kie=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]),Xs=new Uint32Array(64);f8=class f8 extends k0{constructor(e=32){super(64,e,8,!1);this.A=Fi[0]|0,this.B=Fi[1]|0,this.C=Fi[2]|0,this.D=Fi[3]|0,this.E=Fi[4]|0,this.F=Fi[5]|0,this.G=Fi[6]|0,this.H=Fi[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}process(e,t){for(let l=0;l<16;l++,t+=4)Xs[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=Xs[l-15],m=Xs[l-2],h=_o(p,7)^_o(p,18)^p>>>3,y=_o(m,17)^_o(m,19)^m>>>10;Xs[l]=y+Xs[l-7]+h+Xs[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=_o(s,6)^_o(s,11)^_o(s,25),m=d+p+t8(s,a,c)+kie[l]+Xs[l]|0,y=(_o(r,2)^_o(r,13)^_o(r,22))+r8(r,n,o)|0;d=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,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){Ui(Xs)}destroy(){this.set(0,0,0,0,0,0,0,0),Ui(this.buffer)}};m8=(()=>i8(["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))))(),Rie=(()=>m8[0])(),Oie=(()=>m8[1])(),ea=new Uint32Array(80),ta=new Uint32Array(80);h8=class h8 extends k0{constructor(e=64){super(128,e,16,!1);this.Ah=Or[0]|0,this.Al=Or[1]|0,this.Bh=Or[2]|0,this.Bl=Or[3]|0,this.Ch=Or[4]|0,this.Cl=Or[5]|0,this.Dh=Or[6]|0,this.Dl=Or[7]|0,this.Eh=Or[8]|0,this.El=Or[9]|0,this.Fh=Or[10]|0,this.Fl=Or[11]|0,this.Gh=Or[12]|0,this.Gl=Or[13]|0,this.Hh=Or[14]|0,this.Hl=Or[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:d,Fh:l,Fl:p,Gh:m,Gl:h,Hh:y,Hl:x}=this;return[e,t,r,n,o,i,s,a,c,d,l,p,m,h,y,x]}set(e,t,r,n,o,i,s,a,c,d,l,p,m,h,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=d|0,this.Fh=l|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=y|0,this.Hl=x|0}process(e,t){for(let A=0;A<16;A++,t+=4)ea[A]=e.getUint32(t),ta[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let S=ea[A-15]|0,v=ta[A-15]|0,P=gc(S,v,1)^gc(S,v,8)^Nv(S,v,7),k=yc(S,v,1)^yc(S,v,8)^zv(S,v,7),O=ea[A-2]|0,N=ta[A-2]|0,j=gc(O,N,19)^vf(O,N,61)^Nv(O,N,6),R=yc(O,N,19)^Tf(O,N,61)^zv(O,N,6),K=c8(k,R,ta[A-7],ta[A-16]),Z=u8(K,P,j,ea[A-7],ea[A-16]);ea[A]=Z|0,ta[A]=K|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:d,Eh:l,El:p,Fh:m,Fl:h,Gh:y,Gl:x,Hh:_,Hl:w}=this;for(let A=0;A<80;A++){let S=gc(l,p,14)^gc(l,p,18)^vf(l,p,41),v=yc(l,p,14)^yc(l,p,18)^Tf(l,p,41),P=l&m^~l&y,k=p&h^~p&x,O=d8(w,v,k,Oie[A],ta[A]),N=l8(O,_,S,P,Rie[A],ea[A]),j=O|0,R=gc(r,n,28)^vf(r,n,34)^vf(r,n,39),K=yc(r,n,28)^Tf(r,n,34)^Tf(r,n,39),Z=r&o^r&s^o&s,re=n&i^n&a^i&a;_=y|0,w=x|0,y=m|0,x=h|0,m=l|0,h=p|0,{h:l,l:p}=Ko(c|0,d|0,N|0,j|0),c=s|0,d=a|0,s=o|0,a=i|0,o=r|0,i=n|0;let pe=s8(j,K,re);r=a8(pe,N,R,Z),n=pe|0}({h:r,l:n}=Ko(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=Ko(this.Bh|0,this.Bl|0,o|0,i|0),{h:s,l:a}=Ko(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:d}=Ko(this.Dh|0,this.Dl|0,c|0,d|0),{h:l,l:p}=Ko(this.Eh|0,this.El|0,l|0,p|0),{h:m,l:h}=Ko(this.Fh|0,this.Fl|0,m|0,h|0),{h:y,l:x}=Ko(this.Gh|0,this.Gl|0,y|0,x|0),{h:_,l:w}=Ko(this.Hh|0,this.Hl|0,_|0,w|0),this.set(r,n,o,i,s,a,c,d,l,p,m,h,y,x,_,w)}roundClean(){Ui(ea,ta)}destroy(){Ui(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};g8=$v(()=>new f8),y8=$v(()=>new h8)});function Ju(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function jv(e){if(!Ju(e))throw Error("Uint8Array expected")}function Yo(e,t){if(typeof t!=="boolean")throw Error(e+" boolean expected, got "+t)}function Ef(e){let t=e.toString(16);return t.length&1?"0"+t:t}function _8(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?Fv:BigInt("0x"+e)}function ra(e){if(jv(e),w8)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Cie[e[r]];return t}function b8(e){if(e>=ji._0&&e<=ji._9)return e-ji._0;if(e>=ji.A&&e<=ji.F)return e-(ji.A-10);if(e>=ji.a&&e<=ji.f)return e-(ji.a-10);return}function Pf(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(w8)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("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=b8(e.charCodeAt(i)),a=b8(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function qi(e){return _8(ra(e))}function bc(e){return jv(e),_8(ra(Uint8Array.from(e).reverse()))}function xc(e,t){return Pf(e.toString(16).padStart(t*2,"0"))}function Qu(e,t){return xc(e,t).reverse()}function Gt(e,t,r){let n;if(typeof t==="string")try{n=Pf(t)}catch(i){throw Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(Ju(t))n=Uint8Array.from(t);else throw Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r==="number"&&o!==r)throw Error(e+" of length "+r+" expected, got "+o);return n}function na(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];jv(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 O0(e,t,r){return Lv(e)&&Lv(t)&&Lv(r)&&t<=e&&e<r}function Rn(e,t,r,n){if(!O0(t,r,n))throw Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function S8(e){let t;for(t=0;e>Fv;e>>=Uv,t+=1);return t}function v8(e,t,r){if(typeof e!=="number"||e<2)throw Error("hashLen must be a number");if(typeof t!=="number"||t<2)throw Error("qByteLen must be a number");if(typeof r!=="function")throw Error("hmacFn must be a function");let n=Dv(e),o=Dv(e),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...p)=>r(o,n,...p),c=(p=Dv(0))=>{if(o=a(x8([0]),p),n=a(),p.length===0)return;o=a(x8([1]),p),n=a()},d=()=>{if(i++>=1000)throw Error("drbg: tried 1000 values");let p=0,m=[];while(p<t){n=a();let h=n.slice();m.push(h),p+=n.length}return na(...m)};return(p,m)=>{s(),c(p);let h=void 0;while(!(h=m(d())))c();return s(),h}}function Hi(e,t,r={}){let n=(o,i,s)=>{let a=Mie[i];if(typeof a!=="function")throw Error("invalid validator function");let c=e[o];if(s&&c===void 0)return;if(!a(c,e))throw Error("param "+String(o)+" is invalid. Expected "+i+", got "+c)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(r))n(o,i,!0);return e}function Xu(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let i=e(r,...n);return t.set(r,i),i}}var Fv,Uv,w8,Cie,ji,Lv=(e)=>typeof e==="bigint"&&Fv<=e,_c=(e)=>(Uv<<BigInt(e))-Uv,Dv=(e)=>new Uint8Array(e),x8=(e)=>Uint8Array.from(e),Mie;var Af=V(()=>{/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Fv=BigInt(0),Uv=BigInt(1);w8=typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function",Cie=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));ji={_0:48,_9:57,A:65,F:70,a:97,f:102};Mie={bigint:(e)=>typeof e==="bigint",function:(e)=>typeof e==="function",boolean:(e)=>typeof e==="boolean",string:(e)=>typeof e==="string",stringOrUint8Array:(e)=>typeof e==="string"||Ju(e),isSafeInteger:(e)=>Number.isSafeInteger(e),array:(e)=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:(e)=>typeof e==="function"&&Number.isSafeInteger(e.outputLen)}});function Et(e,t){let r=e%t;return r>=tn?r:t+r}function Vt(e,t,r){let n=e;while(t-- >tn)n*=n,n%=r;return n}function C0(e,t){if(e===tn)throw Error("invert: expected non-zero number");if(t<=tn)throw Error("invert: expected positive modulus, got "+t);let r=Et(e,t),n=t,o=tn,i=br,s=br,a=tn;while(r!==tn){let d=n/r,l=n%r,p=o-s*d,m=i-a*d;n=r,r=l,o=s,i=a,s=p,a=m}if(n!==br)throw Error("invert: does not exist");return Et(o,t)}function I8(e,t){let r=(e.ORDER+br)/E8,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw Error("Cannot find square root");return n}function Nie(e,t){let r=(e.ORDER-P8)/A8,n=e.mul(t,wc),o=e.pow(n,r),i=e.mul(t,o),s=e.mul(e.mul(i,wc),o),a=e.mul(i,e.sub(s,e.ONE));if(!e.eql(e.sqr(a),t))throw Error("Cannot find square root");return a}function zie(e){if(e<BigInt(3))throw Error("sqrt is not defined for small field");let t=e-br,r=0;while(t%wc===tn)t/=wc,r++;let n=wc,o=Gi(e);while(T8(o,n)===1)if(n++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return I8;let i=o.pow(n,t),s=(t+br)/wc;return function(c,d){if(c.is0(d))return d;if(T8(c,d)!==1)throw Error("Cannot find square root");let l=r,p=c.mul(c.ONE,i),m=c.pow(d,t),h=c.pow(d,s);while(!c.eql(m,c.ONE)){if(c.is0(m))return c.ZERO;let y=1,x=c.sqr(m);while(!c.eql(x,c.ONE))if(y++,x=c.sqr(x),y===l)throw Error("Cannot find square root");let _=br<<BigInt(l-y-1),w=c.pow(p,_);l=y,p=c.sqr(w),m=c.mul(m,p),h=c.mul(h,w)}return h}}function Bie(e){if(e%E8===$ie)return I8;if(e%A8===P8)return Nie;return zie(e)}function qv(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Lie.reduce((n,o)=>(n[o]="function",n),t);return Hi(e,r)}function Die(e,t,r){if(r<tn)throw Error("invalid exponent, negatives unsupported");if(r===tn)return e.ONE;if(r===br)return t;let n=e.ONE,o=t;while(r>tn){if(r&br)n=e.mul(n,o);o=e.sqr(o),r>>=br}return n}function ed(e,t,r=!1){let n=Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((s,a,c)=>{if(e.is0(a))return s;return n[c]=s,e.mul(s,a)},e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>{if(e.is0(a))return s;return n[c]=e.mul(s,n[c]),e.mul(s,a)},i),n}function T8(e,t){let r=(e.ORDER-br)/wc,n=e.pow(t,r),o=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!o&&!i&&!s)throw Error("invalid Legendre symbol result");return o?1:i?0:-1}function Hv(e,t){if(t!==void 0)P0(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Gi(e,t,r=!1,n={}){if(e<=tn)throw Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:i}=Hv(e,t);if(i>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:i,MASK:_c(o),ZERO:tn,ONE:br,create:(c)=>Et(c,e),isValid:(c)=>{if(typeof c!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof c);return tn<=c&&c<e},is0:(c)=>c===tn,isOdd:(c)=>(c&br)===br,neg:(c)=>Et(-c,e),eql:(c,d)=>c===d,sqr:(c)=>Et(c*c,e),add:(c,d)=>Et(c+d,e),sub:(c,d)=>Et(c-d,e),mul:(c,d)=>Et(c*d,e),pow:(c,d)=>Die(a,c,d),div:(c,d)=>Et(c*C0(d,e),e),sqrN:(c)=>c*c,addN:(c,d)=>c+d,subN:(c,d)=>c-d,mulN:(c,d)=>c*d,inv:(c)=>C0(c,e),sqrt:n.sqrt||((c)=>{if(!s)s=Bie(e);return s(a,c)}),toBytes:(c)=>r?Qu(c,i):xc(c,i),fromBytes:(c)=>{if(c.length!==i)throw Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return r?bc(c):qi(c)},invertBatch:(c)=>ed(a,c),cmov:(c,d,l)=>l?d:c});return Object.freeze(a)}function R8(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Gv(e){let t=R8(e);return t+Math.ceil(t/2)}function O8(e,t,r=!1){let n=e.length,o=R8(t),i=Gv(t);if(n<16||n<i||n>1024)throw Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?bc(e):qi(e),a=Et(s,t-br)+br;return r?Qu(a,o):xc(a,o)}var tn,br,wc,$ie,E8,P8,A8,k8=(e,t)=>(Et(e,t)&br)===br,Lie;var td=V(()=>{hc();Af();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */tn=BigInt(0),br=BigInt(1),wc=BigInt(2),$ie=BigInt(3),E8=BigInt(4),P8=BigInt(5),A8=BigInt(8);Lie=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function Vv(e,t){let r=t.negate();return e?r:t}function $8(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function Zv(e,t){$8(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,i=_c(e),s=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function M8(e,t,r){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=r,a=Number(e&o),c=e>>s;if(a>n)a-=i,c+=Yv;let d=t*n,l=d+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:c,offset:l,isZero:p,isNeg:m,isNegF:h,offsetF:d}}function Uie(e,t){if(!Array.isArray(e))throw Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw Error("invalid point at index "+n)})}function Fie(e,t){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw Error("invalid scalar at index "+n)})}function Kv(e){return N8.get(e)||1}function M0(e,t){return{constTimeNegate:Vv,hasPrecomputes(r){return Kv(r)!==1},unsafeLadder(r,n,o=e.ZERO){let i=r;while(n>C8){if(n&Yv)o=o.add(i);i=i.double(),n>>=Yv}return o},precomputeWindow(r,n){let{windows:o,windowSize:i}=Zv(n,t),s=[],a=r,c=a;for(let d=0;d<o;d++){c=a,s.push(c);for(let l=1;l<i;l++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(r,n,o){let{ZERO:i,BASE:s}=e,a=Zv(r,t);for(let c=0;c<a.windows;c++){let{nextN:d,offset:l,isZero:p,isNeg:m,isNegF:h,offsetF:y}=M8(o,c,a);if(o=d,p)s=s.add(Vv(h,n[y]));else i=i.add(Vv(m,n[l]))}return{p:i,f:s}},wNAFUnsafe(r,n,o,i=e.ZERO){let s=Zv(r,t);for(let a=0;a<s.windows;a++){if(o===C8)break;let{nextN:c,offset:d,isZero:l,isNeg:p}=M8(o,a,s);if(o=c,l)continue;else{let m=n[d];i=i.add(p?m.negate():m)}}return i},getPrecomputes(r,n,o){let i=Wv.get(n);if(!i){if(i=this.precomputeWindow(n,r),r!==1)Wv.set(n,o(i))}return i},wNAFCached(r,n,o){let i=Kv(r);return this.wNAF(i,this.getPrecomputes(i,r,o),n)},wNAFCachedUnsafe(r,n,o,i){let s=Kv(r);if(s===1)return this.unsafeLadder(r,n,i);return this.wNAFUnsafe(s,this.getPrecomputes(s,r,o),n,i)},setWindowSize(r,n){$8(n,t),N8.set(r,n),Wv.delete(r)}}}function $0(e,t,r,n){Uie(r,e),Fie(n,t);let o=r.length,i=n.length;if(o!==i)throw Error("arrays of points and scalars must have equal length");let s=e.ZERO,a=S8(BigInt(o)),c=1;if(a>12)c=a-3;else if(a>4)c=a-2;else if(a>0)c=2;let d=_c(c),l=Array(Number(d)+1).fill(s),p=Math.floor((t.BITS-1)/c)*c,m=s;for(let h=p;h>=0;h-=c){l.fill(s);for(let x=0;x<i;x++){let _=n[x],w=Number(_>>BigInt(h)&d);l[w]=l[w].add(r[x])}let y=s;for(let x=l.length-1,_=s;x>0;x--)_=_.add(l[x]),y=y.add(_);if(m=m.add(y),h!==0)for(let x=0;x<c;x++)m=m.double()}return m}function If(e){return qv(e.Fp),Hi(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Hv(e.n,e.nBitLength),...e,...{p:e.Fp.ORDER}})}var C8,Yv,Wv,N8;var Jv=V(()=>{td();Af();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */C8=BigInt(0),Yv=BigInt(1);Wv=new WeakMap,N8=new WeakMap});var nT=ie(function(dz){Object.defineProperty(dz,"__esModule",{value:!0});dz.USE_PROXY=dz.UNSUPPORTED_MEDIA_TYPE=dz.UNPROCESSABLE_ENTITY=dz.UNAUTHORIZED=dz.TOO_MANY_REQUESTS=dz.TEMPORARY_REDIRECT=dz.SWITCHING_PROTOCOLS=dz.SERVICE_UNAVAILABLE=dz.SEE_OTHER=dz.RESET_CONTENT=dz.REQUESTED_RANGE_NOT_SATISFIABLE=dz.REQUEST_URI_TOO_LONG=dz.REQUEST_TOO_LONG=dz.REQUEST_TIMEOUT=dz.REQUEST_HEADER_FIELDS_TOO_LARGE=dz.PROXY_AUTHENTICATION_REQUIRED=dz.PROCESSING=dz.PRECONDITION_REQUIRED=dz.PRECONDITION_FAILED=dz.PERMANENT_REDIRECT=dz.PAYMENT_REQUIRED=dz.PARTIAL_CONTENT=dz.OK=dz.NOT_MODIFIED=dz.NOT_IMPLEMENTED=dz.NOT_FOUND=dz.NOT_ACCEPTABLE=dz.NON_AUTHORITATIVE_INFORMATION=dz.NO_CONTENT=dz.NETWORK_AUTHENTICATION_REQUIRED=dz.MULTIPLE_CHOICES=dz.MULTI_STATUS=dz.MOVED_TEMPORARILY=dz.MOVED_PERMANENTLY=dz.METHOD_NOT_ALLOWED=dz.METHOD_FAILURE=dz.LOCKED=dz.LENGTH_REQUIRED=dz.INTERNAL_SERVER_ERROR=dz.INSUFFICIENT_STORAGE=dz.INSUFFICIENT_SPACE_ON_RESOURCE=dz.IM_A_TEAPOT=dz.HTTP_VERSION_NOT_SUPPORTED=dz.GONE=dz.GATEWAY_TIMEOUT=dz.FORBIDDEN=dz.FAILED_DEPENDENCY=dz.EXPECTATION_FAILED=dz.CREATED=dz.CONTINUE=dz.CONFLICT=dz.BAD_REQUEST=dz.BAD_GATEWAY=dz.ACCEPTED=void 0;dz.ACCEPTED=202;dz.BAD_GATEWAY=502;dz.BAD_REQUEST=400;dz.CONFLICT=409;dz.CONTINUE=100;dz.CREATED=201;dz.EXPECTATION_FAILED=417;dz.FAILED_DEPENDENCY=424;dz.FORBIDDEN=403;dz.GATEWAY_TIMEOUT=504;dz.GONE=410;dz.HTTP_VERSION_NOT_SUPPORTED=505;dz.IM_A_TEAPOT=418;dz.INSUFFICIENT_SPACE_ON_RESOURCE=419;dz.INSUFFICIENT_STORAGE=507;dz.INTERNAL_SERVER_ERROR=500;dz.LENGTH_REQUIRED=411;dz.LOCKED=423;dz.METHOD_FAILURE=420;dz.METHOD_NOT_ALLOWED=405;dz.MOVED_PERMANENTLY=301;dz.MOVED_TEMPORARILY=302;dz.MULTI_STATUS=207;dz.MULTIPLE_CHOICES=300;dz.NETWORK_AUTHENTICATION_REQUIRED=511;dz.NO_CONTENT=204;dz.NON_AUTHORITATIVE_INFORMATION=203;dz.NOT_ACCEPTABLE=406;dz.NOT_FOUND=404;dz.NOT_IMPLEMENTED=501;dz.NOT_MODIFIED=304;dz.OK=200;dz.PARTIAL_CONTENT=206;dz.PAYMENT_REQUIRED=402;dz.PERMANENT_REDIRECT=308;dz.PRECONDITION_FAILED=412;dz.PRECONDITION_REQUIRED=428;dz.PROCESSING=102;dz.PROXY_AUTHENTICATION_REQUIRED=407;dz.REQUEST_HEADER_FIELDS_TOO_LARGE=431;dz.REQUEST_TIMEOUT=408;dz.REQUEST_TOO_LONG=413;dz.REQUEST_URI_TOO_LONG=414;dz.REQUESTED_RANGE_NOT_SATISFIABLE=416;dz.RESET_CONTENT=205;dz.SEE_OTHER=303;dz.SERVICE_UNAVAILABLE=503;dz.SWITCHING_PROTOCOLS=101;dz.TEMPORARY_REDIRECT=307;dz.TOO_MANY_REQUESTS=429;dz.UNAUTHORIZED=401;dz.UNPROCESSABLE_ENTITY=422;dz.UNSUPPORTED_MEDIA_TYPE=415;dz.USE_PROXY=305;dz.default={ACCEPTED:dz.ACCEPTED,BAD_GATEWAY:dz.BAD_GATEWAY,BAD_REQUEST:dz.BAD_REQUEST,CONFLICT:dz.CONFLICT,CONTINUE:dz.CONTINUE,CREATED:dz.CREATED,EXPECTATION_FAILED:dz.EXPECTATION_FAILED,FORBIDDEN:dz.FORBIDDEN,GATEWAY_TIMEOUT:dz.GATEWAY_TIMEOUT,GONE:dz.GONE,HTTP_VERSION_NOT_SUPPORTED:dz.HTTP_VERSION_NOT_SUPPORTED,IM_A_TEAPOT:dz.IM_A_TEAPOT,INSUFFICIENT_SPACE_ON_RESOURCE:dz.INSUFFICIENT_SPACE_ON_RESOURCE,INSUFFICIENT_STORAGE:dz.INSUFFICIENT_STORAGE,INTERNAL_SERVER_ERROR:dz.INTERNAL_SERVER_ERROR,LENGTH_REQUIRED:dz.LENGTH_REQUIRED,LOCKED:dz.LOCKED,METHOD_FAILURE:dz.METHOD_FAILURE,METHOD_NOT_ALLOWED:dz.METHOD_NOT_ALLOWED,MOVED_PERMANENTLY:dz.MOVED_PERMANENTLY,MOVED_TEMPORARILY:dz.MOVED_TEMPORARILY,MULTI_STATUS:dz.MULTI_STATUS,MULTIPLE_CHOICES:dz.MULTIPLE_CHOICES,NETWORK_AUTHENTICATION_REQUIRED:dz.NETWORK_AUTHENTICATION_REQUIRED,NO_CONTENT:dz.NO_CONTENT,NON_AUTHORITATIVE_INFORMATION:dz.NON_AUTHORITATIVE_INFORMATION,NOT_ACCEPTABLE:dz.NOT_ACCEPTABLE,NOT_FOUND:dz.NOT_FOUND,NOT_IMPLEMENTED:dz.NOT_IMPLEMENTED,NOT_MODIFIED:dz.NOT_MODIFIED,OK:dz.OK,PARTIAL_CONTENT:dz.PARTIAL_CONTENT,PAYMENT_REQUIRED:dz.PAYMENT_REQUIRED,PERMANENT_REDIRECT:dz.PERMANENT_REDIRECT,PRECONDITION_FAILED:dz.PRECONDITION_FAILED,PRECONDITION_REQUIRED:dz.PRECONDITION_REQUIRED,PROCESSING:dz.PROCESSING,PROXY_AUTHENTICATION_REQUIRED:dz.PROXY_AUTHENTICATION_REQUIRED,REQUEST_HEADER_FIELDS_TOO_LARGE:dz.REQUEST_HEADER_FIELDS_TOO_LARGE,REQUEST_TIMEOUT:dz.REQUEST_TIMEOUT,REQUEST_TOO_LONG:dz.REQUEST_TOO_LONG,REQUEST_URI_TOO_LONG:dz.REQUEST_URI_TOO_LONG,REQUESTED_RANGE_NOT_SATISFIABLE:dz.REQUESTED_RANGE_NOT_SATISFIABLE,RESET_CONTENT:dz.RESET_CONTENT,SEE_OTHER:dz.SEE_OTHER,SERVICE_UNAVAILABLE:dz.SERVICE_UNAVAILABLE,SWITCHING_PROTOCOLS:dz.SWITCHING_PROTOCOLS,TEMPORARY_REDIRECT:dz.TEMPORARY_REDIRECT,TOO_MANY_REQUESTS:dz.TOO_MANY_REQUESTS,UNAUTHORIZED:dz.UNAUTHORIZED,UNPROCESSABLE_ENTITY:dz.UNPROCESSABLE_ENTITY,UNSUPPORTED_MEDIA_TYPE:dz.UNSUPPORTED_MEDIA_TYPE,USE_PROXY:dz.USE_PROXY}});var lB=ie(function(uB){Object.defineProperty(uB,"__esModule",{value:!0});uB.reasonPhraseToStatusCode=uB.statusCodeToReasonPhrase=void 0;uB.statusCodeToReasonPhrase={"202":"Accepted","502":"Bad Gateway","400":"Bad Request","409":"Conflict","100":"Continue","201":"Created","417":"Expectation Failed","424":"Failed Dependency","403":"Forbidden","504":"Gateway Timeout","410":"Gone","505":"HTTP Version Not Supported","418":"I'm a teapot","419":"Insufficient Space on Resource","507":"Insufficient Storage","500":"Internal Server Error","411":"Length Required","423":"Locked","420":"Method Failure","405":"Method Not Allowed","301":"Moved Permanently","302":"Moved Temporarily","207":"Multi-Status","300":"Multiple Choices","511":"Network Authentication Required","204":"No Content","203":"Non Authoritative Information","406":"Not Acceptable","404":"Not Found","501":"Not Implemented","304":"Not Modified","200":"OK","206":"Partial Content","402":"Payment Required","308":"Permanent Redirect","412":"Precondition Failed","428":"Precondition Required","102":"Processing","103":"Early Hints","426":"Upgrade Required","407":"Proxy Authentication Required","431":"Request Header Fields Too Large","408":"Request Timeout","413":"Request Entity Too Large","414":"Request-URI Too Long","416":"Requested Range Not Satisfiable","205":"Reset Content","303":"See Other","503":"Service Unavailable","101":"Switching Protocols","307":"Temporary Redirect","429":"Too Many Requests","401":"Unauthorized","451":"Unavailable For Legal Reasons","422":"Unprocessable Entity","415":"Unsupported Media Type","305":"Use Proxy","421":"Misdirected Request"};uB.reasonPhraseToStatusCode={Accepted:202,"Bad Gateway":502,"Bad Request":400,Conflict:409,Continue:100,Created:201,"Expectation Failed":417,"Failed Dependency":424,Forbidden:403,"Gateway Timeout":504,Gone:410,"HTTP Version Not Supported":505,"I'm a teapot":418,"Insufficient Space on Resource":419,"Insufficient Storage":507,"Internal Server Error":500,"Length Required":411,Locked:423,"Method Failure":420,"Method Not Allowed":405,"Moved Permanently":301,"Moved Temporarily":302,"Multi-Status":207,"Multiple Choices":300,"Network Authentication Required":511,"No Content":204,"Non Authoritative Information":203,"Not Acceptable":406,"Not Found":404,"Not Implemented":501,"Not Modified":304,OK:200,"Partial Content":206,"Payment Required":402,"Permanent Redirect":308,"Precondition Failed":412,"Precondition Required":428,Processing:102,"Early Hints":103,"Upgrade Required":426,"Proxy Authentication Required":407,"Request Header Fields Too Large":431,"Request Timeout":408,"Request Entity Too Large":413,"Request-URI Too Long":414,"Requested Range Not Satisfiable":416,"Reset Content":205,"See Other":303,"Service Unavailable":503,"Switching Protocols":101,"Temporary Redirect":307,"Too Many Requests":429,Unauthorized:401,"Unavailable For Legal Reasons":451,"Unprocessable Entity":422,"Unsupported Media Type":415,"Use Proxy":305,"Misdirected Request":421}});var oT=ie(function(mB){Object.defineProperty(mB,"__esModule",{value:!0});mB.getStatusText=mB.getStatusCode=mB.getReasonPhrase=void 0;var pB=lB();function fB(e){var t=pB.statusCodeToReasonPhrase[e.toString()];if(!t)throw Error("Status code does not exist: "+e);return t}mB.getReasonPhrase=fB;function bse(e){var t=pB.reasonPhraseToStatusCode[e];if(!t)throw Error("Reason phrase does not exist: "+e);return t}mB.getStatusCode=bse;mB.getStatusText=fB});var yB=ie(function(gB){Object.defineProperty(gB,"__esModule",{value:!0});gB.StatusCodes=void 0;var wse;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(wse=gB.StatusCodes||(gB.StatusCodes={}))});var xB=ie(function(bB){Object.defineProperty(bB,"__esModule",{value:!0});bB.ReasonPhrases=void 0;var Sse;(function(e){e.ACCEPTED="Accepted",e.BAD_GATEWAY="Bad Gateway",e.BAD_REQUEST="Bad Request",e.CONFLICT="Conflict",e.CONTINUE="Continue",e.CREATED="Created",e.EXPECTATION_FAILED="Expectation Failed",e.FAILED_DEPENDENCY="Failed Dependency",e.FORBIDDEN="Forbidden",e.GATEWAY_TIMEOUT="Gateway Timeout",e.GONE="Gone",e.HTTP_VERSION_NOT_SUPPORTED="HTTP Version Not Supported",e.IM_A_TEAPOT="I'm a teapot",e.INSUFFICIENT_SPACE_ON_RESOURCE="Insufficient Space on Resource",e.INSUFFICIENT_STORAGE="Insufficient Storage",e.INTERNAL_SERVER_ERROR="Internal Server Error",e.LENGTH_REQUIRED="Length Required",e.LOCKED="Locked",e.METHOD_FAILURE="Method Failure",e.METHOD_NOT_ALLOWED="Method Not Allowed",e.MOVED_PERMANENTLY="Moved Permanently",e.MOVED_TEMPORARILY="Moved Temporarily",e.MULTI_STATUS="Multi-Status",e.MULTIPLE_CHOICES="Multiple Choices",e.NETWORK_AUTHENTICATION_REQUIRED="Network Authentication Required",e.NO_CONTENT="No Content",e.NON_AUTHORITATIVE_INFORMATION="Non Authoritative Information",e.NOT_ACCEPTABLE="Not Acceptable",e.NOT_FOUND="Not Found",e.NOT_IMPLEMENTED="Not Implemented",e.NOT_MODIFIED="Not Modified",e.OK="OK",e.PARTIAL_CONTENT="Partial Content",e.PAYMENT_REQUIRED="Payment Required",e.PERMANENT_REDIRECT="Permanent Redirect",e.PRECONDITION_FAILED="Precondition Failed",e.PRECONDITION_REQUIRED="Precondition Required",e.PROCESSING="Processing",e.EARLY_HINTS="Early Hints",e.UPGRADE_REQUIRED="Upgrade Required",e.PROXY_AUTHENTICATION_REQUIRED="Proxy Authentication Required",e.REQUEST_HEADER_FIELDS_TOO_LARGE="Request Header Fields Too Large",e.REQUEST_TIMEOUT="Request Timeout",e.REQUEST_TOO_LONG="Request Entity Too Large",e.REQUEST_URI_TOO_LONG="Request-URI Too Long",e.REQUESTED_RANGE_NOT_SATISFIABLE="Requested Range Not Satisfiable",e.RESET_CONTENT="Reset Content",e.SEE_OTHER="See Other",e.SERVICE_UNAVAILABLE="Service Unavailable",e.SWITCHING_PROTOCOLS="Switching Protocols",e.TEMPORARY_REDIRECT="Temporary Redirect",e.TOO_MANY_REQUESTS="Too Many Requests",e.UNAUTHORIZED="Unauthorized",e.UNAVAILABLE_FOR_LEGAL_REASONS="Unavailable For Legal Reasons",e.UNPROCESSABLE_ENTITY="Unprocessable Entity",e.UNSUPPORTED_MEDIA_TYPE="Unsupported Media Type",e.USE_PROXY="Use Proxy",e.MISDIRECTED_REQUEST="Misdirected Request"})(Sse=bB.ReasonPhrases||(bB.ReasonPhrases={}))});var j0=ie(function(Cr){var F0=Cr&&Cr.__assign||function(){return F0=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++){t=arguments[r];for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o))e[o]=t[o]}return e},F0.apply(this,arguments)},vse=Cr&&Cr.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),Tse=Cr&&Cr.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!t.hasOwnProperty(r))vse(t,e,r)},Ese=Cr&&Cr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Cr,"__esModule",{value:!0});var Pse=Ese(nT()),_B=oT(),aT=oT();Object.defineProperty(Cr,"getStatusCode",{enumerable:!0,get:function(){return aT.getStatusCode}});Object.defineProperty(Cr,"getReasonPhrase",{enumerable:!0,get:function(){return aT.getReasonPhrase}});Object.defineProperty(Cr,"getStatusText",{enumerable:!0,get:function(){return aT.getStatusText}});var Ase=yB();Object.defineProperty(Cr,"StatusCodes",{enumerable:!0,get:function(){return Ase.StatusCodes}});var Ise=xB();Object.defineProperty(Cr,"ReasonPhrases",{enumerable:!0,get:function(){return Ise.ReasonPhrases}});Tse(nT(),Cr);Cr.default=F0(F0({},Pse.default),{getStatusCode:_B.getStatusCode,getStatusText:_B.getStatusText})});function ze(e){if(typeof e==="string")return{address:e,type:"json-rpc"};return e}var Zn,Z0,vB,W0,TB,dT,lT,pT,Cf,Wt;var Mr=V(()=>{Zn=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],Z0=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],vB=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],W0=[...vB,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],TB=[...vB,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],dT=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],lT=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],pT=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],Cf=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],Wt=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}]});function dr(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new fT(e.type);return`${e.name}(${Mf(e.inputs,{includeName:t})})`}function Mf(e,{includeName:t=!1}={}){if(!e)return"";return e.map((r)=>$se(r,{includeName:t})).join(t?", ":",")}function $se(e,{includeName:t}){if(e.type.startsWith("tuple"))return`(${Mf(e.components,{includeName:t})})${e.type.slice(5)}`;return e.type+(t&&e.name?` ${e.name}`:"")}var Zi=V(()=>{ir()});function Kt(e,{strict:t=!0}={}){if(!e)return!1;if(typeof e!=="string")return!1;return t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function et(e){if(Kt(e,{strict:!1}))return Math.ceil((e.length-2)/2);return e.length}var mn=()=>{};var mT="2.56.3";function EB(e,t){if(t?.(e))return e;if(e&&typeof e==="object"&&"cause"in e&&e.cause!==void 0)return EB(e.cause,t);return t?null:e}var hT,C;var He=V(()=>{hT={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${mT}`};C=class C extends Error{constructor(e,t={}){let r=(()=>{if(t.cause instanceof C)return t.cause.details;if(t.cause?.message)return t.cause.message;return t.details})(),n=(()=>{if(t.cause instanceof C)return t.cause.docsPath||t.docsPath;return t.docsPath})(),o=hT.getDocsUrl?.({...t,docsPath:n}),i=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...r?[`Details: ${r}`]:[],...hT.version?[`Version: ${hT.version}`]:[]].join(`
|
|
@@ -58,11 +58,11 @@ Content-Type: ${i.type||"application/octet-stream"}\r
|
|
|
58
58
|
${Z3(m)}`;super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",y].filter(Boolean),name:"CallExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}};tm=class tm extends C{constructor(e,{abi:t,args:r,contractAddress:n,docsPath:o,functionName:i,sender:s}){let a=bn({abi:t,args:r,name:i}),c=a?yE({abiItem:a,args:r,includeFunctionName:!1,includeName:!1}):void 0,d=a?dr(a,{includeName:!0}):void 0,l=Ic({address:n&&W3(n),function:d,args:c&&c!=="()"&&`${[...Array(i?.length??0).keys()].map(()=>" ").join("")}${c}`,sender:s});super(e.shortMessage||`An unknown error occurred while executing the contract function "${i}".`,{cause:e,docsPath:o,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],l&&"Contract Call:",l].filter(Boolean),name:"ContractFunctionExecutionError"});Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=t,this.args=r,this.cause=e,this.contractAddress=n,this.functionName=i,this.sender=s}};bd=class bd extends C{constructor({abi:e,data:t,functionName:r,message:n,cause:o}){let i,s,a,c;if(t&&t!=="0x")try{s=Ey({abi:e,data:t,cause:o});let{abiItem:l,errorName:p,args:m}=s;if(p==="Error")c=m[0];else if(p==="Panic"){let[h]=m;c=D3[h]}else{let h=l?dr(l,{includeName:!0}):void 0,y=l&&m?yE({abiItem:l,args:m,includeFunctionName:!1,includeName:!1}):void 0;a=[h?`Error: ${h}`:"",y&&y!=="()"?` ${[...Array(p?.length??0).keys()].map(()=>" ").join("")}${y}`:""]}}catch(l){i=l}else if(n)c=n;let d;if(i instanceof Nf)d=i.signature,a=[`Unable to decode signature "${d}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${d}.`];super(c&&c!=="execution reverted"||d?[`The contract function "${r}" reverted with the following ${d?"signature":"reason"}:`,c||d].join(`
|
|
59
59
|
`):`The contract function "${r}" reverted.`,{cause:i??o,metaMessages:a,name:"ContractFunctionRevertedError"});Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=s,this.raw=t,this.reason=c,this.signature=d}};AE=class AE extends C{constructor({functionName:e,cause:t}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:t})}};IE=class IE extends C{constructor({factory:e}){super(`Deployment for counterfactual contract call failed${e?` for factory "${e}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}};ns=class ns extends C{constructor({data:e,message:t}){super(t||"",{name:"RawContractError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}});function K3(e){let{abi:t,data:r}=e,n=gn(r,0,4),o=t.find((i)=>i.type==="function"&&n===oi(dr(i)));if(!o)throw new vT(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:o.name,args:"inputs"in o&&o.inputs&&o.inputs.length>0?Xi(o.inputs,gn(r,4)):void 0}}var Y3=V(()=>{ir();Ji();pd();Vf();Zi()});function RE(e){let{abi:t,errorName:r,args:n}=e,o=t[0];if(r){let c=bn({abi:t,args:n,name:r});if(!c)throw new Y0(r,{docsPath:kE});o=c}if(o.type!=="error")throw new Y0(void 0,{docsPath:kE});let i=dr(o),s=oi(i),a="0x";if(n&&n.length>0){if(!o.inputs)throw new _T(o.name,{docsPath:kE});a=nn(o.inputs,n)}return Qt([s,a])}var kE="/docs/contract/encodeErrorResult";var J3=V(()=>{ir();pd();Qi();Zi();la()});function Q3(e){let{abi:t,functionName:r,result:n}=e,o=t[0];if(r){let s=bn({abi:t,name:r});if(!s)throw new Xo(r,{docsPath:OE});o=s}if(o.type!=="function")throw new Xo(void 0,{docsPath:OE});if(!o.outputs)throw new zf(o.name,{docsPath:OE});let i=(()=>{if(o.outputs.length===0)return[];if(o.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Bf(n)})();return nn(o.outputs,i)}var OE="/docs/contract/encodeFunctionResult";var X3=V(()=>{ir();Qi();la()});async function CE(e){let{data:t,ccipRequest:r}=e,{args:[n]}=K3({abi:Z0,data:t}),o=[],i=[];return await Promise.all(n.map(async(s,a)=>{try{i[a]=s.urls.includes(is)?await CE({data:s.data,ccipRequest:r}):await r(s),o[a]=!1}catch(c){o[a]=!0,i[a]=Nae(c)}})),Q3({abi:Z0,functionName:"query",result:[o,i]})}function Nae(e){if(e.name==="HttpRequestError"&&e.status)return RE({abi:Z0,errorName:"HttpError",args:[e.status,e.shortMessage]});return RE({abi:[vy],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}var is="x-batch-gateway:true";var rm=V(()=>{Mr();Ty();Y3();J3();X3()});var Io,wd,Cc,Oy;var Mc=V(()=>{He();Io=class Io extends C{constructor({body:e,cause:t,details:r,headers:n,status:o,url:i}){super("HTTP request failed.",{cause:t,details:r,metaMessages:[o&&`Status: ${o}`,`URL: ${Rc(i)}`,e&&`Request body: ${Je(e)}`].filter(Boolean),name:"HttpRequestError"});Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=n,this.status=o,this.url=i}};wd=class wd extends C{constructor({maxSize:e,size:t}){super("HTTP response body exceeded the size limit.",{metaMessages:[`Max: ${e} bytes`,`Received: ${t} bytes`],name:"ResponseBodyTooLargeError"});Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e,this.size=t}};Cc=class Cc extends C{constructor({body:e,error:t,url:r}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${Rc(r)}`,`Request body: ${Je(e)}`],name:"RpcRequestError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t.code,this.data=t.data,this.url=r}};Oy=class Oy extends C{constructor({body:e,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Rc(t)}`,`Request body: ${Je(e)}`],name:"TimeoutError"});Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}}});var zae=-1,sn,an,Sd,vd,Td,Ed,ss,Jn,Pd,Ad,Id,pa,$c,kd,Nc,Rd,Od,Cd,Md,$d,fa,Nd,zd,Bd,Ld,Dd,ma,Ud,ME;var Fd=V(()=>{He();Mc();sn=class sn extends C{constructor(e,{code:t,docsPath:r,metaMessages:n,name:o,shortMessage:i}){super(i,{cause:e,docsPath:r,metaMessages:n||e?.metaMessages,name:o||"RpcError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=o||e.name,this.code=e instanceof Cc?e.code:t??zae}};an=class an extends sn{constructor(e,t){super(e,t);Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}};Sd=class Sd extends sn{constructor(e){super(e,{code:Sd.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}};Object.defineProperty(Sd,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});vd=class vd extends sn{constructor(e){super(e,{code:vd.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}};Object.defineProperty(vd,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});Td=class Td extends sn{constructor(e,{method:t}={}){super(e,{code:Td.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}};Object.defineProperty(Td,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});Ed=class Ed extends sn{constructor(e){super(e,{code:Ed.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
|
|
60
60
|
`)})}};Object.defineProperty(Ed,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});ss=class ss extends sn{constructor(e){super(e,{code:ss.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}};Object.defineProperty(ss,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});Jn=class Jn extends sn{constructor(e){super(e,{code:Jn.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
|
|
61
|
-
`)})}};Object.defineProperty(Jn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32000});Pd=class Pd extends sn{constructor(e){super(e,{code:Pd.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}};Object.defineProperty(Pd,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});Ad=class Ad extends sn{constructor(e){super(e,{code:Ad.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}};Object.defineProperty(Ad,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});Id=class Id extends sn{constructor(e){super(e,{code:Id.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}};Object.defineProperty(Id,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});pa=class pa extends sn{constructor(e,{method:t}={}){super(e,{code:pa.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}};Object.defineProperty(pa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});$c=class $c extends sn{constructor(e){super(e,{code:$c.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}};Object.defineProperty($c,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});kd=class kd extends sn{constructor(e){super(e,{code:kd.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}};Object.defineProperty(kd,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});Nc=class Nc extends an{constructor(e){super(e,{code:Nc.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(Nc,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});Rd=class Rd extends an{constructor(e){super(e,{code:Rd.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}};Object.defineProperty(Rd,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});Od=class Od extends an{constructor(e,{method:t}={}){super(e,{code:Od.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}};Object.defineProperty(Od,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});Cd=class Cd extends an{constructor(e){super(e,{code:Cd.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}};Object.defineProperty(Cd,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});Md=class Md extends an{constructor(e){super(e,{code:Md.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}};Object.defineProperty(Md,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});$d=class $d extends an{constructor(e){super(e,{code:$d.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}};Object.defineProperty($d,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});fa=class fa extends an{constructor(e){super(e,{code:fa.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}};Object.defineProperty(fa,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});Nd=class Nd extends an{constructor(e){super(e,{code:Nd.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}};Object.defineProperty(Nd,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});zd=class zd extends an{constructor(e){super(e,{code:zd.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}};Object.defineProperty(zd,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});Bd=class Bd extends an{constructor(e){super(e,{code:Bd.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}};Object.defineProperty(Bd,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});Ld=class Ld extends an{constructor(e){super(e,{code:Ld.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}};Object.defineProperty(Ld,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});Dd=class Dd extends an{constructor(e){super(e,{code:Dd.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}};Object.defineProperty(Dd,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});ma=class ma extends an{constructor(e){super(e,{code:ma.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}};Object.defineProperty(ma,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});Ud=class Ud extends an{constructor(e){super(e,{code:Ud.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}};Object.defineProperty(Ud,"code",{enumerable:!0,configurable:!0,writable:!0,value:7000});ME=class ME extends sn{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}});var rL="0.1.1";function nL(){return rL}var oL=()=>{};function iL(e,t){if(t?.(e))return e;if(e&&typeof e==="object"&&"cause"in e&&e.cause)return iL(e.cause,t);return t?null:e}var
|
|
62
|
-
`);super(c,t.cause?{cause:t.cause}:void 0);Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=t.cause,this.details=r,this.docs=i,this.docsOrigin=o,this.docsPath=n,this.shortMessage=e,this.showVersion=s,this.version=a}walk(e){return iL(this,e)}};Object.defineProperty(Ee,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${nL()}`}});(()=>{Ee.setStaticOptions(Ee.defaultStaticOptions)})()});function jd(e,t){if(Xn(e)>t)throw new zE({givenSize:Xn(e),maxSize:t})}function sL(e,t){if(typeof t==="number"&&t>0&&t>Xn(e)-1)throw new Cy({offset:t,position:"start",size:Xn(e)})}function aL(e,t,r){if(typeof t==="number"&&typeof r==="number"&&Xn(e)!==r-t)throw new Cy({offset:r,position:"end",size:Xn(e)})}function $E(e){if(e>=as.zero&&e<=as.nine)return e-as.zero;if(e>=as.A&&e<=as.F)return e-(as.A-10);if(e>=as.a&&e<=as.f)return e-(as.a-10);return}function cL(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new BE({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let i=0;i<n;i++){let s=r==="right";o[s?i:n-i-1]=e[s?i:e.length-i-1]}return o}function NE(e,t={}){let{dir:r="left"}=t,n=e,o=0;for(let i=0;i<n.length-1;i++)if(n[r==="left"?i:n.length-i-1].toString()==="0")o++;else break;return n=r==="left"?n.slice(o):n.slice(0,n.length-o),n}var as;var uL=V(()=>{qd();as={zero:48,nine:57,A:65,F:70,a:97,f:102}});function Hd(e,t){if(sr(e)>t)throw new UE({givenSize:sr(e),maxSize:t})}function dL(e,t){if(typeof t==="number"&&t>0&&t>sr(e)-1)throw new My({offset:t,position:"start",size:sr(e)})}function lL(e,t,r){if(typeof t==="number"&&typeof r==="number"&&sr(e)!==r-t)throw new My({offset:r,position:"end",size:sr(e)})}function LE(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new FE({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}var DE=V(()=>{wn()});function $y(e,t,r){return JSON.stringify(e,(n,o)=>{if(typeof t==="function")return t(n,o);if(typeof o==="bigint")return o.toString()+"#__bigint";return o},r)}function mL(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")return jE(e);return Fae(e)}function Fae(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function jE(e,t={}){let{size:r}=t,n=e;if(r)Hd(e,r),n=si(e,r);let o=n.slice(2);if(o.length%2)o=`0${o}`;let i=o.length/2,s=new Uint8Array(i);for(let a=0,c=0;a<i;a++){let d=$E(o.charCodeAt(c++)),l=$E(o.charCodeAt(c++));if(d===void 0||l===void 0)throw new Ee(`Invalid byte sequence ("${o[c-2]}${o[c-1]}" in "${o}").`);s[a]=d<<4|l}return s}function hL(e,t={}){let{size:r}=t,n=Uae.encode(e);if(typeof r==="number")return jd(n,r),jae(n,r);return n}function jae(e,t){return cL(e,{dir:"right",size:t})}function Xn(e){return e.length}function gL(e,t,r,n={}){let{strict:o}=n;sL(e,t);let i=e.slice(t,r);if(o)aL(i,t,r);return i}function yL(e,t={}){let{size:r}=t;if(typeof r<"u")jd(e,r);let n=Ur(e,t);return HE(n,t)}function bL(e,t={}){let{size:r}=t,n=e;if(typeof r<"u")jd(n,r),n=qE(n);if(n.length>1||n[0]>1)throw new _L(n);return Boolean(n[0])}function ii(e,t={}){let{size:r}=t;if(typeof r<"u")jd(e,r);let n=Ur(e,t);return Ny(n,t)}function xL(e,t={}){let{size:r}=t,n=e;if(typeof r<"u")jd(n,r),n=qae(n);return Dae.decode(n)}function qE(e){return NE(e,{dir:"left"})}function qae(e){return NE(e,{dir:"right"})}var Dae,Uae,_L,zE,Cy,BE;var qd=V(()=>{Qn();wn();uL();DE();Dae=new TextDecoder,Uae=new TextEncoder;_L=class _L extends Ee{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}};zE=class zE extends Ee{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}};Cy=class Cy extends Ee{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"})}};BE=class BE extends Ee{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function Vae(e,t={}){let{strict:r=!1}=t;if(!e)throw new GE(e);if(typeof e!=="string")throw new GE(e);if(r){if(!/^0x[0-9a-fA-F]*$/.test(e))throw new VE(e)}if(!e.startsWith("0x"))throw new VE(e)}function _r(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function wL(e){if(e instanceof Uint8Array)return Ur(e);if(Array.isArray(e))return Ur(new Uint8Array(e));return e}function zy(e,t={}){let r=`0x${Number(e)}`;if(typeof t.size==="number")return Hd(r,t.size),cs(r,t.size);return r}function Ur(e,t={}){let r="";for(let o=0;o<e.length;o++)r+=Gae[e[o]];let n=`0x${r}`;if(typeof t.size==="number")return Hd(n,t.size),si(n,t.size);return n}function rr(e,t={}){let{signed:r,size:n}=t,o=BigInt(e),i;if(n)if(r)i=(1n<<BigInt(n)*8n-1n)-1n;else i=2n**(BigInt(n)*8n)-1n;else if(typeof e==="number")i=BigInt(Number.MAX_SAFE_INTEGER);let s=typeof i==="bigint"&&r?-i-1n:0;if(i&&o>i||o<s){let d=typeof e==="bigint"?"n":"";throw new By({max:i?`${i}${d}`:void 0,min:`${s}${d}`,signed:r,size:n,value:`${e}${d}`})}let c=`0x${(r&&o<0?BigInt.asUintN(n*8,BigInt(o)):o).toString(16)}`;if(n)return cs(c,n);return c}function Gd(e,t={}){return Ur(Hae.encode(e),t)}function cs(e,t){return LE(e,{dir:"left",size:t})}function si(e,t){return LE(e,{dir:"right",size:t})}function Fr(e,t,r,n={}){let{strict:o}=n;dL(e,t);let i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;if(o)lL(i,t,r);return i}function sr(e){return Math.ceil((e.length-2)/2)}function HE(e,t={}){let{signed:r}=t;if(t.size)Hd(e,t.size);let n=BigInt(e);if(!r)return n;let o=(e.length-2)/2,i=(1n<<BigInt(o)*8n)-1n,s=i>>1n;if(n<=s)return n;return n-i-1n}function Ny(e,t={}){let{signed:r,size:n}=t;if(!r&&!n)return Number(e);return Number(HE(e,t))}function ZE(e,t={}){let{strict:r=!1}=t;try{return Vae(e,{strict:r}),!0}catch{return!1}}var Hae,Gae,By,GE,VE,UE,My,FE;var wn=V(()=>{Qn();DE();Hae=new TextEncoder,Gae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));By=class By extends Ee{constructor({max:e,min:t,signed:r,size:n,value:o}){super(`Number \`${o}\` is not in safe${n?` ${n*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}};GE=class GE extends Ee{constructor(e){super(`Value \`${typeof e==="object"?$y(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}};VE=class VE extends Ee{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}};UE=class UE extends Ee{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};My=class My extends Ee{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}};FE=class FE extends Ee{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function SL(e){return{address:e.address,amount:rr(e.amount),index:rr(e.index),validatorIndex:rr(e.validatorIndex)}}var vL=V(()=>{wn()});function Ly(e){return{...typeof e.baseFeePerGas==="bigint"&&{baseFeePerGas:rr(e.baseFeePerGas)},...typeof e.blobBaseFee==="bigint"&&{blobBaseFee:rr(e.blobBaseFee)},...typeof e.feeRecipient==="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit==="bigint"&&{gasLimit:rr(e.gasLimit)},...typeof e.number==="bigint"&&{number:rr(e.number)},...typeof e.prevRandao==="bigint"&&{prevRandao:rr(e.prevRandao)},...typeof e.time==="bigint"&&{time:rr(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(SL)}}}var WE=V(()=>{wn();vL()});var EL="0x82ad56cb";var Dy="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",PL="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",AL="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",zc="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";function Bc(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let o=t.find((s)=>("type"in s)&&s.type==="constructor");if(!o)throw new gT({docsPath:KE});if(!("inputs"in o))throw new K0({docsPath:KE});if(!o.inputs||o.inputs.length===0)throw new K0({docsPath:KE});let i=nn(o.inputs,r);return Qt([n,i])}var KE="/docs/contract/encodeDeployData";var Uy=V(()=>{ir();Qi()});function wr(e,t){if(!ht(e,{strict:!1}))throw new Ft({address:e});if(!ht(t,{strict:!1}))throw new Ft({address:t});return e.toLowerCase()===t.toLowerCase()}var us=V(()=>{ei();Cn()});function zn(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o}=e;if(o!==void 0&&!t)throw new C("`requireCanonical` can only be provided when `blockHash` is set.");if(t)return o?{blockHash:t,requireCanonical:o}:{blockHash:t};if(typeof r==="bigint")return H(r);return n??"latest"}var Lc=V(()=>{He();Fe()});var ai,Ro,im,sm,am,cm,um,dm,lm,pm,ds,Oo;var ls=V(()=>{gd();He();ai=class ai extends C{constructor({cause:e,message:t}={}){let r=t?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${r?`with reason: ${r}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}};Object.defineProperty(ai,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ai,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});Ro=class Ro extends C{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${mr(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}};Object.defineProperty(Ro,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});im=class im extends C{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${mr(t)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}};Object.defineProperty(im,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});sm=class sm extends C{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}};Object.defineProperty(sm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});am=class am extends C{constructor({cause:e,nonce:t}={}){super([`Nonce provided for the transaction ${t?`(${t}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
|
|
61
|
+
`)})}};Object.defineProperty(Jn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32000});Pd=class Pd extends sn{constructor(e){super(e,{code:Pd.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}};Object.defineProperty(Pd,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});Ad=class Ad extends sn{constructor(e){super(e,{code:Ad.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}};Object.defineProperty(Ad,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});Id=class Id extends sn{constructor(e){super(e,{code:Id.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}};Object.defineProperty(Id,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});pa=class pa extends sn{constructor(e,{method:t}={}){super(e,{code:pa.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}};Object.defineProperty(pa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});$c=class $c extends sn{constructor(e){super(e,{code:$c.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}};Object.defineProperty($c,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});kd=class kd extends sn{constructor(e){super(e,{code:kd.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}};Object.defineProperty(kd,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});Nc=class Nc extends an{constructor(e){super(e,{code:Nc.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(Nc,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});Rd=class Rd extends an{constructor(e){super(e,{code:Rd.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}};Object.defineProperty(Rd,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});Od=class Od extends an{constructor(e,{method:t}={}){super(e,{code:Od.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}};Object.defineProperty(Od,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});Cd=class Cd extends an{constructor(e){super(e,{code:Cd.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}};Object.defineProperty(Cd,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});Md=class Md extends an{constructor(e){super(e,{code:Md.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}};Object.defineProperty(Md,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});$d=class $d extends an{constructor(e){super(e,{code:$d.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}};Object.defineProperty($d,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});fa=class fa extends an{constructor(e){super(e,{code:fa.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}};Object.defineProperty(fa,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});Nd=class Nd extends an{constructor(e){super(e,{code:Nd.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}};Object.defineProperty(Nd,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});zd=class zd extends an{constructor(e){super(e,{code:zd.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}};Object.defineProperty(zd,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});Bd=class Bd extends an{constructor(e){super(e,{code:Bd.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}};Object.defineProperty(Bd,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});Ld=class Ld extends an{constructor(e){super(e,{code:Ld.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}};Object.defineProperty(Ld,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});Dd=class Dd extends an{constructor(e){super(e,{code:Dd.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}};Object.defineProperty(Dd,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});ma=class ma extends an{constructor(e){super(e,{code:ma.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}};Object.defineProperty(ma,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});Ud=class Ud extends an{constructor(e){super(e,{code:Ud.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}};Object.defineProperty(Ud,"code",{enumerable:!0,configurable:!0,writable:!0,value:7000});ME=class ME extends sn{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}});var rL="0.1.1";function nL(){return rL}var oL=()=>{};function iL(e,t){if(t?.(e))return e;if(e&&typeof e==="object"&&"cause"in e&&e.cause)return iL(e.cause,t);return t?null:e}var Pe;var Qn=V(()=>{oL();Pe=class Pe extends Error{static setStaticOptions(e){Pe.prototype.docsOrigin=e.docsOrigin,Pe.prototype.showVersion=e.showVersion,Pe.prototype.version=e.version}constructor(e,t={}){let r=(()=>{if(t.cause instanceof Pe){if(t.cause.details)return t.cause.details;if(t.cause.shortMessage)return t.cause.shortMessage}if(t.cause&&"details"in t.cause&&typeof t.cause.details==="string")return t.cause.details;if(t.cause?.message)return t.cause.message;return t.details})(),n=(()=>{if(t.cause instanceof Pe)return t.cause.docsPath||t.docsPath;return t.docsPath})(),o=t.docsOrigin??Pe.prototype.docsOrigin,i=`${o}${n??""}`,s=Boolean(t.version??Pe.prototype.showVersion),a=t.version??Pe.prototype.version,c=[e||"An error occurred.",...t.metaMessages?["",...t.metaMessages]:[],...r||n||s?["",r?`Details: ${r}`:void 0,n?`See: ${i}`:void 0,s?`Version: ${a}`:void 0]:[]].filter((d)=>typeof d==="string").join(`
|
|
62
|
+
`);super(c,t.cause?{cause:t.cause}:void 0);Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=t.cause,this.details=r,this.docs=i,this.docsOrigin=o,this.docsPath=n,this.shortMessage=e,this.showVersion=s,this.version=a}walk(e){return iL(this,e)}};Object.defineProperty(Pe,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${nL()}`}});(()=>{Pe.setStaticOptions(Pe.defaultStaticOptions)})()});function jd(e,t){if(Xn(e)>t)throw new zE({givenSize:Xn(e),maxSize:t})}function sL(e,t){if(typeof t==="number"&&t>0&&t>Xn(e)-1)throw new Cy({offset:t,position:"start",size:Xn(e)})}function aL(e,t,r){if(typeof t==="number"&&typeof r==="number"&&Xn(e)!==r-t)throw new Cy({offset:r,position:"end",size:Xn(e)})}function $E(e){if(e>=as.zero&&e<=as.nine)return e-as.zero;if(e>=as.A&&e<=as.F)return e-(as.A-10);if(e>=as.a&&e<=as.f)return e-(as.a-10);return}function cL(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new BE({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let i=0;i<n;i++){let s=r==="right";o[s?i:n-i-1]=e[s?i:e.length-i-1]}return o}function NE(e,t={}){let{dir:r="left"}=t,n=e,o=0;for(let i=0;i<n.length-1;i++)if(n[r==="left"?i:n.length-i-1].toString()==="0")o++;else break;return n=r==="left"?n.slice(o):n.slice(0,n.length-o),n}var as;var uL=V(()=>{qd();as={zero:48,nine:57,A:65,F:70,a:97,f:102}});function Hd(e,t){if(sr(e)>t)throw new UE({givenSize:sr(e),maxSize:t})}function dL(e,t){if(typeof t==="number"&&t>0&&t>sr(e)-1)throw new My({offset:t,position:"start",size:sr(e)})}function lL(e,t,r){if(typeof t==="number"&&typeof r==="number"&&sr(e)!==r-t)throw new My({offset:r,position:"end",size:sr(e)})}function LE(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new FE({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}var DE=V(()=>{wn()});function $y(e,t,r){return JSON.stringify(e,(n,o)=>{if(typeof t==="function")return t(n,o);if(typeof o==="bigint")return o.toString()+"#__bigint";return o},r)}function mL(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")return jE(e);return Fae(e)}function Fae(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function jE(e,t={}){let{size:r}=t,n=e;if(r)Hd(e,r),n=si(e,r);let o=n.slice(2);if(o.length%2)o=`0${o}`;let i=o.length/2,s=new Uint8Array(i);for(let a=0,c=0;a<i;a++){let d=$E(o.charCodeAt(c++)),l=$E(o.charCodeAt(c++));if(d===void 0||l===void 0)throw new Pe(`Invalid byte sequence ("${o[c-2]}${o[c-1]}" in "${o}").`);s[a]=d<<4|l}return s}function hL(e,t={}){let{size:r}=t,n=Uae.encode(e);if(typeof r==="number")return jd(n,r),jae(n,r);return n}function jae(e,t){return cL(e,{dir:"right",size:t})}function Xn(e){return e.length}function gL(e,t,r,n={}){let{strict:o}=n;sL(e,t);let i=e.slice(t,r);if(o)aL(i,t,r);return i}function yL(e,t={}){let{size:r}=t;if(typeof r<"u")jd(e,r);let n=Ur(e,t);return HE(n,t)}function bL(e,t={}){let{size:r}=t,n=e;if(typeof r<"u")jd(n,r),n=qE(n);if(n.length>1||n[0]>1)throw new _L(n);return Boolean(n[0])}function ii(e,t={}){let{size:r}=t;if(typeof r<"u")jd(e,r);let n=Ur(e,t);return Ny(n,t)}function xL(e,t={}){let{size:r}=t,n=e;if(typeof r<"u")jd(n,r),n=qae(n);return Dae.decode(n)}function qE(e){return NE(e,{dir:"left"})}function qae(e){return NE(e,{dir:"right"})}var Dae,Uae,_L,zE,Cy,BE;var qd=V(()=>{Qn();wn();uL();DE();Dae=new TextDecoder,Uae=new TextEncoder;_L=class _L extends Pe{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}};zE=class zE extends Pe{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}};Cy=class Cy extends Pe{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"})}};BE=class BE extends Pe{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function Vae(e,t={}){let{strict:r=!1}=t;if(!e)throw new GE(e);if(typeof e!=="string")throw new GE(e);if(r){if(!/^0x[0-9a-fA-F]*$/.test(e))throw new VE(e)}if(!e.startsWith("0x"))throw new VE(e)}function _r(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function wL(e){if(e instanceof Uint8Array)return Ur(e);if(Array.isArray(e))return Ur(new Uint8Array(e));return e}function zy(e,t={}){let r=`0x${Number(e)}`;if(typeof t.size==="number")return Hd(r,t.size),cs(r,t.size);return r}function Ur(e,t={}){let r="";for(let o=0;o<e.length;o++)r+=Gae[e[o]];let n=`0x${r}`;if(typeof t.size==="number")return Hd(n,t.size),si(n,t.size);return n}function rr(e,t={}){let{signed:r,size:n}=t,o=BigInt(e),i;if(n)if(r)i=(1n<<BigInt(n)*8n-1n)-1n;else i=2n**(BigInt(n)*8n)-1n;else if(typeof e==="number")i=BigInt(Number.MAX_SAFE_INTEGER);let s=typeof i==="bigint"&&r?-i-1n:0;if(i&&o>i||o<s){let d=typeof e==="bigint"?"n":"";throw new By({max:i?`${i}${d}`:void 0,min:`${s}${d}`,signed:r,size:n,value:`${e}${d}`})}let c=`0x${(r&&o<0?BigInt.asUintN(n*8,BigInt(o)):o).toString(16)}`;if(n)return cs(c,n);return c}function Gd(e,t={}){return Ur(Hae.encode(e),t)}function cs(e,t){return LE(e,{dir:"left",size:t})}function si(e,t){return LE(e,{dir:"right",size:t})}function Fr(e,t,r,n={}){let{strict:o}=n;dL(e,t);let i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;if(o)lL(i,t,r);return i}function sr(e){return Math.ceil((e.length-2)/2)}function HE(e,t={}){let{signed:r}=t;if(t.size)Hd(e,t.size);let n=BigInt(e);if(!r)return n;let o=(e.length-2)/2,i=(1n<<BigInt(o)*8n)-1n,s=i>>1n;if(n<=s)return n;return n-i-1n}function Ny(e,t={}){let{signed:r,size:n}=t;if(!r&&!n)return Number(e);return Number(HE(e,t))}function ZE(e,t={}){let{strict:r=!1}=t;try{return Vae(e,{strict:r}),!0}catch{return!1}}var Hae,Gae,By,GE,VE,UE,My,FE;var wn=V(()=>{Qn();DE();Hae=new TextEncoder,Gae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));By=class By extends Pe{constructor({max:e,min:t,signed:r,size:n,value:o}){super(`Number \`${o}\` is not in safe${n?` ${n*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}};GE=class GE extends Pe{constructor(e){super(`Value \`${typeof e==="object"?$y(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}};VE=class VE extends Pe{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}};UE=class UE extends Pe{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};My=class My extends Pe{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}};FE=class FE extends Pe{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function SL(e){return{address:e.address,amount:rr(e.amount),index:rr(e.index),validatorIndex:rr(e.validatorIndex)}}var vL=V(()=>{wn()});function Ly(e){return{...typeof e.baseFeePerGas==="bigint"&&{baseFeePerGas:rr(e.baseFeePerGas)},...typeof e.blobBaseFee==="bigint"&&{blobBaseFee:rr(e.blobBaseFee)},...typeof e.feeRecipient==="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit==="bigint"&&{gasLimit:rr(e.gasLimit)},...typeof e.number==="bigint"&&{number:rr(e.number)},...typeof e.prevRandao==="bigint"&&{prevRandao:rr(e.prevRandao)},...typeof e.time==="bigint"&&{time:rr(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(SL)}}}var WE=V(()=>{wn();vL()});var EL="0x82ad56cb";var Dy="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",PL="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",AL="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",zc="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";function Bc(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let o=t.find((s)=>("type"in s)&&s.type==="constructor");if(!o)throw new gT({docsPath:KE});if(!("inputs"in o))throw new K0({docsPath:KE});if(!o.inputs||o.inputs.length===0)throw new K0({docsPath:KE});let i=nn(o.inputs,r);return Qt([n,i])}var KE="/docs/contract/encodeDeployData";var Uy=V(()=>{ir();Qi()});function wr(e,t){if(!ht(e,{strict:!1}))throw new Ft({address:e});if(!ht(t,{strict:!1}))throw new Ft({address:t});return e.toLowerCase()===t.toLowerCase()}var us=V(()=>{ei();Cn()});function zn(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o}=e;if(o!==void 0&&!t)throw new C("`requireCanonical` can only be provided when `blockHash` is set.");if(t)return o?{blockHash:t,requireCanonical:o}:{blockHash:t};if(typeof r==="bigint")return H(r);return n??"latest"}var Lc=V(()=>{He();Fe()});var ai,Ro,im,sm,am,cm,um,dm,lm,pm,ds,Oo;var ls=V(()=>{gd();He();ai=class ai extends C{constructor({cause:e,message:t}={}){let r=t?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${r?`with reason: ${r}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}};Object.defineProperty(ai,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ai,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});Ro=class Ro extends C{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${mr(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}};Object.defineProperty(Ro,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});im=class im extends C{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${mr(t)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}};Object.defineProperty(im,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});sm=class sm extends C{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}};Object.defineProperty(sm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});am=class am extends C{constructor({cause:e,nonce:t}={}){super([`Nonce provided for the transaction ${t?`(${t}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
|
|
63
63
|
`),{cause:e,name:"NonceTooLowError"})}};Object.defineProperty(am,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});cm=class cm extends C{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}};Object.defineProperty(cm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});um=class um extends C{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
|
|
64
64
|
`),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(um,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});dm=class dm extends C{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}};Object.defineProperty(dm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});lm=class lm extends C{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}};Object.defineProperty(lm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});pm=class pm extends C{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(pm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});ds=class ds extends C{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${mr(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${mr(r)} gwei`:""}).`].join(`
|
|
65
|
-
`),{cause:e,name:"TipAboveFeeCapError"})}};Object.defineProperty(ds,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Oo=class Oo extends C{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}});function ha(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof C?e.walk((o)=>o?.code===ai.code):e;if(n instanceof C)return new ai({cause:e,message:n.details});if(ai.nodeMessage.test(r))return new ai({cause:e,message:e.details});if(Ro.nodeMessage.test(r))return new Ro({cause:e,maxFeePerGas:t?.maxFeePerGas});if(im.nodeMessage.test(r))return new im({cause:e,maxFeePerGas:t?.maxFeePerGas});if(sm.nodeMessage.test(r))return new sm({cause:e,nonce:t?.nonce});if(am.nodeMessage.test(r))return new am({cause:e,nonce:t?.nonce});if(cm.nodeMessage.test(r))return new cm({cause:e,nonce:t?.nonce});if(um.nodeMessage.test(r))return new um({cause:e});if(dm.nodeMessage.test(r))return new dm({cause:e,gas:t?.gas});if(lm.nodeMessage.test(r))return new lm({cause:e,gas:t?.gas});if(pm.nodeMessage.test(r))return new pm({cause:e});if(ds.nodeMessage.test(r))return new ds({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Oo({cause:e})}var fm=V(()=>{He();ls()});function Fy(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Oo)return e;return o})();return new Oc(n,{docsPath:t,...r})}var YE=V(()=>{os();ls();fm()});function eo(e,{format:t}){if(!t)return{};let r={};function n(i){let s=Object.keys(i);for(let a of s){if(a in e)r[a]=e[a];if(i[a]&&typeof i[a]==="object"&&!Array.isArray(i[a]))n(i[a])}}let o=t(e||{});return n(o),r}function jr(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=Kae(e.authorizationList);if(typeof e.accessList<"u")r.accessList=e.accessList;if(typeof e.blobVersionedHashes<"u")r.blobVersionedHashes=e.blobVersionedHashes;if(typeof e.blobs<"u")if(typeof e.blobs[0]!=="string")r.blobs=e.blobs.map((n)=>mt(n));else r.blobs=e.blobs;if(typeof e.data<"u")r.data=e.data;if(e.account)r.from=e.account.address;if(typeof e.from<"u")r.from=e.from;if(typeof e.gas<"u")r.gas=H(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=H(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=H(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=H(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=H(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=H(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=Wae[e.type];if(typeof e.value<"u")r.value=H(e.value);return r}function Kae(e){return e.map((t)=>({address:t.address,r:t.r?H(BigInt(t.r)):t.r,s:t.s?H(BigInt(t.s)):t.s,chainId:H(t.chainId),nonce:H(t.nonce),...typeof t.yParity<"u"?{yParity:H(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:H(t.v)}:{}}))}var Wae;var ps=V(()=>{Fe();Wae={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function Vd(){let e=()=>{return},t=()=>{return};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Zd({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let i=async()=>{let l=c();s();let p=l.map(({args:m})=>m);if(p.length===0)return;e(p).then((m)=>{if(o&&Array.isArray(m))m.sort(o);for(let h=0;h<l.length;h++){let{resolve:y}=l[h];y?.([m[h],m])}}).catch((m)=>{for(let h=0;h<l.length;h++){let{reject:y}=l[h];y?.(m)}})},s=()=>JE.delete(t),a=()=>c().map(({args:l})=>l),c=()=>JE.get(t)||[],d=(l)=>JE.set(t,[...c(),l]);return{flush:s,async schedule(l){let{promise:p,resolve:m,reject:h}=Vd();if(r?.([...a(),l]))i();if(c().length>0)return d({args:l,resolve:m,reject:h}),p;return d({args:l,resolve:m,reject:h}),setTimeout(i,n),p}}}var JE;var jy=V(()=>{JE=new Map});function IL(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new ey({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new ey({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function Yae(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:i}=e,s={};if(i!==void 0)s.code=i;if(t!==void 0)s.balance=H(t);if(r!==void 0)s.nonce=H(r);if(n!==void 0)s.state=IL(n);if(o!==void 0){if(s.state)throw new _E;s.stateDiff=IL(o)}return s}function Wd(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!ht(r,{strict:!1}))throw new Ft({address:r});if(t[r])throw new xE({address:r});t[r]=Yae(n)}return t}var qy=V(()=>{ei();ty();wE();Cn();Fe()});var ZAe,WAe,KAe,YAe,JAe,QAe,XAe,eIe,tIe,rIe,nIe,oIe,iIe,sIe,aIe,cIe,uIe,dIe,lIe,pIe,fIe,mIe,hIe,gIe,yIe,bIe,xIe,_Ie,wIe,SIe,vIe,TIe,EIe,PIe,AIe,IIe,kIe,RIe,OIe,CIe,MIe,$Ie,NIe,zIe,BIe,LIe,DIe,UIe,FIe,jIe,qIe,HIe,GIe,VIe,ZIe,WIe,KIe,YIe,JIe,QIe,XIe,eke,tke,rke,nke,oke,ike,ske,ake,cke,uke,dke,lke,pke,fke,mke,hke,gke,yke,bke,xke,_ke,wke,Ske,vke,Tke,Eke,Pke,Ake,Ike,kke,Rke,Oke,Cke,Mke,Kd;var QE=V(()=>{ZAe=2n**(8n-1n)-1n,WAe=2n**(16n-1n)-1n,KAe=2n**(24n-1n)-1n,YAe=2n**(32n-1n)-1n,JAe=2n**(40n-1n)-1n,QAe=2n**(48n-1n)-1n,XAe=2n**(56n-1n)-1n,eIe=2n**(64n-1n)-1n,tIe=2n**(72n-1n)-1n,rIe=2n**(80n-1n)-1n,nIe=2n**(88n-1n)-1n,oIe=2n**(96n-1n)-1n,iIe=2n**(104n-1n)-1n,sIe=2n**(112n-1n)-1n,aIe=2n**(120n-1n)-1n,cIe=2n**(128n-1n)-1n,uIe=2n**(136n-1n)-1n,dIe=2n**(144n-1n)-1n,lIe=2n**(152n-1n)-1n,pIe=2n**(160n-1n)-1n,fIe=2n**(168n-1n)-1n,mIe=2n**(176n-1n)-1n,hIe=2n**(184n-1n)-1n,gIe=2n**(192n-1n)-1n,yIe=2n**(200n-1n)-1n,bIe=2n**(208n-1n)-1n,xIe=2n**(216n-1n)-1n,_Ie=2n**(224n-1n)-1n,wIe=2n**(232n-1n)-1n,SIe=2n**(240n-1n)-1n,vIe=2n**(248n-1n)-1n,TIe=2n**(256n-1n)-1n,EIe=-(2n**(8n-1n)),PIe=-(2n**(16n-1n)),AIe=-(2n**(24n-1n)),IIe=-(2n**(32n-1n)),kIe=-(2n**(40n-1n)),RIe=-(2n**(48n-1n)),OIe=-(2n**(56n-1n)),CIe=-(2n**(64n-1n)),MIe=-(2n**(72n-1n)),$Ie=-(2n**(80n-1n)),NIe=-(2n**(88n-1n)),zIe=-(2n**(96n-1n)),BIe=-(2n**(104n-1n)),LIe=-(2n**(112n-1n)),DIe=-(2n**(120n-1n)),UIe=-(2n**(128n-1n)),FIe=-(2n**(136n-1n)),jIe=-(2n**(144n-1n)),qIe=-(2n**(152n-1n)),HIe=-(2n**(160n-1n)),GIe=-(2n**(168n-1n)),VIe=-(2n**(176n-1n)),ZIe=-(2n**(184n-1n)),WIe=-(2n**(192n-1n)),KIe=-(2n**(200n-1n)),YIe=-(2n**(208n-1n)),JIe=-(2n**(216n-1n)),QIe=-(2n**(224n-1n)),XIe=-(2n**(232n-1n)),eke=-(2n**(240n-1n)),tke=-(2n**(248n-1n)),rke=-(2n**(256n-1n)),nke=2n**8n-1n,oke=2n**16n-1n,ike=2n**24n-1n,ske=2n**32n-1n,ake=2n**40n-1n,cke=2n**48n-1n,uke=2n**56n-1n,dke=2n**64n-1n,lke=2n**72n-1n,pke=2n**80n-1n,fke=2n**88n-1n,mke=2n**96n-1n,hke=2n**104n-1n,gke=2n**112n-1n,yke=2n**120n-1n,bke=2n**128n-1n,xke=2n**136n-1n,_ke=2n**144n-1n,wke=2n**152n-1n,Ske=2n**160n-1n,vke=2n**168n-1n,Tke=2n**176n-1n,Eke=2n**184n-1n,Pke=2n**192n-1n,Ake=2n**200n-1n,Ike=2n**208n-1n,kke=2n**216n-1n,Rke=2n**224n-1n,Oke=2n**232n-1n,Cke=2n**240n-1n,Mke=2n**248n-1n,Kd=2n**256n-1n});function Sr(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,i=t?ze(t):void 0;if(i&&!ht(i.address))throw new Ft({address:i.address});if(o&&!ht(o))throw new Ft({address:o});if(r&&r>Kd)throw new Ro({maxFeePerGas:r});if(n&&r&&n>r)throw new ds({maxFeePerGas:r,maxPriorityFeePerGas:n})}var ci=V(()=>{QE();ei();ls();Cn()});var XE,eP,tP;var kL=V(()=>{He();XE=class XE extends C{constructor({callbackSelector:e,cause:t,data:r,extraData:n,sender:o,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map((s)=>` ${Rc(s)}`)],` Sender: ${o}`,` Data: ${r}`,` Callback selector: ${e}`,` Extra data: ${n}`].flat(),name:"OffchainLookupError"})}};eP=class eP extends C{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${Rc(t)}`,`Response: ${Je(e)}`],name:"OffchainLookupResponseMalformedError"})}};tP=class tP extends C{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}});async function OL(e,{blockNumber:t,blockTag:r,data:n,requestOptions:o,to:i}){let{args:s}=Ey({data:n,abi:[Jae]}),[a,c,d,l,p]=s,{ccipRead:m}=e,h=m&&typeof m?.request==="function"?m.request:Qae;try{if(!wr(i,a))throw new tP({sender:a,to:i});let y=c.includes(is)?await CE({data:d,ccipRequest:(_)=>h({..._,requestOptions:o})}):await h({data:d,requestOptions:o,sender:a,urls:c}),{data:x}=await Sn(e,{blockNumber:t,blockTag:r,data:fr([l,nn([{type:"bytes"},{type:"bytes"}],[y,p])]),requestOptions:o,to:i});return x}catch(y){if(o?.signal?.aborted)throw Nr(o.signal);if(_n(y))throw y;throw new XE({callbackSelector:l,cause:y,data:n,extraData:p,sender:a,urls:c})}}async function Qae({data:e,requestOptions:t,sender:r,urls:n}){let o=Error("An unknown error occurred.");for(let i=0;i<n.length;i++){if(t?.signal?.aborted)throw Nr(t.signal);let s=n[i],a=s.includes("{data}")?"GET":"POST",c=a==="POST"?{data:e,sender:r}:void 0,d=a==="POST"?{"Content-Type":"application/json"}:{};try{let l=await fetch(s.replace("{sender}",r.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:a,...t?.signal?{signal:t.signal}:{}}),p;if(l.headers.get("Content-Type")?.startsWith("application/json"))p=(await l.json()).data;else p=await l.text();if(!l.ok){o=new Io({body:c,details:p?.error?Je(p.error):l.statusText,headers:l.headers,status:l.status,url:s});continue}if(!Kt(p)){o=new eP({result:p,url:s});continue}return p}catch(l){if(t?.signal?.aborted)throw Nr(t.signal);if(_n(l))throw l;o=new Io({body:c,details:l.message,url:s})}}throw o}var RL="0x556f1830",Jae;var CL=V(()=>{ga();kL();Mc();gE();Qi();us();rm();Jae={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});async function Sn(e,t){let{account:r=e.account,authorizationList:n,batch:o=Boolean(e.batch?.multicall),blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:d,blobs:l,blockOverrides:p,code:m,data:h,factory:y,factoryData:x,gas:_,gasPrice:w,maxFeePerBlobGas:A,maxFeePerGas:S,maxPriorityFeePerGas:v,nonce:P,requestOptions:k,to:O,value:N,stateOverride:j,...R}=t,K=r?ze(r):void 0;if(m&&(y||x))throw new C("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(m&&O)throw new C("Cannot provide both `code` & `to` as parameters.");let Z=m&&h,re=y&&x&&O&&h,pe=Z||re,U=(()=>{if(Z)return NL({code:m,data:h});if(re)return oce({data:h,factory:y,factoryData:x,to:O});return h})();try{Sr(t);let ee=zn({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),me=p?Ly(p):void 0,z=Wd(j),F=e.chain?.formatters?.transactionRequest?.format,we=(F||jr)({...eo(R,{format:F}),accessList:d,account:K,authorizationList:n,blobs:l,data:U,gas:_,gasPrice:w,maxFeePerBlobGas:A,maxFeePerGas:S,maxPriorityFeePerGas:v,nonce:P,to:pe?void 0:O,value:N},"call");if(o&&Xae({request:we})&&!me&&i===void 0)try{let{deployless:Te=!1}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},Pe=$L(e,{blockNumber:s,deployless:Te});if(!Pe||!nce(z,Pe))return await rce(e,{...we,blockHash:i,blockNumber:s,blockTag:a,multicallAddress:Pe,requestOptions:k,requireCanonical:c,rpcStateOverride:z})}catch(Te){if(!(Te instanceof Sy)&&!(Te instanceof fd))throw Te}let te=(()=>{let Te=[we,ee];if(z&&me)return[...Te,z,me];if(z)return[...Te,z];if(me)return[...Te,{},me];return Te})(),$e=await e.request({method:"eth_call",params:te},k);if($e==="0x")return{data:void 0};return{data:$e}}catch(ee){if(k?.signal?.aborted)throw Nr(k.signal);if(_n(ee))throw ee;let me=ice(ee);await Promise.resolve().then(() => CL());if(e.ccipRead!==!1&&me?.slice(0,10)===RL&&O)return{data:await OL(e,{data:me,requestOptions:k,to:O})};if(pe&&me?.slice(0,10)==="0x101bb98d")throw new IE({factory:y});throw Fy(ee,{...t,account:K,chain:e.chain})}}function Xae({request:e}){let{data:t,to:r,...n}=e;if(!t)return!1;if(t.startsWith(EL))return!1;if(!r)return!1;if(Object.values(n).filter((o)=>typeof o<"u").length>0)return!1;return!0}function tce(e){if(!e)return"default";let t=ML.get(e);if(t!==void 0)return t;let r=ece++;return ML.set(e,r),r}async function rce(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:d,multicallAddress:l,requestOptions:p,rpcStateOverride:m,to:h}=t,y=l!==void 0?l:$L(e,{blockNumber:s,deployless:n}),x=zn({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),_=typeof x==="string"?x:JSON.stringify(x),w=m?`.${JSON.stringify(m)}`:"",{schedule:A}=Zd({id:`${e.uid}.${_}.${tce(p)}${w}`,wait:o,shouldSplitBatch(P){return P.reduce((O,{data:N})=>O+(N.length-2),0)>r*2},fn:async(P)=>{let k=P.map((R)=>({allowFailure:!0,callData:R.data,target:R.to})),O=At({abi:Zn,args:[k],functionName:"aggregate3"}),N={...y===null?{data:NL({code:zc,data:O})}:{to:y,data:O}},j=await e.request({method:"eth_call",params:m?[N,x,m]:[N,x]},p);return Dr({abi:Zn,args:[k],functionName:"aggregate3",data:j||"0x"})}}),[{returnData:S,success:v}]=await A({data:d,to:h});if(!v)throw new ns({data:S});if(S==="0x")return{data:void 0};return{data:S}}function $L(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return Yn({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new Sy}function nce(e,t){if(!e)return!1;return Object.keys(e).some((r)=>wr(r,t))}function NL(e){let{code:t,data:r}=e;return Bc({abi:by(["constructor(bytes, bytes)"]),bytecode:Dy,args:[t,r]})}function oce(e){let{data:t,factory:r,factoryData:n,to:o}=e;return Bc({abi:by(["constructor(address, bytes, address, bytes)"]),bytecode:PL,args:[o,t,r,n]})}function ice(e){if(!(e instanceof C))return;let t=e.walk();return typeof t?.data==="object"?t.data?.data:t.data}var ece=0,ML;var ga=V(()=>{Kf();WE();Mr();He();Jf();os();rs();Uy();xn();us();Lc();Ac();YE();ps();jy();qy();ci();ML=new WeakMap});var aP,cP=(e,t,r)=>new aP(e,t).update(r).digest();var KL=V(()=>{hc();aP=class aP extends Sf{constructor(e,t){super();this.finished=!1,this.destroyed=!1,Q4(e);let r=wf(t);if(this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ui(o)}update(e){return Yu(this),this.iHash.update(e),this}digestInto(e){Yu(this),mc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:s}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};cP.create=(e,t)=>new aP(e,t)});function YL(e){if(e.lowS!==void 0)Yo("lowS",e.lowS);if(e.prehash!==void 0)Yo("prehash",e.prehash)}function fce(e){let t=If(e);Hi(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof r!=="object"||typeof r.beta!=="bigint"||typeof r.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function uP(e,t){return ra(xc(e,t))}function hce(e){let t=fce(e),{Fp:r}=t,n=Gi(t.n,t.nBitLength),o=t.toBytes||((S,v,P)=>{let k=v.toAffine();return na(Uint8Array.from([4]),r.toBytes(k.x),r.toBytes(k.y))}),i=t.fromBytes||((S)=>{let v=S.subarray(1),P=r.fromBytes(v.subarray(0,r.BYTES)),k=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x:P,y:k}});function s(S){let{a:v,b:P}=t,k=r.sqr(S),O=r.mul(k,S);return r.add(r.add(O,r.mul(S,v)),P)}function a(S,v){let P=r.sqr(v),k=s(S);return r.eql(P,k)}if(!a(t.Gx,t.Gy))throw Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,dP),mce),d=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,d)))throw Error("bad curve params: a or b");function l(S){return O0(S,vr,t.n)}function p(S){let{allowedPrivateKeyLengths:v,nByteLength:P,wrapPrivateKey:k,n:O}=t;if(v&&typeof S!=="bigint"){if(Ju(S))S=ra(S);if(typeof S!=="string"||!v.includes(S.length))throw Error("invalid private key");S=S.padStart(P*2,"0")}let N;try{N=typeof S==="bigint"?S:qi(Gt("private key",S,P))}catch(j){throw Error("invalid private key, expected hex or "+P+" bytes, got "+typeof S)}if(k)N=Et(N,O);return Rn("private key",N,vr,O),N}function m(S){if(!(S instanceof x))throw Error("ProjectivePoint expected")}let h=Xu((S,v)=>{let{px:P,py:k,pz:O}=S;if(r.eql(O,r.ONE))return{x:P,y:k};let N=S.is0();if(v==null)v=N?r.ONE:r.inv(O);let j=r.mul(P,v),R=r.mul(k,v),K=r.mul(O,v);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(K,r.ONE))throw Error("invZ was invalid");return{x:j,y:R}}),y=Xu((S)=>{if(S.is0()){if(t.allowInfinityPoint&&!r.is0(S.py))return;throw Error("bad point: ZERO")}let{x:v,y:P}=S.toAffine();if(!r.isValid(v)||!r.isValid(P))throw Error("bad point: x or y not FE");if(!a(v,P))throw Error("bad point: equation left != right");if(!S.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class x{constructor(S,v,P){if(S==null||!r.isValid(S))throw Error("x required");if(v==null||!r.isValid(v)||r.is0(v))throw Error("y required");if(P==null||!r.isValid(P))throw Error("z required");this.px=S,this.py=v,this.pz=P,Object.freeze(this)}static fromAffine(S){let{x:v,y:P}=S||{};if(!S||!r.isValid(v)||!r.isValid(P))throw Error("invalid affine point");if(S instanceof x)throw Error("projective point not allowed");let k=(O)=>r.eql(O,r.ZERO);if(k(v)&&k(P))return x.ZERO;return new x(v,P,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let v=ed(r,S.map((P)=>P.pz));return S.map((P,k)=>P.toAffine(v[k])).map(x.fromAffine)}static fromHex(S){let v=x.fromAffine(i(Gt("pointHex",S)));return v.assertValidity(),v}static fromPrivateKey(S){return x.BASE.multiply(p(S))}static msm(S,v){return $0(x,n,S,v)}_setWindowSize(S){A.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw Error("Field doesn't support isOdd")}equals(S){m(S);let{px:v,py:P,pz:k}=this,{px:O,py:N,pz:j}=S,R=r.eql(r.mul(v,j),r.mul(O,k)),K=r.eql(r.mul(P,j),r.mul(N,k));return R&&K}negate(){return new x(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:v}=t,P=r.mul(v,dP),{px:k,py:O,pz:N}=this,{ZERO:j,ZERO:R,ZERO:K}=r,Z=r.mul(k,k),re=r.mul(O,O),pe=r.mul(N,N),U=r.mul(k,O);return U=r.add(U,U),K=r.mul(k,N),K=r.add(K,K),j=r.mul(S,K),R=r.mul(P,pe),R=r.add(j,R),j=r.sub(re,R),R=r.add(re,R),R=r.mul(j,R),j=r.mul(U,j),K=r.mul(P,K),pe=r.mul(S,pe),U=r.sub(Z,pe),U=r.mul(S,U),U=r.add(U,K),K=r.add(Z,Z),Z=r.add(K,Z),Z=r.add(Z,pe),Z=r.mul(Z,U),R=r.add(R,Z),pe=r.mul(O,N),pe=r.add(pe,pe),Z=r.mul(pe,U),j=r.sub(j,Z),K=r.mul(pe,re),K=r.add(K,K),K=r.add(K,K),new x(j,R,K)}add(S){m(S);let{px:v,py:P,pz:k}=this,{px:O,py:N,pz:j}=S,{ZERO:R,ZERO:K,ZERO:Z}=r,re=t.a,pe=r.mul(t.b,dP),U=r.mul(v,O),ee=r.mul(P,N),me=r.mul(k,j),z=r.add(v,P),F=r.add(O,N);z=r.mul(z,F),F=r.add(U,ee),z=r.sub(z,F),F=r.add(v,k);let Y=r.add(O,j);return F=r.mul(F,Y),Y=r.add(U,me),F=r.sub(F,Y),Y=r.add(P,k),R=r.add(N,j),Y=r.mul(Y,R),R=r.add(ee,me),Y=r.sub(Y,R),Z=r.mul(re,F),R=r.mul(pe,me),Z=r.add(R,Z),R=r.sub(ee,Z),Z=r.add(ee,Z),K=r.mul(R,Z),ee=r.add(U,U),ee=r.add(ee,U),me=r.mul(re,me),F=r.mul(pe,F),ee=r.add(ee,me),me=r.sub(U,me),me=r.mul(re,me),F=r.add(F,me),U=r.mul(ee,F),K=r.add(K,U),U=r.mul(Y,F),R=r.mul(z,R),R=r.sub(R,U),U=r.mul(z,ee),Z=r.mul(Y,Z),Z=r.add(Z,U),new x(R,K,Z)}subtract(S){return this.add(S.negate())}is0(){return this.equals(x.ZERO)}wNAF(S){return A.wNAFCached(this,S,x.normalizeZ)}multiplyUnsafe(S){let{endo:v,n:P}=t;Rn("scalar",S,ms,P);let k=x.ZERO;if(S===ms)return k;if(this.is0()||S===vr)return this;if(!v||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,S,x.normalizeZ);let{k1neg:O,k1:N,k2neg:j,k2:R}=v.splitScalar(S),K=k,Z=k,re=this;while(N>ms||R>ms){if(N&vr)K=K.add(re);if(R&vr)Z=Z.add(re);re=re.double(),N>>=vr,R>>=vr}if(O)K=K.negate();if(j)Z=Z.negate();return Z=new x(r.mul(Z.px,v.beta),Z.py,Z.pz),K.add(Z)}multiply(S){let{endo:v,n:P}=t;Rn("scalar",S,vr,P);let k,O;if(v){let{k1neg:N,k1:j,k2neg:R,k2:K}=v.splitScalar(S),{p:Z,f:re}=this.wNAF(j),{p:pe,f:U}=this.wNAF(K);Z=A.constTimeNegate(N,Z),pe=A.constTimeNegate(R,pe),pe=new x(r.mul(pe.px,v.beta),pe.py,pe.pz),k=Z.add(pe),O=re.add(U)}else{let{p:N,f:j}=this.wNAF(S);k=N,O=j}return x.normalizeZ([k,O])[0]}multiplyAndAddUnsafe(S,v,P){let k=x.BASE,O=(j,R)=>R===ms||R===vr||!j.equals(k)?j.multiplyUnsafe(R):j.multiply(R),N=O(this,v).add(O(S,P));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:v}=t;if(S===vr)return!0;if(v)return v(x,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:v}=t;if(S===vr)return this;if(v)return v(x,this);return this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return Yo("isCompressed",S),this.assertValidity(),o(x,this,S)}toHex(S=!0){return Yo("isCompressed",S),ra(this.toRawBytes(S))}}x.BASE=new x(t.Gx,t.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO);let{endo:_,nBitLength:w}=t,A=M0(x,_?Math.ceil(w/2):w);return{CURVE:t,ProjectivePoint:x,normPrivateKeyToScalar:p,weierstrassEquation:s,isWithinCurveOrder:l}}function gce(e){let t=If(e);return Hi(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function QL(e){let t=gce(e),{Fp:r,n,nByteLength:o,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(U){return Et(U,n)}function d(U){return C0(U,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:p,weierstrassEquation:m,isWithinCurveOrder:h}=hce({...t,toBytes(U,ee,me){let z=ee.toAffine(),F=r.toBytes(z.x),Y=na;if(Yo("isCompressed",me),me)return Y(Uint8Array.from([ee.hasEvenY()?2:3]),F);else return Y(Uint8Array.from([4]),F,r.toBytes(z.y))},fromBytes(U){let ee=U.length,me=U[0],z=U.subarray(1);if(ee===s&&(me===2||me===3)){let F=qi(z);if(!O0(F,vr,r.ORDER))throw Error("Point is not on curve");let Y=m(F),we;try{we=r.sqrt(Y)}catch(Te){let Pe=Te instanceof Error?": "+Te.message:"";throw Error("Point is not on curve"+Pe)}let te=(we&vr)===vr;if((me&1)===1!==te)we=r.neg(we);return{x:F,y:we}}else if(ee===a&&me===4){let F=r.fromBytes(z.subarray(0,r.BYTES)),Y=r.fromBytes(z.subarray(r.BYTES,2*r.BYTES));return{x:F,y:Y}}else{let F=s,Y=a;throw Error("invalid Point, expected length of "+F+", or uncompressed "+Y+", got "+ee)}}});function y(U){let ee=n>>vr;return U>ee}function x(U){return y(U)?c(-U):U}let _=(U,ee,me)=>qi(U.slice(ee,me));class w{constructor(U,ee,me){if(Rn("r",U,vr,n),Rn("s",ee,vr,n),this.r=U,this.s=ee,me!=null)this.recovery=me;Object.freeze(this)}static fromCompact(U){let ee=o;return U=Gt("compactSignature",U,ee*2),new w(_(U,0,ee),_(U,ee,2*ee))}static fromDER(U){let{r:ee,s:me}=fs.toSig(Gt("DER",U));return new w(ee,me)}assertValidity(){}addRecoveryBit(U){return new w(this.r,this.s,U)}recoverPublicKey(U){let{r:ee,s:me,recovery:z}=this,F=O(Gt("msgHash",U));if(z==null||![0,1,2,3].includes(z))throw Error("recovery id invalid");let Y=z===2||z===3?ee+t.n:ee;if(Y>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let we=(z&1)===0?"02":"03",te=l.fromHex(we+uP(Y,r.BYTES)),$e=d(Y),Te=c(-F*$e),Pe=c(me*$e),tt=l.BASE.multiplyAndAddUnsafe(te,Te,Pe);if(!tt)throw Error("point at infinify");return tt.assertValidity(),tt}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Pf(this.toDERHex())}toDERHex(){return fs.hexFromSig(this)}toCompactRawBytes(){return Pf(this.toCompactHex())}toCompactHex(){let U=o;return uP(this.r,U)+uP(this.s,U)}}let A={isValidPrivateKey(U){try{return p(U),!0}catch(ee){return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{let U=Gv(t.n);return O8(t.randomBytes(U),t.n)},precompute(U=8,ee=l.BASE){return ee._setWindowSize(U),ee.multiply(BigInt(3)),ee}};function S(U,ee=!0){return l.fromPrivateKey(U).toRawBytes(ee)}function v(U){if(typeof U==="bigint")return!1;if(U instanceof l)return!0;let me=Gt("key",U).length,z=r.BYTES,F=z+1,Y=2*z+1;if(t.allowedPrivateKeyLengths||o===F)return;else return me===F||me===Y}function P(U,ee,me=!0){if(v(U)===!0)throw Error("first arg must be private key");if(v(ee)===!1)throw Error("second arg must be public key");return l.fromHex(ee).multiply(p(U)).toRawBytes(me)}let k=t.bits2int||function(U){if(U.length>8192)throw Error("input is too large");let ee=qi(U),me=U.length*8-i;return me>0?ee>>BigInt(me):ee},O=t.bits2int_modN||function(U){return c(k(U))},N=_c(i);function j(U){return Rn("num < 2^"+i,U,ms,N),xc(U,o)}function R(U,ee,me=K){if(["recovered","canonical"].some((q)=>(q in me)))throw Error("sign() legacy options not supported");let{hash:z,randomBytes:F}=t,{lowS:Y,prehash:we,extraEntropy:te}=me;if(Y==null)Y=!0;if(U=Gt("msgHash",U),YL(me),we)U=Gt("prehashed msgHash",z(U));let $e=O(U),Te=p(ee),Pe=[j(Te),j($e)];if(te!=null&&te!==!1){let q=te===!0?F(r.BYTES):te;Pe.push(Gt("extraEntropy",q))}let tt=na(...Pe),yt=$e;function ft(q){let ne=k(q);if(!h(ne))return;let ce=d(ne),he=l.BASE.multiply(ne).toAffine(),Q=c(he.x);if(Q===ms)return;let Be=c(ce*c(yt+Q*Te));if(Be===ms)return;let bt=(he.x===Q?0:2)|Number(he.y&vr),xt=Be;if(Y&&y(Be))xt=x(Be),bt^=1;return new w(Q,xt,bt)}return{seed:tt,k2sig:ft}}let K={lowS:t.lowS,prehash:!1},Z={lowS:t.lowS,prehash:!1};function re(U,ee,me=K){let{seed:z,k2sig:F}=R(U,ee,me),Y=t;return v8(Y.hash.outputLen,Y.nByteLength,Y.hmac)(z,F)}l.BASE._setWindowSize(8);function pe(U,ee,me,z=Z){let F=U;ee=Gt("msgHash",ee),me=Gt("publicKey",me);let{lowS:Y,prehash:we,format:te}=z;if(YL(z),"strict"in z)throw Error("options.strict was renamed to lowS");if(te!==void 0&&te!=="compact"&&te!=="der")throw Error("format must be compact or der");let $e=typeof F==="string"||Ju(F),Te=!$e&&!te&&typeof F==="object"&&F!==null&&typeof F.r==="bigint"&&typeof F.s==="bigint";if(!$e&&!Te)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Pe=void 0,tt;try{if(Te)Pe=new w(F.r,F.s);if($e){try{if(te!=="compact")Pe=w.fromDER(F)}catch(bt){if(!(bt instanceof fs.Err))throw bt}if(!Pe&&te!=="der")Pe=w.fromCompact(F)}tt=l.fromHex(me)}catch(bt){return!1}if(!Pe)return!1;if(Y&&Pe.hasHighS())return!1;if(we)ee=t.hash(ee);let{r:yt,s:ft}=Pe,q=O(ee),ne=d(ft),ce=c(q*ne),he=c(yt*ne),Q=l.BASE.multiplyAndAddUnsafe(tt,ce,he)?.toAffine();if(!Q)return!1;return c(Q.x)===yt}return{CURVE:t,getPublicKey:S,getSharedSecret:P,sign:re,verify:pe,ProjectivePoint:l,Signature:w,utils:A}}var JL,fs,ms,vr,m6e,dP,mce;var XL=V(()=>{Jv();td();Af();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */JL=class JL extends Error{constructor(e=""){super(e)}};fs={Err:JL,_tlv:{encode:(e,t)=>{let{Err:r}=fs;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=Ef(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?Ef(o.length/2|128):"";return Ef(e)+i+o+t},decode(e,t){let{Err:r}=fs,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=t.subarray(n,n+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of d)s=s<<8|l;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=fs;if(e<ms)throw new t("integer: negative integers are not allowed");let r=Ef(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=fs;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return qi(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=fs,o=Gt("signature",e),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:d,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(e){let{_tlv:t,_int:r}=fs,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}};ms=BigInt(0),vr=BigInt(1),m6e=BigInt(2),dP=BigInt(3),mce=BigInt(4)});function yce(e){return{hash:e,hmac:(t,...r)=>cP(e,t,Mv(...r)),randomBytes:I0}}function e9(e,t){let r=(n)=>QL({...e,...yce(n)});return{...r(t),create:r}}var t9=V(()=>{KL();hc();XL();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */});function _ce(e){let t=o9,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),d=e*e*e%t,l=d*d*e%t,p=Vt(l,r,t)*l%t,m=Vt(p,r,t)*l%t,h=Vt(m,lP,t)*d%t,y=Vt(h,o,t)*h%t,x=Vt(y,i,t)*y%t,_=Vt(x,a,t)*x%t,w=Vt(_,c,t)*_%t,A=Vt(w,a,t)*x%t,S=Vt(A,r,t)*l%t,v=Vt(S,s,t)*y%t,P=Vt(v,n,t)*d%t,k=Vt(P,lP,t);if(!pP.eql(pP.sqr(k),e))throw Error("Cannot find square root");return k}var o9,r9,bce,xce,lP,n9=(e,t)=>(e+t/lP)/t,pP,hs;var hm=V(()=>{Bv();t9();td();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */o9=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),r9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),bce=BigInt(0),xce=BigInt(1),lP=BigInt(2);pP=Gi(o9,void 0,void 0,{sqrt:_ce}),hs=e9({a:bce,b:BigInt(7),Fp:pP,n:r9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(e)=>{let t=r9,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-xce*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=n9(i*e,t),c=n9(-n*e,t),d=Et(e-a*r-c*o,t),l=Et(-a*n-c*i,t),p=d>s,m=l>s;if(p)d=t-d;if(m)l=t-l;if(d>s||l>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:p,k1:d,k2neg:m,k2:l}}}},g8)});import{webcrypto as gpe}from"node:crypto";import uG from"node:http";import dG from"node:https";import uu from"node:zlib";import Gk,{PassThrough as Vk,pipeline as du}from"node:stream";import{Buffer as bh}from"node:buffer";function DH(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,"");let t=e.indexOf(",");if(t===-1||t<=4)throw TypeError("malformed data: URI");let r=e.substring(5,t).split(";"),n="",o=!1,i=r[0]||"text/plain",s=i;for(let l=1;l<r.length;l++)if(r[l]==="base64")o=!0;else if(r[l]){if(s+=`;${r[l]}`,r[l].indexOf("charset=")===0)n=r[l].substring(8)}if(!r[0]&&!n.length)s+=";charset=US-ASCII",n="US-ASCII";let a=o?"base64":"ascii",c=unescape(e.substring(t+1)),d=Buffer.from(c,a);return d.type=i,d.typeFull=s,d.charset=n,d}var fk=DH;Zl();dh();import ks,{PassThrough as Ok}from"node:stream";import{types as Ck,deprecate as r1,promisify as eG}from"node:util";import{Buffer as Dn}from"node:buffer";class As extends Error{constructor(e,t){super(e);Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class Tn extends As{constructor(e,t,r){super(e,t);if(r)this.code=this.errno=r.code,this.erroredSysCall=r.syscall}}var lh=Symbol.toStringTag,Xx=(e)=>typeof e==="object"&&typeof e.append==="function"&&typeof e.delete==="function"&&typeof e.get==="function"&&typeof e.getAll==="function"&&typeof e.has==="function"&&typeof e.set==="function"&&typeof e.sort==="function"&&e[lh]==="URLSearchParams",Kl=(e)=>e&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&typeof e.constructor==="function"&&/^(Blob|File)$/.test(e[lh]),Sk=(e)=>typeof e==="object"&&(e[lh]==="AbortSignal"||e[lh]==="EventTarget"),vk=(e,t)=>{let r=new URL(t).hostname,n=new URL(e).hostname;return r===n||r.endsWith(`.${n}`)},Tk=(e,t)=>{let r=new URL(t).protocol,n=new URL(e).protocol;return r===n};var tG=eG(ks.pipeline),un=Symbol("Body internals");class vi{constructor(e,{size:t=0}={}){let r=null;if(e===null)e=null;else if(Xx(e))e=Dn.from(e.toString());else if(Kl(e));else if(Dn.isBuffer(e));else if(Ck.isAnyArrayBuffer(e))e=Dn.from(e);else if(ArrayBuffer.isView(e))e=Dn.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ks);else if(e instanceof Ua)e=wk(e),r=e.type.split("=")[1];else e=Dn.from(String(e));let n=e;if(Dn.isBuffer(e))n=ks.Readable.from(e);else if(Kl(e))n=ks.Readable.from(e.stream());if(this[un]={body:e,stream:n,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof ks)e.on("error",(o)=>{let i=o instanceof As?o:new Tn(`Invalid response body while trying to fetch ${this.url}: ${o.message}`,"system",o);this[un].error=i})}get body(){return this[un].stream}get bodyUsed(){return this[un].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:r}=await t1(this);return e.slice(t,t+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Ua,n=new URLSearchParams(await this.text());for(let[o,i]of n)r.append(o,i);return r}await Promise.resolve().then(() => Rk());return kk(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[un].body&&this[un].body.type||"",t=await this.arrayBuffer();return new Si([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await t1(this);return new TextDecoder().decode(e)}buffer(){return t1(this)}}vi.prototype.buffer=r1(vi.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(vi.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:r1(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function t1(e){if(e[un].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[un].disturbed=!0,e[un].error)throw e[un].error;let{body:t}=e;if(t===null)return Dn.alloc(0);if(!(t instanceof ks))return Dn.alloc(0);let r=[],n=0;try{for await(let o of t){if(e.size>0&&n+o.length>e.size){let i=new Tn(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(i),i}n+=o.length,r.push(o)}}catch(o){throw o instanceof As?o:new Tn(`Invalid response body while trying to fetch ${e.url}: ${o.message}`,"system",o)}if(t.readableEnded===!0||t._readableState.ended===!0)try{if(r.every((o)=>typeof o==="string"))return Dn.from(r.join(""));return Dn.concat(r,n)}catch(o){throw new Tn(`Could not create Buffer from response body for ${e.url}: ${o.message}`,"system",o)}else throw new Tn(`Premature close of server response while trying to fetch ${e.url}`)}var au=(e,t)=>{let r,n,{body:o}=e[un];if(e.bodyUsed)throw Error("cannot clone body after it is used");if(o instanceof ks&&typeof o.getBoundary!=="function")r=new Ok({highWaterMark:t}),n=new Ok({highWaterMark:t}),o.pipe(r),o.pipe(n),e[un].stream=r,o=n;return o},rG=r1((e)=>e.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),mh=(e,t)=>{if(e===null)return null;if(typeof e==="string")return"text/plain;charset=UTF-8";if(Xx(e))return"application/x-www-form-urlencoded;charset=UTF-8";if(Kl(e))return e.type||null;if(Dn.isBuffer(e)||Ck.isAnyArrayBuffer(e)||ArrayBuffer.isView(e))return null;if(e instanceof Ua)return`multipart/form-data; boundary=${t[un].boundary}`;if(e&&typeof e.getBoundary==="function")return`multipart/form-data;boundary=${rG(e)}`;if(e instanceof ks)return null;return"text/plain;charset=UTF-8"},Mk=(e)=>{let{body:t}=e[un];if(t===null)return 0;if(Kl(t))return t.size;if(Dn.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==="function")return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null;return null},$k=async(e,{body:t})=>{if(t===null)e.end();else await tG(t,e)};import{types as Nk}from"node:util";import gh from"node:http";var hh=typeof gh.validateHeaderName==="function"?gh.validateHeaderName:(e)=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),t}},n1=typeof gh.validateHeaderValue==="function"?gh.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let r=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}};class Zr extends URLSearchParams{constructor(e){let t=[];if(e instanceof Zr){let r=e.raw();for(let[n,o]of Object.entries(r))t.push(...o.map((i)=>[n,i]))}else if(e==null);else if(typeof e==="object"&&!Nk.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)t.push(...Object.entries(e));else{if(typeof r!=="function")throw TypeError("Header pairs must be iterable");t=[...e].map((n)=>{if(typeof n!=="object"||Nk.isBoxedPrimitive(n))throw TypeError("Each header pair must be an iterable object");return[...n]}).map((n)=>{if(n.length!==2)throw TypeError("Each header pair must be a name/value tuple");return[...n]})}}else throw TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");t=t.length>0?t.map(([r,n])=>(hh(r),n1(r,String(n)),[String(r).toLowerCase(),String(n)])):void 0;super(t);return new Proxy(this,{get(r,n,o){switch(n){case"append":case"set":return(i,s)=>(hh(i),n1(i,String(s)),URLSearchParams.prototype[n].call(r,String(i).toLowerCase(),String(s)));case"delete":case"has":case"getAll":return(i)=>(hh(i),URLSearchParams.prototype[n].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,n,o)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let r=t.join(", ");if(/^content-encoding$/i.test(e))r=r.toLowerCase();return r}forEach(e,t=void 0){for(let r of this.keys())Reflect.apply(e,t,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let r=this.getAll(t);if(t==="host")e[t]=r[0];else e[t]=r.length>1?r:r[0];return e},{})}}Object.defineProperties(Zr.prototype,["get","entries","forEach","values"].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));function zk(e=[]){return new Zr(e.reduce((t,r,n,o)=>{if(n%2===0)t.push(o.slice(n,n+2));return t},[]).filter(([t,r])=>{try{return hh(t),n1(t,String(r)),!0}catch{return!1}}))}var nG=new Set([301,302,303,307,308]),yh=(e)=>nG.has(e);var io=Symbol("Response internals");class Ar extends vi{constructor(e=null,t={}){super(e,t);let r=t.status!=null?t.status:200,n=new Zr(t.headers);if(e!==null&&!n.has("Content-Type")){let o=mh(e,this);if(o)n.append("Content-Type",o)}this[io]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:n,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[io].type}get url(){return this[io].url||""}get status(){return this[io].status}get ok(){return this[io].status>=200&&this[io].status<300}get redirected(){return this[io].counter>0}get statusText(){return this[io].statusText}get headers(){return this[io].headers}get highWaterMark(){return this[io].highWaterMark}clone(){return new Ar(au(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!yh(t))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');return new Ar(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new Ar(null,{status:0,statusText:""});return e[io].type="error",e}static json(e=void 0,t={}){let r=JSON.stringify(e);if(r===void 0)throw TypeError("data is not JSON serializable");let n=new Zr(t&&t.headers);if(!n.has("content-type"))n.set("content-type","application/json");return new Ar(r,{...t,headers:n})}get[Symbol.toStringTag](){return"Response"}}Object.defineProperties(Ar.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});import{format as sG}from"node:url";import{deprecate as aG}from"node:util";var Bk=(e)=>{if(e.search)return e.search;let t=e.href.length-1,r=e.hash||(e.href[t]==="#"?"#":"");return e.href[t-r.length]==="?"?"?":""};import{isIP as oG}from"node:net";function Lk(e,t=!1){if(e==null)return"no-referrer";if(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))return"no-referrer";if(e.username="",e.password="",e.hash="",t)e.pathname="",e.search="";return e}var Dk=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Uk="strict-origin-when-cross-origin";function Fk(e){if(!Dk.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function iG(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,""),r=oG(t);if(r===4&&/^127\./.test(t))return!0;if(r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t))return!0;if(e.host==="localhost"||e.host.endsWith(".localhost"))return!1;if(e.protocol==="file:")return!0;return!1}function cu(e){if(/^about:(blank|srcdoc)$/.test(e))return!0;if(e.protocol==="data:")return!0;if(/^(blob|filesystem):$/.test(e.protocol))return!0;return iG(e)}function jk(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if(e.referrer==="no-referrer"||e.referrerPolicy==="")return null;let n=e.referrerPolicy;if(e.referrer==="about:client")return"no-referrer";let o=e.referrer,i=Lk(o),s=Lk(o,!0);if(i.toString().length>4096)i=s;if(t)i=t(i);if(r)s=r(s);let a=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return s;case"unsafe-url":return i;case"strict-origin":if(cu(i)&&!cu(a))return"no-referrer";return s.toString();case"strict-origin-when-cross-origin":if(i.origin===a.origin)return i;if(cu(i)&&!cu(a))return"no-referrer";return s;case"same-origin":if(i.origin===a.origin)return i;return"no-referrer";case"origin-when-cross-origin":if(i.origin===a.origin)return i;return s;case"no-referrer-when-downgrade":if(cu(i)&&!cu(a))return"no-referrer";return i;default:throw TypeError(`Invalid referrerPolicy: ${n}`)}}function qk(e){let t=(e.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of t)if(n&&Dk.has(n))r=n;return r}var hr=Symbol("Request internals"),Jl=(e)=>typeof e==="object"&&typeof e[hr]==="object",cG=aG(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");class Ti extends vi{constructor(e,t={}){let r;if(Jl(e))r=new URL(e.url);else r=new URL(e),e={};if(r.username!==""||r.password!=="")throw TypeError(`${r} is an url with embedded credentials.`);let n=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n))n=n.toUpperCase();if(!Jl(t)&&"data"in t)cG();if((t.body!=null||Jl(e)&&e.body!==null)&&(n==="GET"||n==="HEAD"))throw TypeError("Request with GET/HEAD method cannot have body");let o=t.body?t.body:Jl(e)&&e.body!==null?au(e):null;super(o,{size:t.size||e.size||0});let i=new Zr(t.headers||e.headers||{});if(o!==null&&!i.has("Content-Type")){let c=mh(o,this);if(c)i.set("Content-Type",c)}let s=Jl(e)?e.signal:null;if("signal"in t)s=t.signal;if(s!=null&&!Sk(s))throw TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let a=t.referrer==null?e.referrer:t.referrer;if(a==="")a="no-referrer";else if(a){let c=new URL(a);a=/^about:(\/\/)?client$/.test(c)?"client":c}else a=void 0;this[hr]={method:n,redirect:t.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:s,referrer:a},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[hr].method}get url(){return sG(this[hr].parsedURL)}get headers(){return this[hr].headers}get redirect(){return this[hr].redirect}get signal(){return this[hr].signal}get referrer(){if(this[hr].referrer==="no-referrer")return"";if(this[hr].referrer==="client")return"about:client";if(this[hr].referrer)return this[hr].referrer.toString();return}get referrerPolicy(){return this[hr].referrerPolicy}set referrerPolicy(e){this[hr].referrerPolicy=Fk(e)}clone(){return new Ti(this)}get[Symbol.toStringTag](){return"Request"}}Object.defineProperties(Ti.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});var Hk=(e)=>{let{parsedURL:t}=e[hr],r=new Zr(e[hr].headers);if(!r.has("Accept"))r.set("Accept","*/*");let n=null;if(e.body===null&&/^(post|put)$/i.test(e.method))n="0";if(e.body!==null){let a=Mk(e);if(typeof a==="number"&&!Number.isNaN(a))n=String(a)}if(n)r.set("Content-Length",n);if(e.referrerPolicy==="")e.referrerPolicy=Uk;if(e.referrer&&e.referrer!=="no-referrer")e[hr].referrer=jk(e);else e[hr].referrer="no-referrer";if(e[hr].referrer instanceof URL)r.set("Referer",e.referrer);if(!r.has("User-Agent"))r.set("User-Agent","node-fetch");if(e.compress&&!r.has("Accept-Encoding"))r.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=e;if(typeof o==="function")o=o(t);let i=Bk(t),s={path:t.pathname+i,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:o};return{parsedURL:t,options:s}};class o1 extends As{constructor(e,t="aborted"){super(e,t)}}dh();e1();var lG=new Set(["data:","http:","https:"]);async function xh(e,t){return new Promise((r,n)=>{let o=new Ti(e,t),{parsedURL:i,options:s}=Hk(o);if(!lG.has(i.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let y=fk(o.url),x=new Ar(y,{headers:{"Content-Type":y.typeFull}});r(x);return}let a=(i.protocol==="https:"?dG:uG).request,{signal:c}=o,d=null,l=()=>{let y=new o1("The operation was aborted.");if(n(y),o.body&&o.body instanceof Gk.Readable)o.body.destroy(y);if(!d||!d.body)return;d.body.emit("error",y)};if(c&&c.aborted){l();return}let p=()=>{l(),h()},m=a(i.toString(),s);if(c)c.addEventListener("abort",p);let h=()=>{if(m.abort(),c)c.removeEventListener("abort",p)};if(m.on("error",(y)=>{n(new Tn(`request to ${o.url} failed, reason: ${y.message}`,"system",y)),h()}),pG(m,(y)=>{if(d&&d.body)d.body.destroy(y)}),process.version<"v14")m.on("socket",(y)=>{let x;y.prependListener("end",()=>{x=y._eventsCount}),y.prependListener("close",(_)=>{if(d&&x<y._eventsCount&&!_){let w=Error("Premature close");w.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",w)}})});m.on("response",(y)=>{m.setTimeout(0);let x=zk(y.rawHeaders);if(yh(y.statusCode)){let v=x.get("Location"),P=null;try{P=v===null?null:new URL(v,o.url)}catch{if(o.redirect!=="manual"){n(new Tn(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),h();return}}switch(o.redirect){case"error":n(new Tn(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),h();return;case"manual":break;case"follow":{if(P===null)break;if(o.counter>=o.follow){n(new Tn(`maximum redirect reached at: ${o.url}`,"max-redirect")),h();return}let k={headers:new Zr(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:au(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!vk(o.url,P)||!Tk(o.url,P))for(let N of["authorization","www-authenticate","cookie","cookie2"])k.headers.delete(N);if(y.statusCode!==303&&o.body&&t.body instanceof Gk.Readable){n(new Tn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),h();return}if(y.statusCode===303||(y.statusCode===301||y.statusCode===302)&&o.method==="POST")k.method="GET",k.body=void 0,k.headers.delete("content-length");let O=qk(x);if(O)k.referrerPolicy=O;r(xh(new Ti(P,k))),h();return}default:return n(TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}if(c)y.once("end",()=>{c.removeEventListener("abort",p)});let _=du(y,new Vk,(v)=>{if(v)n(v)});if(process.version<"v12.10")y.on("aborted",p);let w={url:o.url,status:y.statusCode,statusText:y.statusMessage,headers:x,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=x.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||y.statusCode===204||y.statusCode===304){d=new Ar(_,w),r(d);return}let S={flush:uu.Z_SYNC_FLUSH,finishFlush:uu.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){_=du(_,uu.createGunzip(S),(v)=>{if(v)n(v)}),d=new Ar(_,w),r(d);return}if(A==="deflate"||A==="x-deflate"){let v=du(y,new Vk,(P)=>{if(P)n(P)});v.once("data",(P)=>{if((P[0]&15)===8)_=du(_,uu.createInflate(),(k)=>{if(k)n(k)});else _=du(_,uu.createInflateRaw(),(k)=>{if(k)n(k)});d=new Ar(_,w),r(d)}),v.once("end",()=>{if(!d)d=new Ar(_,w),r(d)});return}if(A==="br"){_=du(_,uu.createBrotliDecompress(),(v)=>{if(v)n(v)}),d=new Ar(_,w),r(d);return}d=new Ar(_,w),r(d)}),$k(m,o).catch(n)})}function pG(e,t){let r=bh.from(`0\r
|
|
65
|
+
`),{cause:e,name:"TipAboveFeeCapError"})}};Object.defineProperty(ds,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Oo=class Oo extends C{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}});function ha(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof C?e.walk((o)=>o?.code===ai.code):e;if(n instanceof C)return new ai({cause:e,message:n.details});if(ai.nodeMessage.test(r))return new ai({cause:e,message:e.details});if(Ro.nodeMessage.test(r))return new Ro({cause:e,maxFeePerGas:t?.maxFeePerGas});if(im.nodeMessage.test(r))return new im({cause:e,maxFeePerGas:t?.maxFeePerGas});if(sm.nodeMessage.test(r))return new sm({cause:e,nonce:t?.nonce});if(am.nodeMessage.test(r))return new am({cause:e,nonce:t?.nonce});if(cm.nodeMessage.test(r))return new cm({cause:e,nonce:t?.nonce});if(um.nodeMessage.test(r))return new um({cause:e});if(dm.nodeMessage.test(r))return new dm({cause:e,gas:t?.gas});if(lm.nodeMessage.test(r))return new lm({cause:e,gas:t?.gas});if(pm.nodeMessage.test(r))return new pm({cause:e});if(ds.nodeMessage.test(r))return new ds({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Oo({cause:e})}var fm=V(()=>{He();ls()});function Fy(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Oo)return e;return o})();return new Oc(n,{docsPath:t,...r})}var YE=V(()=>{os();ls();fm()});function eo(e,{format:t}){if(!t)return{};let r={};function n(i){let s=Object.keys(i);for(let a of s){if(a in e)r[a]=e[a];if(i[a]&&typeof i[a]==="object"&&!Array.isArray(i[a]))n(i[a])}}let o=t(e||{});return n(o),r}function jr(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=Kae(e.authorizationList);if(typeof e.accessList<"u")r.accessList=e.accessList;if(typeof e.blobVersionedHashes<"u")r.blobVersionedHashes=e.blobVersionedHashes;if(typeof e.blobs<"u")if(typeof e.blobs[0]!=="string")r.blobs=e.blobs.map((n)=>mt(n));else r.blobs=e.blobs;if(typeof e.data<"u")r.data=e.data;if(e.account)r.from=e.account.address;if(typeof e.from<"u")r.from=e.from;if(typeof e.gas<"u")r.gas=H(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=H(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=H(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=H(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=H(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=H(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=Wae[e.type];if(typeof e.value<"u")r.value=H(e.value);return r}function Kae(e){return e.map((t)=>({address:t.address,r:t.r?H(BigInt(t.r)):t.r,s:t.s?H(BigInt(t.s)):t.s,chainId:H(t.chainId),nonce:H(t.nonce),...typeof t.yParity<"u"?{yParity:H(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:H(t.v)}:{}}))}var Wae;var ps=V(()=>{Fe();Wae={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function Vd(){let e=()=>{return},t=()=>{return};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Zd({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let i=async()=>{let l=c();s();let p=l.map(({args:m})=>m);if(p.length===0)return;e(p).then((m)=>{if(o&&Array.isArray(m))m.sort(o);for(let h=0;h<l.length;h++){let{resolve:y}=l[h];y?.([m[h],m])}}).catch((m)=>{for(let h=0;h<l.length;h++){let{reject:y}=l[h];y?.(m)}})},s=()=>JE.delete(t),a=()=>c().map(({args:l})=>l),c=()=>JE.get(t)||[],d=(l)=>JE.set(t,[...c(),l]);return{flush:s,async schedule(l){let{promise:p,resolve:m,reject:h}=Vd();if(r?.([...a(),l]))i();if(c().length>0)return d({args:l,resolve:m,reject:h}),p;return d({args:l,resolve:m,reject:h}),setTimeout(i,n),p}}}var JE;var jy=V(()=>{JE=new Map});function IL(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new ey({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new ey({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function Yae(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:i}=e,s={};if(i!==void 0)s.code=i;if(t!==void 0)s.balance=H(t);if(r!==void 0)s.nonce=H(r);if(n!==void 0)s.state=IL(n);if(o!==void 0){if(s.state)throw new _E;s.stateDiff=IL(o)}return s}function Wd(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!ht(r,{strict:!1}))throw new Ft({address:r});if(t[r])throw new xE({address:r});t[r]=Yae(n)}return t}var qy=V(()=>{ei();ty();wE();Cn();Fe()});var ZAe,WAe,KAe,YAe,JAe,QAe,XAe,eIe,tIe,rIe,nIe,oIe,iIe,sIe,aIe,cIe,uIe,dIe,lIe,pIe,fIe,mIe,hIe,gIe,yIe,bIe,xIe,_Ie,wIe,SIe,vIe,TIe,EIe,PIe,AIe,IIe,kIe,RIe,OIe,CIe,MIe,$Ie,NIe,zIe,BIe,LIe,DIe,UIe,FIe,jIe,qIe,HIe,GIe,VIe,ZIe,WIe,KIe,YIe,JIe,QIe,XIe,eke,tke,rke,nke,oke,ike,ske,ake,cke,uke,dke,lke,pke,fke,mke,hke,gke,yke,bke,xke,_ke,wke,Ske,vke,Tke,Eke,Pke,Ake,Ike,kke,Rke,Oke,Cke,Mke,Kd;var QE=V(()=>{ZAe=2n**(8n-1n)-1n,WAe=2n**(16n-1n)-1n,KAe=2n**(24n-1n)-1n,YAe=2n**(32n-1n)-1n,JAe=2n**(40n-1n)-1n,QAe=2n**(48n-1n)-1n,XAe=2n**(56n-1n)-1n,eIe=2n**(64n-1n)-1n,tIe=2n**(72n-1n)-1n,rIe=2n**(80n-1n)-1n,nIe=2n**(88n-1n)-1n,oIe=2n**(96n-1n)-1n,iIe=2n**(104n-1n)-1n,sIe=2n**(112n-1n)-1n,aIe=2n**(120n-1n)-1n,cIe=2n**(128n-1n)-1n,uIe=2n**(136n-1n)-1n,dIe=2n**(144n-1n)-1n,lIe=2n**(152n-1n)-1n,pIe=2n**(160n-1n)-1n,fIe=2n**(168n-1n)-1n,mIe=2n**(176n-1n)-1n,hIe=2n**(184n-1n)-1n,gIe=2n**(192n-1n)-1n,yIe=2n**(200n-1n)-1n,bIe=2n**(208n-1n)-1n,xIe=2n**(216n-1n)-1n,_Ie=2n**(224n-1n)-1n,wIe=2n**(232n-1n)-1n,SIe=2n**(240n-1n)-1n,vIe=2n**(248n-1n)-1n,TIe=2n**(256n-1n)-1n,EIe=-(2n**(8n-1n)),PIe=-(2n**(16n-1n)),AIe=-(2n**(24n-1n)),IIe=-(2n**(32n-1n)),kIe=-(2n**(40n-1n)),RIe=-(2n**(48n-1n)),OIe=-(2n**(56n-1n)),CIe=-(2n**(64n-1n)),MIe=-(2n**(72n-1n)),$Ie=-(2n**(80n-1n)),NIe=-(2n**(88n-1n)),zIe=-(2n**(96n-1n)),BIe=-(2n**(104n-1n)),LIe=-(2n**(112n-1n)),DIe=-(2n**(120n-1n)),UIe=-(2n**(128n-1n)),FIe=-(2n**(136n-1n)),jIe=-(2n**(144n-1n)),qIe=-(2n**(152n-1n)),HIe=-(2n**(160n-1n)),GIe=-(2n**(168n-1n)),VIe=-(2n**(176n-1n)),ZIe=-(2n**(184n-1n)),WIe=-(2n**(192n-1n)),KIe=-(2n**(200n-1n)),YIe=-(2n**(208n-1n)),JIe=-(2n**(216n-1n)),QIe=-(2n**(224n-1n)),XIe=-(2n**(232n-1n)),eke=-(2n**(240n-1n)),tke=-(2n**(248n-1n)),rke=-(2n**(256n-1n)),nke=2n**8n-1n,oke=2n**16n-1n,ike=2n**24n-1n,ske=2n**32n-1n,ake=2n**40n-1n,cke=2n**48n-1n,uke=2n**56n-1n,dke=2n**64n-1n,lke=2n**72n-1n,pke=2n**80n-1n,fke=2n**88n-1n,mke=2n**96n-1n,hke=2n**104n-1n,gke=2n**112n-1n,yke=2n**120n-1n,bke=2n**128n-1n,xke=2n**136n-1n,_ke=2n**144n-1n,wke=2n**152n-1n,Ske=2n**160n-1n,vke=2n**168n-1n,Tke=2n**176n-1n,Eke=2n**184n-1n,Pke=2n**192n-1n,Ake=2n**200n-1n,Ike=2n**208n-1n,kke=2n**216n-1n,Rke=2n**224n-1n,Oke=2n**232n-1n,Cke=2n**240n-1n,Mke=2n**248n-1n,Kd=2n**256n-1n});function Sr(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,i=t?ze(t):void 0;if(i&&!ht(i.address))throw new Ft({address:i.address});if(o&&!ht(o))throw new Ft({address:o});if(r&&r>Kd)throw new Ro({maxFeePerGas:r});if(n&&r&&n>r)throw new ds({maxFeePerGas:r,maxPriorityFeePerGas:n})}var ci=V(()=>{QE();ei();ls();Cn()});var XE,eP,tP;var kL=V(()=>{He();XE=class XE extends C{constructor({callbackSelector:e,cause:t,data:r,extraData:n,sender:o,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map((s)=>` ${Rc(s)}`)],` Sender: ${o}`,` Data: ${r}`,` Callback selector: ${e}`,` Extra data: ${n}`].flat(),name:"OffchainLookupError"})}};eP=class eP extends C{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${Rc(t)}`,`Response: ${Je(e)}`],name:"OffchainLookupResponseMalformedError"})}};tP=class tP extends C{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}});async function OL(e,{blockNumber:t,blockTag:r,data:n,requestOptions:o,to:i}){let{args:s}=Ey({data:n,abi:[Jae]}),[a,c,d,l,p]=s,{ccipRead:m}=e,h=m&&typeof m?.request==="function"?m.request:Qae;try{if(!wr(i,a))throw new tP({sender:a,to:i});let y=c.includes(is)?await CE({data:d,ccipRequest:(_)=>h({..._,requestOptions:o})}):await h({data:d,requestOptions:o,sender:a,urls:c}),{data:x}=await Sn(e,{blockNumber:t,blockTag:r,data:fr([l,nn([{type:"bytes"},{type:"bytes"}],[y,p])]),requestOptions:o,to:i});return x}catch(y){if(o?.signal?.aborted)throw Nr(o.signal);if(_n(y))throw y;throw new XE({callbackSelector:l,cause:y,data:n,extraData:p,sender:a,urls:c})}}async function Qae({data:e,requestOptions:t,sender:r,urls:n}){let o=Error("An unknown error occurred.");for(let i=0;i<n.length;i++){if(t?.signal?.aborted)throw Nr(t.signal);let s=n[i],a=s.includes("{data}")?"GET":"POST",c=a==="POST"?{data:e,sender:r}:void 0,d=a==="POST"?{"Content-Type":"application/json"}:{};try{let l=await fetch(s.replace("{sender}",r.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:a,...t?.signal?{signal:t.signal}:{}}),p;if(l.headers.get("Content-Type")?.startsWith("application/json"))p=(await l.json()).data;else p=await l.text();if(!l.ok){o=new Io({body:c,details:p?.error?Je(p.error):l.statusText,headers:l.headers,status:l.status,url:s});continue}if(!Kt(p)){o=new eP({result:p,url:s});continue}return p}catch(l){if(t?.signal?.aborted)throw Nr(t.signal);if(_n(l))throw l;o=new Io({body:c,details:l.message,url:s})}}throw o}var RL="0x556f1830",Jae;var CL=V(()=>{ga();kL();Mc();gE();Qi();us();rm();Jae={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});async function Sn(e,t){let{account:r=e.account,authorizationList:n,batch:o=Boolean(e.batch?.multicall),blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:d,blobs:l,blockOverrides:p,code:m,data:h,factory:y,factoryData:x,gas:_,gasPrice:w,maxFeePerBlobGas:A,maxFeePerGas:S,maxPriorityFeePerGas:v,nonce:P,requestOptions:k,to:O,value:N,stateOverride:j,...R}=t,K=r?ze(r):void 0;if(m&&(y||x))throw new C("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(m&&O)throw new C("Cannot provide both `code` & `to` as parameters.");let Z=m&&h,re=y&&x&&O&&h,pe=Z||re,U=(()=>{if(Z)return NL({code:m,data:h});if(re)return oce({data:h,factory:y,factoryData:x,to:O});return h})();try{Sr(t);let ee=zn({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),me=p?Ly(p):void 0,z=Wd(j),F=e.chain?.formatters?.transactionRequest?.format,we=(F||jr)({...eo(R,{format:F}),accessList:d,account:K,authorizationList:n,blobs:l,data:U,gas:_,gasPrice:w,maxFeePerBlobGas:A,maxFeePerGas:S,maxPriorityFeePerGas:v,nonce:P,to:pe?void 0:O,value:N},"call");if(o&&Xae({request:we})&&!me&&i===void 0)try{let{deployless:Ee=!1}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},Ae=$L(e,{blockNumber:s,deployless:Ee});if(!Ae||!nce(z,Ae))return await rce(e,{...we,blockHash:i,blockNumber:s,blockTag:a,multicallAddress:Ae,requestOptions:k,requireCanonical:c,rpcStateOverride:z})}catch(Ee){if(!(Ee instanceof Sy)&&!(Ee instanceof fd))throw Ee}let te=(()=>{let Ee=[we,ee];if(z&&me)return[...Ee,z,me];if(z)return[...Ee,z];if(me)return[...Ee,{},me];return Ee})(),$e=await e.request({method:"eth_call",params:te},k);if($e==="0x")return{data:void 0};return{data:$e}}catch(ee){if(k?.signal?.aborted)throw Nr(k.signal);if(_n(ee))throw ee;let me=ice(ee);await Promise.resolve().then(() => CL());if(e.ccipRead!==!1&&me?.slice(0,10)===RL&&O)return{data:await OL(e,{data:me,requestOptions:k,to:O})};if(pe&&me?.slice(0,10)==="0x101bb98d")throw new IE({factory:y});throw Fy(ee,{...t,account:K,chain:e.chain})}}function Xae({request:e}){let{data:t,to:r,...n}=e;if(!t)return!1;if(t.startsWith(EL))return!1;if(!r)return!1;if(Object.values(n).filter((o)=>typeof o<"u").length>0)return!1;return!0}function tce(e){if(!e)return"default";let t=ML.get(e);if(t!==void 0)return t;let r=ece++;return ML.set(e,r),r}async function rce(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:d,multicallAddress:l,requestOptions:p,rpcStateOverride:m,to:h}=t,y=l!==void 0?l:$L(e,{blockNumber:s,deployless:n}),x=zn({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),_=typeof x==="string"?x:JSON.stringify(x),w=m?`.${JSON.stringify(m)}`:"",{schedule:A}=Zd({id:`${e.uid}.${_}.${tce(p)}${w}`,wait:o,shouldSplitBatch(P){return P.reduce((O,{data:N})=>O+(N.length-2),0)>r*2},fn:async(P)=>{let k=P.map((R)=>({allowFailure:!0,callData:R.data,target:R.to})),O=At({abi:Zn,args:[k],functionName:"aggregate3"}),N={...y===null?{data:NL({code:zc,data:O})}:{to:y,data:O}},j=await e.request({method:"eth_call",params:m?[N,x,m]:[N,x]},p);return Dr({abi:Zn,args:[k],functionName:"aggregate3",data:j||"0x"})}}),[{returnData:S,success:v}]=await A({data:d,to:h});if(!v)throw new ns({data:S});if(S==="0x")return{data:void 0};return{data:S}}function $L(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return Yn({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new Sy}function nce(e,t){if(!e)return!1;return Object.keys(e).some((r)=>wr(r,t))}function NL(e){let{code:t,data:r}=e;return Bc({abi:by(["constructor(bytes, bytes)"]),bytecode:Dy,args:[t,r]})}function oce(e){let{data:t,factory:r,factoryData:n,to:o}=e;return Bc({abi:by(["constructor(address, bytes, address, bytes)"]),bytecode:PL,args:[o,t,r,n]})}function ice(e){if(!(e instanceof C))return;let t=e.walk();return typeof t?.data==="object"?t.data?.data:t.data}var ece=0,ML;var ga=V(()=>{Kf();WE();Mr();He();Jf();os();rs();Uy();xn();us();Lc();Ac();YE();ps();jy();qy();ci();ML=new WeakMap});var aP,cP=(e,t,r)=>new aP(e,t).update(r).digest();var KL=V(()=>{hc();aP=class aP extends Sf{constructor(e,t){super();this.finished=!1,this.destroyed=!1,Q4(e);let r=wf(t);if(this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ui(o)}update(e){return Yu(this),this.iHash.update(e),this}digestInto(e){Yu(this),mc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:s}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};cP.create=(e,t)=>new aP(e,t)});function YL(e){if(e.lowS!==void 0)Yo("lowS",e.lowS);if(e.prehash!==void 0)Yo("prehash",e.prehash)}function fce(e){let t=If(e);Hi(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof r!=="object"||typeof r.beta!=="bigint"||typeof r.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function uP(e,t){return ra(xc(e,t))}function hce(e){let t=fce(e),{Fp:r}=t,n=Gi(t.n,t.nBitLength),o=t.toBytes||((S,v,P)=>{let k=v.toAffine();return na(Uint8Array.from([4]),r.toBytes(k.x),r.toBytes(k.y))}),i=t.fromBytes||((S)=>{let v=S.subarray(1),P=r.fromBytes(v.subarray(0,r.BYTES)),k=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x:P,y:k}});function s(S){let{a:v,b:P}=t,k=r.sqr(S),O=r.mul(k,S);return r.add(r.add(O,r.mul(S,v)),P)}function a(S,v){let P=r.sqr(v),k=s(S);return r.eql(P,k)}if(!a(t.Gx,t.Gy))throw Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,dP),mce),d=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,d)))throw Error("bad curve params: a or b");function l(S){return O0(S,vr,t.n)}function p(S){let{allowedPrivateKeyLengths:v,nByteLength:P,wrapPrivateKey:k,n:O}=t;if(v&&typeof S!=="bigint"){if(Ju(S))S=ra(S);if(typeof S!=="string"||!v.includes(S.length))throw Error("invalid private key");S=S.padStart(P*2,"0")}let N;try{N=typeof S==="bigint"?S:qi(Gt("private key",S,P))}catch(j){throw Error("invalid private key, expected hex or "+P+" bytes, got "+typeof S)}if(k)N=Et(N,O);return Rn("private key",N,vr,O),N}function m(S){if(!(S instanceof x))throw Error("ProjectivePoint expected")}let h=Xu((S,v)=>{let{px:P,py:k,pz:O}=S;if(r.eql(O,r.ONE))return{x:P,y:k};let N=S.is0();if(v==null)v=N?r.ONE:r.inv(O);let j=r.mul(P,v),R=r.mul(k,v),K=r.mul(O,v);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(K,r.ONE))throw Error("invZ was invalid");return{x:j,y:R}}),y=Xu((S)=>{if(S.is0()){if(t.allowInfinityPoint&&!r.is0(S.py))return;throw Error("bad point: ZERO")}let{x:v,y:P}=S.toAffine();if(!r.isValid(v)||!r.isValid(P))throw Error("bad point: x or y not FE");if(!a(v,P))throw Error("bad point: equation left != right");if(!S.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class x{constructor(S,v,P){if(S==null||!r.isValid(S))throw Error("x required");if(v==null||!r.isValid(v)||r.is0(v))throw Error("y required");if(P==null||!r.isValid(P))throw Error("z required");this.px=S,this.py=v,this.pz=P,Object.freeze(this)}static fromAffine(S){let{x:v,y:P}=S||{};if(!S||!r.isValid(v)||!r.isValid(P))throw Error("invalid affine point");if(S instanceof x)throw Error("projective point not allowed");let k=(O)=>r.eql(O,r.ZERO);if(k(v)&&k(P))return x.ZERO;return new x(v,P,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let v=ed(r,S.map((P)=>P.pz));return S.map((P,k)=>P.toAffine(v[k])).map(x.fromAffine)}static fromHex(S){let v=x.fromAffine(i(Gt("pointHex",S)));return v.assertValidity(),v}static fromPrivateKey(S){return x.BASE.multiply(p(S))}static msm(S,v){return $0(x,n,S,v)}_setWindowSize(S){A.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw Error("Field doesn't support isOdd")}equals(S){m(S);let{px:v,py:P,pz:k}=this,{px:O,py:N,pz:j}=S,R=r.eql(r.mul(v,j),r.mul(O,k)),K=r.eql(r.mul(P,j),r.mul(N,k));return R&&K}negate(){return new x(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:v}=t,P=r.mul(v,dP),{px:k,py:O,pz:N}=this,{ZERO:j,ZERO:R,ZERO:K}=r,Z=r.mul(k,k),re=r.mul(O,O),pe=r.mul(N,N),U=r.mul(k,O);return U=r.add(U,U),K=r.mul(k,N),K=r.add(K,K),j=r.mul(S,K),R=r.mul(P,pe),R=r.add(j,R),j=r.sub(re,R),R=r.add(re,R),R=r.mul(j,R),j=r.mul(U,j),K=r.mul(P,K),pe=r.mul(S,pe),U=r.sub(Z,pe),U=r.mul(S,U),U=r.add(U,K),K=r.add(Z,Z),Z=r.add(K,Z),Z=r.add(Z,pe),Z=r.mul(Z,U),R=r.add(R,Z),pe=r.mul(O,N),pe=r.add(pe,pe),Z=r.mul(pe,U),j=r.sub(j,Z),K=r.mul(pe,re),K=r.add(K,K),K=r.add(K,K),new x(j,R,K)}add(S){m(S);let{px:v,py:P,pz:k}=this,{px:O,py:N,pz:j}=S,{ZERO:R,ZERO:K,ZERO:Z}=r,re=t.a,pe=r.mul(t.b,dP),U=r.mul(v,O),ee=r.mul(P,N),me=r.mul(k,j),z=r.add(v,P),F=r.add(O,N);z=r.mul(z,F),F=r.add(U,ee),z=r.sub(z,F),F=r.add(v,k);let Y=r.add(O,j);return F=r.mul(F,Y),Y=r.add(U,me),F=r.sub(F,Y),Y=r.add(P,k),R=r.add(N,j),Y=r.mul(Y,R),R=r.add(ee,me),Y=r.sub(Y,R),Z=r.mul(re,F),R=r.mul(pe,me),Z=r.add(R,Z),R=r.sub(ee,Z),Z=r.add(ee,Z),K=r.mul(R,Z),ee=r.add(U,U),ee=r.add(ee,U),me=r.mul(re,me),F=r.mul(pe,F),ee=r.add(ee,me),me=r.sub(U,me),me=r.mul(re,me),F=r.add(F,me),U=r.mul(ee,F),K=r.add(K,U),U=r.mul(Y,F),R=r.mul(z,R),R=r.sub(R,U),U=r.mul(z,ee),Z=r.mul(Y,Z),Z=r.add(Z,U),new x(R,K,Z)}subtract(S){return this.add(S.negate())}is0(){return this.equals(x.ZERO)}wNAF(S){return A.wNAFCached(this,S,x.normalizeZ)}multiplyUnsafe(S){let{endo:v,n:P}=t;Rn("scalar",S,ms,P);let k=x.ZERO;if(S===ms)return k;if(this.is0()||S===vr)return this;if(!v||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,S,x.normalizeZ);let{k1neg:O,k1:N,k2neg:j,k2:R}=v.splitScalar(S),K=k,Z=k,re=this;while(N>ms||R>ms){if(N&vr)K=K.add(re);if(R&vr)Z=Z.add(re);re=re.double(),N>>=vr,R>>=vr}if(O)K=K.negate();if(j)Z=Z.negate();return Z=new x(r.mul(Z.px,v.beta),Z.py,Z.pz),K.add(Z)}multiply(S){let{endo:v,n:P}=t;Rn("scalar",S,vr,P);let k,O;if(v){let{k1neg:N,k1:j,k2neg:R,k2:K}=v.splitScalar(S),{p:Z,f:re}=this.wNAF(j),{p:pe,f:U}=this.wNAF(K);Z=A.constTimeNegate(N,Z),pe=A.constTimeNegate(R,pe),pe=new x(r.mul(pe.px,v.beta),pe.py,pe.pz),k=Z.add(pe),O=re.add(U)}else{let{p:N,f:j}=this.wNAF(S);k=N,O=j}return x.normalizeZ([k,O])[0]}multiplyAndAddUnsafe(S,v,P){let k=x.BASE,O=(j,R)=>R===ms||R===vr||!j.equals(k)?j.multiplyUnsafe(R):j.multiply(R),N=O(this,v).add(O(S,P));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:v}=t;if(S===vr)return!0;if(v)return v(x,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:v}=t;if(S===vr)return this;if(v)return v(x,this);return this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return Yo("isCompressed",S),this.assertValidity(),o(x,this,S)}toHex(S=!0){return Yo("isCompressed",S),ra(this.toRawBytes(S))}}x.BASE=new x(t.Gx,t.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO);let{endo:_,nBitLength:w}=t,A=M0(x,_?Math.ceil(w/2):w);return{CURVE:t,ProjectivePoint:x,normPrivateKeyToScalar:p,weierstrassEquation:s,isWithinCurveOrder:l}}function gce(e){let t=If(e);return Hi(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function QL(e){let t=gce(e),{Fp:r,n,nByteLength:o,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(U){return Et(U,n)}function d(U){return C0(U,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:p,weierstrassEquation:m,isWithinCurveOrder:h}=hce({...t,toBytes(U,ee,me){let z=ee.toAffine(),F=r.toBytes(z.x),Y=na;if(Yo("isCompressed",me),me)return Y(Uint8Array.from([ee.hasEvenY()?2:3]),F);else return Y(Uint8Array.from([4]),F,r.toBytes(z.y))},fromBytes(U){let ee=U.length,me=U[0],z=U.subarray(1);if(ee===s&&(me===2||me===3)){let F=qi(z);if(!O0(F,vr,r.ORDER))throw Error("Point is not on curve");let Y=m(F),we;try{we=r.sqrt(Y)}catch(Ee){let Ae=Ee instanceof Error?": "+Ee.message:"";throw Error("Point is not on curve"+Ae)}let te=(we&vr)===vr;if((me&1)===1!==te)we=r.neg(we);return{x:F,y:we}}else if(ee===a&&me===4){let F=r.fromBytes(z.subarray(0,r.BYTES)),Y=r.fromBytes(z.subarray(r.BYTES,2*r.BYTES));return{x:F,y:Y}}else{let F=s,Y=a;throw Error("invalid Point, expected length of "+F+", or uncompressed "+Y+", got "+ee)}}});function y(U){let ee=n>>vr;return U>ee}function x(U){return y(U)?c(-U):U}let _=(U,ee,me)=>qi(U.slice(ee,me));class w{constructor(U,ee,me){if(Rn("r",U,vr,n),Rn("s",ee,vr,n),this.r=U,this.s=ee,me!=null)this.recovery=me;Object.freeze(this)}static fromCompact(U){let ee=o;return U=Gt("compactSignature",U,ee*2),new w(_(U,0,ee),_(U,ee,2*ee))}static fromDER(U){let{r:ee,s:me}=fs.toSig(Gt("DER",U));return new w(ee,me)}assertValidity(){}addRecoveryBit(U){return new w(this.r,this.s,U)}recoverPublicKey(U){let{r:ee,s:me,recovery:z}=this,F=O(Gt("msgHash",U));if(z==null||![0,1,2,3].includes(z))throw Error("recovery id invalid");let Y=z===2||z===3?ee+t.n:ee;if(Y>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let we=(z&1)===0?"02":"03",te=l.fromHex(we+uP(Y,r.BYTES)),$e=d(Y),Ee=c(-F*$e),Ae=c(me*$e),tt=l.BASE.multiplyAndAddUnsafe(te,Ee,Ae);if(!tt)throw Error("point at infinify");return tt.assertValidity(),tt}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Pf(this.toDERHex())}toDERHex(){return fs.hexFromSig(this)}toCompactRawBytes(){return Pf(this.toCompactHex())}toCompactHex(){let U=o;return uP(this.r,U)+uP(this.s,U)}}let A={isValidPrivateKey(U){try{return p(U),!0}catch(ee){return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{let U=Gv(t.n);return O8(t.randomBytes(U),t.n)},precompute(U=8,ee=l.BASE){return ee._setWindowSize(U),ee.multiply(BigInt(3)),ee}};function S(U,ee=!0){return l.fromPrivateKey(U).toRawBytes(ee)}function v(U){if(typeof U==="bigint")return!1;if(U instanceof l)return!0;let me=Gt("key",U).length,z=r.BYTES,F=z+1,Y=2*z+1;if(t.allowedPrivateKeyLengths||o===F)return;else return me===F||me===Y}function P(U,ee,me=!0){if(v(U)===!0)throw Error("first arg must be private key");if(v(ee)===!1)throw Error("second arg must be public key");return l.fromHex(ee).multiply(p(U)).toRawBytes(me)}let k=t.bits2int||function(U){if(U.length>8192)throw Error("input is too large");let ee=qi(U),me=U.length*8-i;return me>0?ee>>BigInt(me):ee},O=t.bits2int_modN||function(U){return c(k(U))},N=_c(i);function j(U){return Rn("num < 2^"+i,U,ms,N),xc(U,o)}function R(U,ee,me=K){if(["recovered","canonical"].some((q)=>(q in me)))throw Error("sign() legacy options not supported");let{hash:z,randomBytes:F}=t,{lowS:Y,prehash:we,extraEntropy:te}=me;if(Y==null)Y=!0;if(U=Gt("msgHash",U),YL(me),we)U=Gt("prehashed msgHash",z(U));let $e=O(U),Ee=p(ee),Ae=[j(Ee),j($e)];if(te!=null&&te!==!1){let q=te===!0?F(r.BYTES):te;Ae.push(Gt("extraEntropy",q))}let tt=na(...Ae),yt=$e;function ft(q){let ne=k(q);if(!h(ne))return;let ce=d(ne),he=l.BASE.multiply(ne).toAffine(),Q=c(he.x);if(Q===ms)return;let Be=c(ce*c(yt+Q*Ee));if(Be===ms)return;let bt=(he.x===Q?0:2)|Number(he.y&vr),xt=Be;if(Y&&y(Be))xt=x(Be),bt^=1;return new w(Q,xt,bt)}return{seed:tt,k2sig:ft}}let K={lowS:t.lowS,prehash:!1},Z={lowS:t.lowS,prehash:!1};function re(U,ee,me=K){let{seed:z,k2sig:F}=R(U,ee,me),Y=t;return v8(Y.hash.outputLen,Y.nByteLength,Y.hmac)(z,F)}l.BASE._setWindowSize(8);function pe(U,ee,me,z=Z){let F=U;ee=Gt("msgHash",ee),me=Gt("publicKey",me);let{lowS:Y,prehash:we,format:te}=z;if(YL(z),"strict"in z)throw Error("options.strict was renamed to lowS");if(te!==void 0&&te!=="compact"&&te!=="der")throw Error("format must be compact or der");let $e=typeof F==="string"||Ju(F),Ee=!$e&&!te&&typeof F==="object"&&F!==null&&typeof F.r==="bigint"&&typeof F.s==="bigint";if(!$e&&!Ee)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Ae=void 0,tt;try{if(Ee)Ae=new w(F.r,F.s);if($e){try{if(te!=="compact")Ae=w.fromDER(F)}catch(bt){if(!(bt instanceof fs.Err))throw bt}if(!Ae&&te!=="der")Ae=w.fromCompact(F)}tt=l.fromHex(me)}catch(bt){return!1}if(!Ae)return!1;if(Y&&Ae.hasHighS())return!1;if(we)ee=t.hash(ee);let{r:yt,s:ft}=Ae,q=O(ee),ne=d(ft),ce=c(q*ne),he=c(yt*ne),Q=l.BASE.multiplyAndAddUnsafe(tt,ce,he)?.toAffine();if(!Q)return!1;return c(Q.x)===yt}return{CURVE:t,getPublicKey:S,getSharedSecret:P,sign:re,verify:pe,ProjectivePoint:l,Signature:w,utils:A}}var JL,fs,ms,vr,m6e,dP,mce;var XL=V(()=>{Jv();td();Af();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */JL=class JL extends Error{constructor(e=""){super(e)}};fs={Err:JL,_tlv:{encode:(e,t)=>{let{Err:r}=fs;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=Ef(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?Ef(o.length/2|128):"";return Ef(e)+i+o+t},decode(e,t){let{Err:r}=fs,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=t.subarray(n,n+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of d)s=s<<8|l;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=fs;if(e<ms)throw new t("integer: negative integers are not allowed");let r=Ef(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=fs;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return qi(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=fs,o=Gt("signature",e),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:d,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(e){let{_tlv:t,_int:r}=fs,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}};ms=BigInt(0),vr=BigInt(1),m6e=BigInt(2),dP=BigInt(3),mce=BigInt(4)});function yce(e){return{hash:e,hmac:(t,...r)=>cP(e,t,Mv(...r)),randomBytes:I0}}function e9(e,t){let r=(n)=>QL({...e,...yce(n)});return{...r(t),create:r}}var t9=V(()=>{KL();hc();XL();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */});function _ce(e){let t=o9,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),d=e*e*e%t,l=d*d*e%t,p=Vt(l,r,t)*l%t,m=Vt(p,r,t)*l%t,h=Vt(m,lP,t)*d%t,y=Vt(h,o,t)*h%t,x=Vt(y,i,t)*y%t,_=Vt(x,a,t)*x%t,w=Vt(_,c,t)*_%t,A=Vt(w,a,t)*x%t,S=Vt(A,r,t)*l%t,v=Vt(S,s,t)*y%t,P=Vt(v,n,t)*d%t,k=Vt(P,lP,t);if(!pP.eql(pP.sqr(k),e))throw Error("Cannot find square root");return k}var o9,r9,bce,xce,lP,n9=(e,t)=>(e+t/lP)/t,pP,hs;var hm=V(()=>{Bv();t9();td();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */o9=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),r9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),bce=BigInt(0),xce=BigInt(1),lP=BigInt(2);pP=Gi(o9,void 0,void 0,{sqrt:_ce}),hs=e9({a:bce,b:BigInt(7),Fp:pP,n:r9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(e)=>{let t=r9,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-xce*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=n9(i*e,t),c=n9(-n*e,t),d=Et(e-a*r-c*o,t),l=Et(-a*n-c*i,t),p=d>s,m=l>s;if(p)d=t-d;if(m)l=t-l;if(d>s||l>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:p,k1:d,k2neg:m,k2:l}}}},g8)});import{webcrypto as gpe}from"node:crypto";import uG from"node:http";import dG from"node:https";import uu from"node:zlib";import Gk,{PassThrough as Vk,pipeline as du}from"node:stream";import{Buffer as bh}from"node:buffer";function DH(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,"");let t=e.indexOf(",");if(t===-1||t<=4)throw TypeError("malformed data: URI");let r=e.substring(5,t).split(";"),n="",o=!1,i=r[0]||"text/plain",s=i;for(let l=1;l<r.length;l++)if(r[l]==="base64")o=!0;else if(r[l]){if(s+=`;${r[l]}`,r[l].indexOf("charset=")===0)n=r[l].substring(8)}if(!r[0]&&!n.length)s+=";charset=US-ASCII",n="US-ASCII";let a=o?"base64":"ascii",c=unescape(e.substring(t+1)),d=Buffer.from(c,a);return d.type=i,d.typeFull=s,d.charset=n,d}var fk=DH;Zl();dh();import ks,{PassThrough as Ok}from"node:stream";import{types as Ck,deprecate as r1,promisify as eG}from"node:util";import{Buffer as Dn}from"node:buffer";class As extends Error{constructor(e,t){super(e);Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class Tn extends As{constructor(e,t,r){super(e,t);if(r)this.code=this.errno=r.code,this.erroredSysCall=r.syscall}}var lh=Symbol.toStringTag,Xx=(e)=>typeof e==="object"&&typeof e.append==="function"&&typeof e.delete==="function"&&typeof e.get==="function"&&typeof e.getAll==="function"&&typeof e.has==="function"&&typeof e.set==="function"&&typeof e.sort==="function"&&e[lh]==="URLSearchParams",Kl=(e)=>e&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&typeof e.constructor==="function"&&/^(Blob|File)$/.test(e[lh]),Sk=(e)=>typeof e==="object"&&(e[lh]==="AbortSignal"||e[lh]==="EventTarget"),vk=(e,t)=>{let r=new URL(t).hostname,n=new URL(e).hostname;return r===n||r.endsWith(`.${n}`)},Tk=(e,t)=>{let r=new URL(t).protocol,n=new URL(e).protocol;return r===n};var tG=eG(ks.pipeline),un=Symbol("Body internals");class vi{constructor(e,{size:t=0}={}){let r=null;if(e===null)e=null;else if(Xx(e))e=Dn.from(e.toString());else if(Kl(e));else if(Dn.isBuffer(e));else if(Ck.isAnyArrayBuffer(e))e=Dn.from(e);else if(ArrayBuffer.isView(e))e=Dn.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ks);else if(e instanceof Ua)e=wk(e),r=e.type.split("=")[1];else e=Dn.from(String(e));let n=e;if(Dn.isBuffer(e))n=ks.Readable.from(e);else if(Kl(e))n=ks.Readable.from(e.stream());if(this[un]={body:e,stream:n,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof ks)e.on("error",(o)=>{let i=o instanceof As?o:new Tn(`Invalid response body while trying to fetch ${this.url}: ${o.message}`,"system",o);this[un].error=i})}get body(){return this[un].stream}get bodyUsed(){return this[un].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:r}=await t1(this);return e.slice(t,t+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Ua,n=new URLSearchParams(await this.text());for(let[o,i]of n)r.append(o,i);return r}await Promise.resolve().then(() => Rk());return kk(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[un].body&&this[un].body.type||"",t=await this.arrayBuffer();return new Si([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await t1(this);return new TextDecoder().decode(e)}buffer(){return t1(this)}}vi.prototype.buffer=r1(vi.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(vi.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:r1(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function t1(e){if(e[un].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[un].disturbed=!0,e[un].error)throw e[un].error;let{body:t}=e;if(t===null)return Dn.alloc(0);if(!(t instanceof ks))return Dn.alloc(0);let r=[],n=0;try{for await(let o of t){if(e.size>0&&n+o.length>e.size){let i=new Tn(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(i),i}n+=o.length,r.push(o)}}catch(o){throw o instanceof As?o:new Tn(`Invalid response body while trying to fetch ${e.url}: ${o.message}`,"system",o)}if(t.readableEnded===!0||t._readableState.ended===!0)try{if(r.every((o)=>typeof o==="string"))return Dn.from(r.join(""));return Dn.concat(r,n)}catch(o){throw new Tn(`Could not create Buffer from response body for ${e.url}: ${o.message}`,"system",o)}else throw new Tn(`Premature close of server response while trying to fetch ${e.url}`)}var au=(e,t)=>{let r,n,{body:o}=e[un];if(e.bodyUsed)throw Error("cannot clone body after it is used");if(o instanceof ks&&typeof o.getBoundary!=="function")r=new Ok({highWaterMark:t}),n=new Ok({highWaterMark:t}),o.pipe(r),o.pipe(n),e[un].stream=r,o=n;return o},rG=r1((e)=>e.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),mh=(e,t)=>{if(e===null)return null;if(typeof e==="string")return"text/plain;charset=UTF-8";if(Xx(e))return"application/x-www-form-urlencoded;charset=UTF-8";if(Kl(e))return e.type||null;if(Dn.isBuffer(e)||Ck.isAnyArrayBuffer(e)||ArrayBuffer.isView(e))return null;if(e instanceof Ua)return`multipart/form-data; boundary=${t[un].boundary}`;if(e&&typeof e.getBoundary==="function")return`multipart/form-data;boundary=${rG(e)}`;if(e instanceof ks)return null;return"text/plain;charset=UTF-8"},Mk=(e)=>{let{body:t}=e[un];if(t===null)return 0;if(Kl(t))return t.size;if(Dn.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==="function")return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null;return null},$k=async(e,{body:t})=>{if(t===null)e.end();else await tG(t,e)};import{types as Nk}from"node:util";import gh from"node:http";var hh=typeof gh.validateHeaderName==="function"?gh.validateHeaderName:(e)=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),t}},n1=typeof gh.validateHeaderValue==="function"?gh.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let r=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}};class Zr extends URLSearchParams{constructor(e){let t=[];if(e instanceof Zr){let r=e.raw();for(let[n,o]of Object.entries(r))t.push(...o.map((i)=>[n,i]))}else if(e==null);else if(typeof e==="object"&&!Nk.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)t.push(...Object.entries(e));else{if(typeof r!=="function")throw TypeError("Header pairs must be iterable");t=[...e].map((n)=>{if(typeof n!=="object"||Nk.isBoxedPrimitive(n))throw TypeError("Each header pair must be an iterable object");return[...n]}).map((n)=>{if(n.length!==2)throw TypeError("Each header pair must be a name/value tuple");return[...n]})}}else throw TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");t=t.length>0?t.map(([r,n])=>(hh(r),n1(r,String(n)),[String(r).toLowerCase(),String(n)])):void 0;super(t);return new Proxy(this,{get(r,n,o){switch(n){case"append":case"set":return(i,s)=>(hh(i),n1(i,String(s)),URLSearchParams.prototype[n].call(r,String(i).toLowerCase(),String(s)));case"delete":case"has":case"getAll":return(i)=>(hh(i),URLSearchParams.prototype[n].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,n,o)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let r=t.join(", ");if(/^content-encoding$/i.test(e))r=r.toLowerCase();return r}forEach(e,t=void 0){for(let r of this.keys())Reflect.apply(e,t,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let r=this.getAll(t);if(t==="host")e[t]=r[0];else e[t]=r.length>1?r:r[0];return e},{})}}Object.defineProperties(Zr.prototype,["get","entries","forEach","values"].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));function zk(e=[]){return new Zr(e.reduce((t,r,n,o)=>{if(n%2===0)t.push(o.slice(n,n+2));return t},[]).filter(([t,r])=>{try{return hh(t),n1(t,String(r)),!0}catch{return!1}}))}var nG=new Set([301,302,303,307,308]),yh=(e)=>nG.has(e);var io=Symbol("Response internals");class Ar extends vi{constructor(e=null,t={}){super(e,t);let r=t.status!=null?t.status:200,n=new Zr(t.headers);if(e!==null&&!n.has("Content-Type")){let o=mh(e,this);if(o)n.append("Content-Type",o)}this[io]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:n,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[io].type}get url(){return this[io].url||""}get status(){return this[io].status}get ok(){return this[io].status>=200&&this[io].status<300}get redirected(){return this[io].counter>0}get statusText(){return this[io].statusText}get headers(){return this[io].headers}get highWaterMark(){return this[io].highWaterMark}clone(){return new Ar(au(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!yh(t))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');return new Ar(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new Ar(null,{status:0,statusText:""});return e[io].type="error",e}static json(e=void 0,t={}){let r=JSON.stringify(e);if(r===void 0)throw TypeError("data is not JSON serializable");let n=new Zr(t&&t.headers);if(!n.has("content-type"))n.set("content-type","application/json");return new Ar(r,{...t,headers:n})}get[Symbol.toStringTag](){return"Response"}}Object.defineProperties(Ar.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});import{format as sG}from"node:url";import{deprecate as aG}from"node:util";var Bk=(e)=>{if(e.search)return e.search;let t=e.href.length-1,r=e.hash||(e.href[t]==="#"?"#":"");return e.href[t-r.length]==="?"?"?":""};import{isIP as oG}from"node:net";function Lk(e,t=!1){if(e==null)return"no-referrer";if(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))return"no-referrer";if(e.username="",e.password="",e.hash="",t)e.pathname="",e.search="";return e}var Dk=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Uk="strict-origin-when-cross-origin";function Fk(e){if(!Dk.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function iG(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,""),r=oG(t);if(r===4&&/^127\./.test(t))return!0;if(r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t))return!0;if(e.host==="localhost"||e.host.endsWith(".localhost"))return!1;if(e.protocol==="file:")return!0;return!1}function cu(e){if(/^about:(blank|srcdoc)$/.test(e))return!0;if(e.protocol==="data:")return!0;if(/^(blob|filesystem):$/.test(e.protocol))return!0;return iG(e)}function jk(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if(e.referrer==="no-referrer"||e.referrerPolicy==="")return null;let n=e.referrerPolicy;if(e.referrer==="about:client")return"no-referrer";let o=e.referrer,i=Lk(o),s=Lk(o,!0);if(i.toString().length>4096)i=s;if(t)i=t(i);if(r)s=r(s);let a=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return s;case"unsafe-url":return i;case"strict-origin":if(cu(i)&&!cu(a))return"no-referrer";return s.toString();case"strict-origin-when-cross-origin":if(i.origin===a.origin)return i;if(cu(i)&&!cu(a))return"no-referrer";return s;case"same-origin":if(i.origin===a.origin)return i;return"no-referrer";case"origin-when-cross-origin":if(i.origin===a.origin)return i;return s;case"no-referrer-when-downgrade":if(cu(i)&&!cu(a))return"no-referrer";return i;default:throw TypeError(`Invalid referrerPolicy: ${n}`)}}function qk(e){let t=(e.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of t)if(n&&Dk.has(n))r=n;return r}var hr=Symbol("Request internals"),Jl=(e)=>typeof e==="object"&&typeof e[hr]==="object",cG=aG(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");class Ti extends vi{constructor(e,t={}){let r;if(Jl(e))r=new URL(e.url);else r=new URL(e),e={};if(r.username!==""||r.password!=="")throw TypeError(`${r} is an url with embedded credentials.`);let n=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n))n=n.toUpperCase();if(!Jl(t)&&"data"in t)cG();if((t.body!=null||Jl(e)&&e.body!==null)&&(n==="GET"||n==="HEAD"))throw TypeError("Request with GET/HEAD method cannot have body");let o=t.body?t.body:Jl(e)&&e.body!==null?au(e):null;super(o,{size:t.size||e.size||0});let i=new Zr(t.headers||e.headers||{});if(o!==null&&!i.has("Content-Type")){let c=mh(o,this);if(c)i.set("Content-Type",c)}let s=Jl(e)?e.signal:null;if("signal"in t)s=t.signal;if(s!=null&&!Sk(s))throw TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let a=t.referrer==null?e.referrer:t.referrer;if(a==="")a="no-referrer";else if(a){let c=new URL(a);a=/^about:(\/\/)?client$/.test(c)?"client":c}else a=void 0;this[hr]={method:n,redirect:t.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:s,referrer:a},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[hr].method}get url(){return sG(this[hr].parsedURL)}get headers(){return this[hr].headers}get redirect(){return this[hr].redirect}get signal(){return this[hr].signal}get referrer(){if(this[hr].referrer==="no-referrer")return"";if(this[hr].referrer==="client")return"about:client";if(this[hr].referrer)return this[hr].referrer.toString();return}get referrerPolicy(){return this[hr].referrerPolicy}set referrerPolicy(e){this[hr].referrerPolicy=Fk(e)}clone(){return new Ti(this)}get[Symbol.toStringTag](){return"Request"}}Object.defineProperties(Ti.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});var Hk=(e)=>{let{parsedURL:t}=e[hr],r=new Zr(e[hr].headers);if(!r.has("Accept"))r.set("Accept","*/*");let n=null;if(e.body===null&&/^(post|put)$/i.test(e.method))n="0";if(e.body!==null){let a=Mk(e);if(typeof a==="number"&&!Number.isNaN(a))n=String(a)}if(n)r.set("Content-Length",n);if(e.referrerPolicy==="")e.referrerPolicy=Uk;if(e.referrer&&e.referrer!=="no-referrer")e[hr].referrer=jk(e);else e[hr].referrer="no-referrer";if(e[hr].referrer instanceof URL)r.set("Referer",e.referrer);if(!r.has("User-Agent"))r.set("User-Agent","node-fetch");if(e.compress&&!r.has("Accept-Encoding"))r.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=e;if(typeof o==="function")o=o(t);let i=Bk(t),s={path:t.pathname+i,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:o};return{parsedURL:t,options:s}};class o1 extends As{constructor(e,t="aborted"){super(e,t)}}dh();e1();var lG=new Set(["data:","http:","https:"]);async function xh(e,t){return new Promise((r,n)=>{let o=new Ti(e,t),{parsedURL:i,options:s}=Hk(o);if(!lG.has(i.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let y=fk(o.url),x=new Ar(y,{headers:{"Content-Type":y.typeFull}});r(x);return}let a=(i.protocol==="https:"?dG:uG).request,{signal:c}=o,d=null,l=()=>{let y=new o1("The operation was aborted.");if(n(y),o.body&&o.body instanceof Gk.Readable)o.body.destroy(y);if(!d||!d.body)return;d.body.emit("error",y)};if(c&&c.aborted){l();return}let p=()=>{l(),h()},m=a(i.toString(),s);if(c)c.addEventListener("abort",p);let h=()=>{if(m.abort(),c)c.removeEventListener("abort",p)};if(m.on("error",(y)=>{n(new Tn(`request to ${o.url} failed, reason: ${y.message}`,"system",y)),h()}),pG(m,(y)=>{if(d&&d.body)d.body.destroy(y)}),process.version<"v14")m.on("socket",(y)=>{let x;y.prependListener("end",()=>{x=y._eventsCount}),y.prependListener("close",(_)=>{if(d&&x<y._eventsCount&&!_){let w=Error("Premature close");w.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",w)}})});m.on("response",(y)=>{m.setTimeout(0);let x=zk(y.rawHeaders);if(yh(y.statusCode)){let v=x.get("Location"),P=null;try{P=v===null?null:new URL(v,o.url)}catch{if(o.redirect!=="manual"){n(new Tn(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),h();return}}switch(o.redirect){case"error":n(new Tn(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),h();return;case"manual":break;case"follow":{if(P===null)break;if(o.counter>=o.follow){n(new Tn(`maximum redirect reached at: ${o.url}`,"max-redirect")),h();return}let k={headers:new Zr(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:au(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!vk(o.url,P)||!Tk(o.url,P))for(let N of["authorization","www-authenticate","cookie","cookie2"])k.headers.delete(N);if(y.statusCode!==303&&o.body&&t.body instanceof Gk.Readable){n(new Tn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),h();return}if(y.statusCode===303||(y.statusCode===301||y.statusCode===302)&&o.method==="POST")k.method="GET",k.body=void 0,k.headers.delete("content-length");let O=qk(x);if(O)k.referrerPolicy=O;r(xh(new Ti(P,k))),h();return}default:return n(TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}if(c)y.once("end",()=>{c.removeEventListener("abort",p)});let _=du(y,new Vk,(v)=>{if(v)n(v)});if(process.version<"v12.10")y.on("aborted",p);let w={url:o.url,status:y.statusCode,statusText:y.statusMessage,headers:x,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=x.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||y.statusCode===204||y.statusCode===304){d=new Ar(_,w),r(d);return}let S={flush:uu.Z_SYNC_FLUSH,finishFlush:uu.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){_=du(_,uu.createGunzip(S),(v)=>{if(v)n(v)}),d=new Ar(_,w),r(d);return}if(A==="deflate"||A==="x-deflate"){let v=du(y,new Vk,(P)=>{if(P)n(P)});v.once("data",(P)=>{if((P[0]&15)===8)_=du(_,uu.createInflate(),(k)=>{if(k)n(k)});else _=du(_,uu.createInflateRaw(),(k)=>{if(k)n(k)});d=new Ar(_,w),r(d)}),v.once("end",()=>{if(!d)d=new Ar(_,w),r(d)});return}if(A==="br"){_=du(_,uu.createBrotliDecompress(),(v)=>{if(v)n(v)}),d=new Ar(_,w),r(d);return}d=new Ar(_,w),r(d)}),$k(m,o).catch(n)})}function pG(e,t){let r=bh.from(`0\r
|
|
66
66
|
\r
|
|
67
67
|
`),n=!1,o=!1,i;e.on("response",(s)=>{let{headers:a}=s;n=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),e.on("socket",(s)=>{let a=()=>{if(n&&!o){let d=Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",t(d)}},c=(d)=>{if(o=bh.compare(d.slice(-5),r)===0,!o&&i)o=bh.compare(i.slice(-3),r.slice(0,3))===0&&bh.compare(d.slice(-2),r.slice(3))===0;i=d};s.prependListener("close",a),s.on("data",c),e.on("close",()=>{s.removeListener("close",a),s.removeListener("data",c)})})}var MV=Vr(FR(),1),$V=Vr(Ah(),1),NV=Vr(fu(),1),zV=Vr(d1(),1),BV=Vr(p1(),1),LV=Vr(b1(),1),x1=Vr(Oh(),1),DV=Vr(ZR(),1);var it;(function(e){e.assertEqual=(o)=>{};function t(o){}e.assertIs=t;function r(o){throw Error()}e.assertNever=r,e.arrayToEnum=(o)=>{let i={};for(let s of o)i[s]=s;return i},e.getValidEnumValues=(o)=>{let i=e.objectKeys(o).filter((a)=>typeof o[o[a]]!=="number"),s={};for(let a of i)s[a]=o[a];return e.objectValues(s)},e.objectValues=(o)=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys==="function"?(o)=>Object.keys(o):(o)=>{let i=[];for(let s in o)if(Object.prototype.hasOwnProperty.call(o,s))i.push(s);return i},e.find=(o,i)=>{for(let s of o)if(i(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(o)=>Number.isInteger(o):(o)=>typeof o==="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map((s)=>typeof s==="string"?`'${s}'`:s).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(o,i)=>{if(typeof i==="bigint")return i.toString();return i}})(it||(it={}));var WR;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(WR||(WR={}));var ge=it.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ii=(e)=>{switch(typeof e){case"undefined":return ge.undefined;case"string":return ge.string;case"number":return Number.isNaN(e)?ge.nan:ge.number;case"boolean":return ge.boolean;case"function":return ge.function;case"bigint":return ge.bigint;case"symbol":return ge.symbol;case"object":if(Array.isArray(e))return ge.array;if(e===null)return ge.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return ge.promise;if(typeof Map<"u"&&e instanceof Map)return ge.map;if(typeof Set<"u"&&e instanceof Set)return ge.set;if(typeof Date<"u"&&e instanceof Date)return ge.date;return ge.object;default:return ge.unknown}};var oe=it.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Pn extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},r={_errors:[]},n=(o)=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let s=r,a=0;while(a<i.path.length){let c=i.path[a];if(a!==i.path.length-1)s[c]=s[c]||{_errors:[]};else s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(i));s=s[c],a++}}};return n(this),r}static assert(e){if(!(e instanceof Pn))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,it.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),r=[];for(let n of this.issues)if(n.path.length>0){let o=n.path[0];t[o]=t[o]||[],t[o].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Pn.create=(e)=>new Pn(e);var UV=(e,t)=>{let r;switch(e.code){case oe.invalid_type:if(e.received===ge.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case oe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,it.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:r=`Unrecognized key(s) in object: ${it.joinValues(e.keys,", ")}`;break;case oe.invalid_union:r="Invalid input";break;case oe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${it.joinValues(e.options)}`;break;case oe.invalid_enum_value:r=`Invalid enum value. Expected ${it.joinValues(e.options)}, received '${e.received}'`;break;case oe.invalid_arguments:r="Invalid function arguments";break;case oe.invalid_return_type:r="Invalid function return type";break;case oe.invalid_date:r="Invalid date";break;case oe.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else it.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case oe.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case oe.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case oe.custom:r="Invalid input";break;case oe.invalid_intersection_types:r="Intersection results could not be merged";break;case oe.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case oe.not_finite:r="Number must be finite";break;default:r=t.defaultError,it.assertNever(e)}return{message:r}},$s=UV;var FV=$s;function ip(){return FV}var Mh=(e)=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",c=n.filter((d)=>!!d).slice().reverse();for(let d of c)a=d(s,{data:t,defaultError:a}).message;return{...o,path:i,message:a}};function fe(e,t){let r=ip(),n=Mh({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===$s?void 0:$s].filter((o)=>!!o)});e.common.issues.push(n)}class Br{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return Le;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let o=await n.key,i=await n.value;r.push({key:o,value:i})}return Br.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:o,value:i}=n;if(o.status==="aborted")return Le;if(i.status==="aborted")return Le;if(o.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(o.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet))r[o.value]=i.value}return{status:e.value,value:r}}}var Le=Object.freeze({status:"aborted"}),xu=(e)=>({status:"dirty",value:e}),Wr=(e)=>({status:"valid",value:e}),_1=(e)=>e.status==="aborted",w1=(e)=>e.status==="dirty",Va=(e)=>e.status==="valid",sp=(e)=>typeof Promise<"u"&&e instanceof Promise;var Se;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(Se||(Se={}));class ao{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var KR=(e,t)=>{if(Va(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Pn(e.common.issues);return this._error=r,this._error}}}};function We(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:o};return{errorMap:(s,a)=>{let{message:c}=e;if(s.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??n??a.defaultError};if(s.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:o}}class Xe{get description(){return this._def.description}_getType(e){return Ii(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ii(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Br,ctx:{common:e.parent.common,data:e.data,parsedType:Ii(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(sp(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)},n=this._parseSync({data:e,path:r.path,parent:r});return KR(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Va(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>Va(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(sp(n)?n:Promise.resolve(n));return KR(r,o)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,o)=>{let i=e(n),s=()=>o.addIssue({code:oe.custom,...r(n)});if(typeof Promise<"u"&&i instanceof Promise)return i.then((a)=>{if(!a)return s(),!1;else return!0});if(!i)return s(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new jo({schema:this,typeName:se.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return Fo.create(this,this._def)}nullable(){return Ns.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this)}promise(){return Tu.create(this,this._def)}or(e){return lp.create([this,e],this._def)}and(e){return pp.create(this,e,this._def)}transform(e){return new jo({...We(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new gp({...We(this._def),innerType:this,defaultValue:t,typeName:se.ZodDefault})}brand(){return new E1({typeName:se.ZodBranded,type:this,...We(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new yp({...We(this._def),innerType:this,catchValue:t,typeName:se.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Fh.create(this,e)}readonly(){return bp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var jV=/^c[^\s-]{8,}$/i,qV=/^[0-9a-z]+$/,HV=/^[0-9A-HJKMNP-TV-Z]{26}$/i,GV=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,VV=/^[a-z0-9_-]{21}$/i,ZV=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,WV=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,KV=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,YV="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",S1,JV=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,QV=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,XV=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,eZ=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tZ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rZ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,YR="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",nZ=new RegExp(`^${YR}$`);function JR(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function oZ(e){return new RegExp(`^${JR(e)}$`)}function iZ(e){let t=`${YR}T${JR(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function sZ(e,t){if((t==="v4"||!t)&&JV.test(e))return!0;if((t==="v6"||!t)&&XV.test(e))return!0;return!1}function aZ(e,t){if(!ZV.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));if(typeof o!=="object"||o===null)return!1;if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&o.alg!==t)return!1;return!0}catch{return!1}}function cZ(e,t){if((t==="v4"||!t)&&QV.test(e))return!0;if((t==="v6"||!t)&&eZ.test(e))return!0;return!1}class Ri extends Xe{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==ge.string){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.string,received:o.parsedType}),Le}let r=new Br,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.length<o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="max"){if(e.data.length>o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="length"){let i=e.data.length>o.value,s=e.data.length<o.value;if(i||s){if(n=this._getOrReturnCtx(e,n),i)fe(n,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});else if(s)fe(n,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});r.dirty()}}else if(o.kind==="email"){if(!KV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"email",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="emoji"){if(!S1)S1=new RegExp(YV,"u");if(!S1.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"emoji",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="uuid"){if(!GV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"uuid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="nanoid"){if(!VV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"nanoid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid"){if(!jV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cuid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid2"){if(!qV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cuid2",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ulid"){if(!HV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"ulid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),fe(n,{validation:"url",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="regex"){if(o.regex.lastIndex=0,!o.regex.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"regex",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="trim")e.data=e.data.trim();else if(o.kind==="includes"){if(!e.data.includes(o.value,o.position))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()}else if(o.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(o.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(o.kind==="startsWith"){if(!e.data.startsWith(o.value))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="endsWith"){if(!e.data.endsWith(o.value))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="datetime"){if(!iZ(o).test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"datetime",message:o.message}),r.dirty()}else if(o.kind==="date"){if(!nZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"date",message:o.message}),r.dirty()}else if(o.kind==="time"){if(!oZ(o).test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"time",message:o.message}),r.dirty()}else if(o.kind==="duration"){if(!WV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"duration",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ip"){if(!sZ(e.data,o.version))n=this._getOrReturnCtx(e,n),fe(n,{validation:"ip",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="jwt"){if(!aZ(e.data,o.alg))n=this._getOrReturnCtx(e,n),fe(n,{validation:"jwt",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cidr"){if(!cZ(e.data,o.version))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cidr",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64"){if(!tZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"base64",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64url"){if(!rZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"base64url",code:oe.invalid_string,message:o.message}),r.dirty()}else it.assertNever(o);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:oe.invalid_string,...Se.errToObj(r)})}_addCheck(e){return new Ri({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Se.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Se.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Se.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Se.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Se.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Se.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Se.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Se.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Se.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Se.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Se.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Se.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Se.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Se.errToObj(t)})}nonempty(e){return this.min(1,Se.errToObj(e))}trim(){return new Ri({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ri({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ri({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Ri.create=(e)=>new Ri({checks:[],typeName:se.ZodString,coerce:e?.coerce??!1,...We(e)});function uZ(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}class wu extends Xe{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==ge.number){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.number,received:o.parsedType}),Le}let r=void 0,n=new Br;for(let o of this._def.checks)if(o.kind==="int"){if(!it.isInteger(e.data))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.invalid_type,expected:"integer",received:"float",message:o.message}),n.dirty()}else if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(uZ(e.data,o.value)!==0)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else if(o.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_finite,message:o.message}),n.dirty()}else it.assertNever(o);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Se.toString(t))}setLimit(e,t,r,n){return new wu({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Se.toString(n)}]})}_addCheck(e){return new wu({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Se.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&it.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}}wu.create=(e)=>new wu({checks:[],typeName:se.ZodNumber,coerce:e?.coerce||!1,...We(e)});class Su extends Xe{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ge.bigint)return this._getInvalidInput(e);let r=void 0,n=new Br;for(let o of this._def.checks)if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(e.data%o.value!==BigInt(0))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else it.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return fe(t,{code:oe.invalid_type,expected:ge.bigint,received:t.parsedType}),Le}gte(e,t){return this.setLimit("min",e,!0,Se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Se.toString(t))}setLimit(e,t,r,n){return new Su({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Se.toString(n)}]})}_addCheck(e){return new Su({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Su.create=(e)=>new Su({checks:[],typeName:se.ZodBigInt,coerce:e?.coerce??!1,...We(e)});class $h extends Xe{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==ge.boolean){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.boolean,received:r.parsedType}),Le}return Wr(e.data)}}$h.create=(e)=>new $h({typeName:se.ZodBoolean,coerce:e?.coerce||!1,...We(e)});class cp extends Xe{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==ge.date){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.date,received:o.parsedType}),Le}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_date}),Le}let r=new Br,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.getTime()<o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()}else if(o.kind==="max"){if(e.data.getTime()>o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()}else it.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new cp({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Se.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Se.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}cp.create=(e)=>new cp({checks:[],coerce:e?.coerce||!1,typeName:se.ZodDate,...We(e)});class Nh extends Xe{_parse(e){if(this._getType(e)!==ge.symbol){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.symbol,received:r.parsedType}),Le}return Wr(e.data)}}Nh.create=(e)=>new Nh({typeName:se.ZodSymbol,...We(e)});class up extends Xe{_parse(e){if(this._getType(e)!==ge.undefined){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.undefined,received:r.parsedType}),Le}return Wr(e.data)}}up.create=(e)=>new up({typeName:se.ZodUndefined,...We(e)});class dp extends Xe{_parse(e){if(this._getType(e)!==ge.null){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.null,received:r.parsedType}),Le}return Wr(e.data)}}dp.create=(e)=>new dp({typeName:se.ZodNull,...We(e)});class zh extends Xe{constructor(){super(...arguments);this._any=!0}_parse(e){return Wr(e.data)}}zh.create=(e)=>new zh({typeName:se.ZodAny,...We(e)});class Za extends Xe{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Wr(e.data)}}Za.create=(e)=>new Za({typeName:se.ZodUnknown,...We(e)});class Oi extends Xe{_parse(e){let t=this._getOrReturnCtx(e);return fe(t,{code:oe.invalid_type,expected:ge.never,received:t.parsedType}),Le}}Oi.create=(e)=>new Oi({typeName:se.ZodNever,...We(e)});class Bh extends Xe{_parse(e){if(this._getType(e)!==ge.undefined){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.void,received:r.parsedType}),Le}return Wr(e.data)}}Bh.create=(e)=>new Bh({typeName:se.ZodVoid,...We(e)});class Uo extends Xe{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ge.array)return fe(t,{code:oe.invalid_type,expected:ge.array,received:t.parsedType}),Le;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;if(i||s)fe(t,{code:i?oe.too_big:oe.too_small,minimum:s?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)fe(t,{code:oe.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)fe(t,{code:oe.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((i,s)=>n.type._parseAsync(new ao(t,i,t.path,s)))).then((i)=>Br.mergeArray(r,i));let o=[...t.data].map((i,s)=>n.type._parseSync(new ao(t,i,t.path,s)));return Br.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new Uo({...this._def,minLength:{value:e,message:Se.toString(t)}})}max(e,t){return new Uo({...this._def,maxLength:{value:e,message:Se.toString(t)}})}length(e,t){return new Uo({...this._def,exactLength:{value:e,message:Se.toString(t)}})}nonempty(e){return this.min(1,e)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...We(t)});function _u(e){if(e instanceof Xt){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Fo.create(_u(n))}return new Xt({...e._def,shape:()=>t})}else if(e instanceof Uo)return new Uo({...e._def,type:_u(e.element)});else if(e instanceof Fo)return Fo.create(_u(e.unwrap()));else if(e instanceof Ns)return Ns.create(_u(e.unwrap()));else if(e instanceof Ci)return Ci.create(e.items.map((t)=>_u(t)));else return e}class Xt extends Xe{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=it.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ge.object){let c=this._getOrReturnCtx(e);return fe(c,{code:oe.invalid_type,expected:ge.object,received:c.parsedType}),Le}let{status:r,ctx:n}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof Oi&&this._def.unknownKeys==="strip")){for(let c in n.data)if(!i.includes(c))s.push(c)}let a=[];for(let c of i){let d=o[c],l=n.data[c];a.push({key:{status:"valid",value:c},value:d._parse(new ao(n,l,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof Oi){let c=this._def.unknownKeys;if(c==="passthrough")for(let d of s)a.push({key:{status:"valid",value:d},value:{status:"valid",value:n.data[d]}});else if(c==="strict"){if(s.length>0)fe(n,{code:oe.unrecognized_keys,keys:s}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let d of s){let l=n.data[d];a.push({key:{status:"valid",value:d},value:c._parse(new ao(n,l,n.path,d)),alwaysSet:d in n.data})}}if(n.common.async)return Promise.resolve().then(async()=>{let c=[];for(let d of a){let l=await d.key,p=await d.value;c.push({key:l,value:p,alwaysSet:d.alwaysSet})}return c}).then((c)=>Br.mergeObjectSync(r,c));else return Br.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return Se.errToObj,new Xt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:Se.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new Xt({...this._def,unknownKeys:"strip"})}passthrough(){return new Xt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Xt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Xt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:se.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Xt({...this._def,catchall:e})}pick(e){let t={};for(let r of it.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new Xt({...this._def,shape:()=>t})}omit(e){let t={};for(let r of it.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new Xt({...this._def,shape:()=>t})}deepPartial(){return _u(this)}partial(e){let t={};for(let r of it.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new Xt({...this._def,shape:()=>t})}required(e){let t={};for(let r of it.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let o=this.shape[r];while(o instanceof Fo)o=o._def.innerType;t[r]=o}return new Xt({...this._def,shape:()=>t})}keyof(){return QR(it.objectKeys(this.shape))}}Xt.create=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strip",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});Xt.strictCreate=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strict",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});Xt.lazycreate=(e,t)=>new Xt({shape:e,unknownKeys:"strip",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});class lp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map((s)=>new Pn(s.ctx.common.issues));return fe(t,{code:oe.invalid_union,unionErrors:i}),Le}if(t.common.async)return Promise.all(r.map(async(o)=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);else{let o=void 0,i=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},d=a._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;else if(d.status==="dirty"&&!o)o={result:d,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map((a)=>new Pn(a));return fe(t,{code:oe.invalid_union,unionErrors:s}),Le}}get options(){return this._def.options}}lp.create=(e,t)=>new lp({options:e,typeName:se.ZodUnion,...We(t)});var ki=(e)=>{if(e instanceof fp)return ki(e.schema);else if(e instanceof jo)return ki(e.innerType());else if(e instanceof mp)return[e.value];else if(e instanceof Wa)return e.options;else if(e instanceof hp)return it.objectValues(e.enum);else if(e instanceof gp)return ki(e._def.innerType);else if(e instanceof up)return[void 0];else if(e instanceof dp)return[null];else if(e instanceof Fo)return[void 0,...ki(e.unwrap())];else if(e instanceof Ns)return[null,...ki(e.unwrap())];else if(e instanceof E1)return ki(e.unwrap());else if(e instanceof bp)return ki(e.unwrap());else if(e instanceof yp)return ki(e._def.innerType);else return[]};class T1 extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.object)return fe(t,{code:oe.invalid_type,expected:ge.object,received:t.parsedType}),Le;let r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);if(!o)return fe(t,{code:oe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Le;if(t.common.async)return o._parseAsync({data:t.data,path:t.path,parent:t});else return o._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let o of t){let i=ki(o.shape[e]);if(!i.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of i){if(n.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,o)}}return new T1({typeName:se.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...We(r)})}}function v1(e,t){let r=Ii(e),n=Ii(t);if(e===t)return{valid:!0,data:e};else if(r===ge.object&&n===ge.object){let o=it.objectKeys(t),i=it.objectKeys(e).filter((a)=>o.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=v1(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===ge.array&&n===ge.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=v1(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else if(r===ge.date&&n===ge.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class pp extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(_1(o)||_1(i))return Le;let s=v1(o.value,i.value);if(!s.valid)return fe(r,{code:oe.invalid_intersection_types}),Le;if(w1(o)||w1(i))t.dirty();return{status:t.value,value:s.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>n(o,i));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pp.create=(e,t,r)=>new pp({left:e,right:t,typeName:se.ZodIntersection,...We(r)});class Ci extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.array)return fe(r,{code:oe.invalid_type,expected:ge.array,received:r.parsedType}),Le;if(r.data.length<this._def.items.length)return fe(r,{code:oe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Le;if(!this._def.rest&&r.data.length>this._def.items.length)fe(r,{code:oe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let o=[...r.data].map((i,s)=>{let a=this._def.items[s]||this._def.rest;if(!a)return null;return a._parse(new ao(r,i,r.path,s))}).filter((i)=>!!i);if(r.common.async)return Promise.all(o).then((i)=>Br.mergeArray(t,i));else return Br.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new Ci({...this._def,rest:e})}}Ci.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ci({items:e,typeName:se.ZodTuple,rest:null,...We(t)})};class Lh extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.object)return fe(r,{code:oe.invalid_type,expected:ge.object,received:r.parsedType}),Le;let n=[],o=this._def.keyType,i=this._def.valueType;for(let s in r.data)n.push({key:o._parse(new ao(r,s,r.path,s)),value:i._parse(new ao(r,r.data[s],r.path,s)),alwaysSet:s in r.data});if(r.common.async)return Br.mergeObjectAsync(t,n);else return Br.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof Xe)return new Lh({keyType:e,valueType:t,typeName:se.ZodRecord,...We(r)});return new Lh({keyType:Ri.create(),valueType:e,typeName:se.ZodRecord,...We(t)})}}class Dh extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.map)return fe(r,{code:oe.invalid_type,expected:ge.map,received:r.parsedType}),Le;let n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([s,a],c)=>({key:n._parse(new ao(r,s,r.path,[c,"key"])),value:o._parse(new ao(r,a,r.path,[c,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let a of i){let c=await a.key,d=await a.value;if(c.status==="aborted"||d.status==="aborted")return Le;if(c.status==="dirty"||d.status==="dirty")t.dirty();s.set(c.value,d.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let a of i){let{key:c,value:d}=a;if(c.status==="aborted"||d.status==="aborted")return Le;if(c.status==="dirty"||d.status==="dirty")t.dirty();s.set(c.value,d.value)}return{status:t.value,value:s}}}}Dh.create=(e,t,r)=>new Dh({valueType:t,keyType:e,typeName:se.ZodMap,...We(r)});class vu extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.set)return fe(r,{code:oe.invalid_type,expected:ge.set,received:r.parsedType}),Le;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)fe(r,{code:oe.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)fe(r,{code:oe.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let o=this._def.valueType;function i(a){let c=new Set;for(let d of a){if(d.status==="aborted")return Le;if(d.status==="dirty")t.dirty();c.add(d.value)}return{status:t.value,value:c}}let s=[...r.data.values()].map((a,c)=>o._parse(new ao(r,a,r.path,c)));if(r.common.async)return Promise.all(s).then((a)=>i(a));else return i(s)}min(e,t){return new vu({...this._def,minSize:{value:e,message:Se.toString(t)}})}max(e,t){return new vu({...this._def,maxSize:{value:e,message:Se.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}vu.create=(e,t)=>new vu({valueType:e,minSize:null,maxSize:null,typeName:se.ZodSet,...We(t)});class ap extends Xe{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.function)return fe(t,{code:oe.invalid_type,expected:ge.function,received:t.parsedType}),Le;function r(s,a){return Mh({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ip(),$s].filter((c)=>!!c),issueData:{code:oe.invalid_arguments,argumentsError:a}})}function n(s,a){return Mh({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ip(),$s].filter((c)=>!!c),issueData:{code:oe.invalid_return_type,returnTypeError:a}})}let o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Tu){let s=this;return Wr(async function(...a){let c=new Pn([]),d=await s._def.args.parseAsync(a,o).catch((m)=>{throw c.addIssue(r(a,m)),c}),l=await Reflect.apply(i,this,d);return await s._def.returns._def.type.parseAsync(l,o).catch((m)=>{throw c.addIssue(n(l,m)),c})})}else{let s=this;return Wr(function(...a){let c=s._def.args.safeParse(a,o);if(!c.success)throw new Pn([r(a,c.error)]);let d=Reflect.apply(i,this,c.data),l=s._def.returns.safeParse(d,o);if(!l.success)throw new Pn([n(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ap({...this._def,args:Ci.create(e).rest(Za.create())})}returns(e){return new ap({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ap({args:e?e:Ci.create([]).rest(Za.create()),returns:t||Za.create(),typeName:se.ZodFunction,...We(r)})}}class fp extends Xe{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}fp.create=(e,t)=>new fp({getter:e,typeName:se.ZodLazy,...We(t)});class mp extends Xe{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return fe(t,{received:t.data,code:oe.invalid_literal,expected:this._def.value}),Le}return{status:"valid",value:e.data}}get value(){return this._def.value}}mp.create=(e,t)=>new mp({value:e,typeName:se.ZodLiteral,...We(t)});function QR(e,t){return new Wa({values:e,typeName:se.ZodEnum,...We(t)})}class Wa extends Xe{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return fe(t,{expected:it.joinValues(r),received:t.parsedType,code:oe.invalid_type}),Le}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return fe(t,{received:t.data,code:oe.invalid_enum_value,options:r}),Le}return Wr(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Wa.create(e,{...this._def,...t})}exclude(e,t=this._def){return Wa.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}Wa.create=QR;class hp extends Xe{_parse(e){let t=it.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ge.string&&r.parsedType!==ge.number){let n=it.objectValues(t);return fe(r,{expected:it.joinValues(n),received:r.parsedType,code:oe.invalid_type}),Le}if(!this._cache)this._cache=new Set(it.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=it.objectValues(t);return fe(r,{received:r.data,code:oe.invalid_enum_value,options:n}),Le}return Wr(e.data)}get enum(){return this._def.values}}hp.create=(e,t)=>new hp({values:e,typeName:se.ZodNativeEnum,...We(t)});class Tu extends Xe{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.promise&&t.common.async===!1)return fe(t,{code:oe.invalid_type,expected:ge.promise,received:t.parsedType}),Le;let r=t.parsedType===ge.promise?t.data:Promise.resolve(t.data);return Wr(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Tu.create=(e,t)=>new Tu({type:e,typeName:se.ZodPromise,...We(t)});class jo extends Xe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===se.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:(i)=>{if(fe(r,i),i.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){let i=n.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async(s)=>{if(t.value==="aborted")return Le;let a=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});if(a.status==="aborted")return Le;if(a.status==="dirty")return xu(a.value);if(t.value==="dirty")return xu(a.value);return a});else{if(t.value==="aborted")return Le;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});if(s.status==="aborted")return Le;if(s.status==="dirty")return xu(s.value);if(t.value==="dirty")return xu(s.value);return s}}if(n.type==="refinement"){let i=(s)=>{let a=n.refinement(s,o);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(s.status==="aborted")return Le;if(s.status==="dirty")t.dirty();return i(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(s.status==="aborted")return Le;if(s.status==="dirty")t.dirty();return i(s.value).then(()=>({status:t.value,value:s.value}))})}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Va(i))return Le;let s=n.transform(i.value,o);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(!Va(i))return Le;return Promise.resolve(n.transform(i.value,o)).then((s)=>({status:t.value,value:s}))});it.assertNever(n)}}jo.create=(e,t,r)=>new jo({schema:e,typeName:se.ZodEffects,effect:t,...We(r)});jo.createWithPreprocess=(e,t,r)=>new jo({schema:t,effect:{type:"preprocess",transform:e},typeName:se.ZodEffects,...We(r)});class Fo extends Xe{_parse(e){if(this._getType(e)===ge.undefined)return Wr(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Fo.create=(e,t)=>new Fo({innerType:e,typeName:se.ZodOptional,...We(t)});class Ns extends Xe{_parse(e){if(this._getType(e)===ge.null)return Wr(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ns.create=(e,t)=>new Ns({innerType:e,typeName:se.ZodNullable,...We(t)});class gp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===ge.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}gp.create=(e,t)=>new gp({innerType:e,typeName:se.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...We(t)});class yp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(sp(n))return n.then((o)=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Pn(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Pn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}yp.create=(e,t)=>new yp({innerType:e,typeName:se.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...We(t)});class Uh extends Xe{_parse(e){if(this._getType(e)!==ge.nan){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.nan,received:r.parsedType}),Le}return{status:"valid",value:e.data}}}Uh.create=(e)=>new Uh({typeName:se.ZodNaN,...We(e)});var Eme=Symbol("zod_brand");class E1 extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Fh extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return Le;if(o.status==="dirty")return t.dirty(),xu(o.value);else return this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return Le;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new Fh({in:e,out:t,typeName:se.ZodPipeline})}}class bp extends Xe{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(Va(n))n.value=Object.freeze(n.value);return n};return sp(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}}bp.create=(e,t)=>new bp({innerType:e,typeName:se.ZodReadonly,...We(t)});var Pme={object:Xt.lazycreate},se;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(se||(se={}));var Ame=Ri.create,Ime=wu.create,kme=Uh.create,Rme=Su.create,Ome=$h.create,Cme=cp.create,Mme=Nh.create,$me=up.create,Nme=dp.create,zme=zh.create,Bme=Za.create,Lme=Oi.create,Dme=Bh.create,Ume=Uo.create,{create:XR,strictCreate:Fme}=Xt,jme=lp.create,qme=T1.create,Hme=pp.create,Gme=Ci.create,Vme=Lh.create,Zme=Dh.create,Wme=vu.create,Kme=ap.create,Yme=fp.create,Jme=mp.create,Qme=Wa.create,Xme=hp.create,ehe=Tu.create,the=jo.create,rhe=Fo.create,nhe=Ns.create,ohe=jo.createWithPreprocess,ihe=Fh.create;var e2;function D(e,t,r){function n(a,c){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let d=s.prototype,l=Object.keys(d);for(let p=0;p<l.length;p++){let m=l[p];if(!(m in a))a[m]=d[m].bind(a)}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let d=r?.Parent?new i:this;n(d,a),(c=d._zod).deferred??(c.deferred=[]);for(let l of d._zod.deferred)l();return d}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var ahe=Symbol("zod_brand");class Mi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class xp extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(e2=globalThis).__zod_globalConfig??(e2.__zod_globalConfig={});var Eu=globalThis.__zod_globalConfig;function An(e){if(e)Object.assign(Eu,e);return Eu}function qh(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function A1(e,t="|"){return e.map((r)=>R1(r)).join(t)}function _p(e,t){if(typeof t==="bigint")return t.toString();return t}function wp(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Hh(e){return e===null||e===void 0}function Gh(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function r2(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}var t2=Symbol("evaluating");function _t(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===t2)return;if(n===void 0)n=t2,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Ka(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function zs(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function I1(e){return JSON.stringify(e)}function n2(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var k1="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Pu(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var o2=wp(()=>{if(Eu.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ya(e){if(Pu(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(Pu(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Vh(e){if(Ya(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var i2=new Set(["string","number","symbol"]);function Bs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fn(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function xe(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function R1(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function s2(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var a2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function c2(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=zs(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return Ka(this,"shape",s),s},checks:[]});return Fn(e,i)}function u2(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=zs(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return Ka(this,"shape",s),s},checks:[]});return Fn(e,i)}function d2(e,t){if(!Ya(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=zs(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Ka(this,"shape",i),i}});return Fn(e,o)}function l2(e,t){if(!Ya(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=zs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Ka(this,"shape",n),n}});return Fn(e,r)}function dZ(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=zs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Ka(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Fn(e,r)}function p2(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=zs(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let d in r){if(!(d in a))throw Error(`Unrecognized key: "${d}"`);if(!r[d])continue;c[d]=e?new e({type:"optional",innerType:a[d]}):a[d]}else for(let d in a)c[d]=e?new e({type:"optional",innerType:a[d]}):a[d];return Ka(this,"shape",c),c},checks:[]});return Fn(t,s)}function f2(e,t,r){let n=zs(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:o[s]})}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Ka(this,"shape",i),i}});return Fn(t,n)}function Ja(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function m2(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Ls(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function jh(e){return typeof e==="string"?e:e?.message}function co(e,t,r){let n=e.message?e.message:jh(e.inst?._zod.def?.error?.(e))??jh(t?.error?.(e))??jh(r.customError?.(e))??jh(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=n,t?.reportInput)a.input=s;return a}function Zh(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function h2(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Qa(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var g2=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,_p,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Wh=D("$ZodError",g2),Sp=D("$ZodError",g2,{Parent:Error});function y2(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function b2(e,t=(r)=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,d=0;while(d<a.length){let l=a[d];if(d!==a.length-1)c[l]=c[l]||{_errors:[]};else c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(s));c=c[l],d++}}}};return n(e),r}var vp=(e)=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Mi;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>co(c,i,An())));throw k1(a,o?.callee),a}return s.value},Kh=vp(Sp),Tp=(e)=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>co(c,i,An())));throw k1(a,o?.callee),a}return s.value},Yh=Tp(Sp),Ep=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Mi;return i.issues.length?{success:!1,error:new(e??Wh)(i.issues.map((s)=>co(s,o,An())))}:{success:!0,data:i.value}},Xa=Ep(Sp),Pp=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>co(s,o,An())))}:{success:!0,data:i.value}},ec=Pp(Sp),x2=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return vp(e)(t,r,o)};var _2=(e)=>(t,r,n)=>vp(e)(t,r,n);var w2=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Tp(e)(t,r,o)};var S2=(e)=>async(t,r,n)=>Tp(e)(t,r,n);var v2=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ep(e)(t,r,o)};var T2=(e)=>(t,r,n)=>Ep(e)(t,r,n);var E2=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Pp(e)(t,r,o)};var P2=(e)=>async(t,r,n)=>Pp(e)(t,r,n);var A2=/^[cC][0-9a-z]{6,}$/,I2=/^[0-9a-z]+$/,k2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,R2=/^[0-9a-vA-V]{20}$/,O2=/^[A-Za-z0-9]{27}$/,C2=/^[a-zA-Z0-9_-]{21}$/,M2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var $2=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,O1=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var N2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var pZ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function z2(){return new RegExp(pZ,"u")}var B2=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,L2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var D2=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,U2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,F2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,C1=/^[A-Za-z0-9_-]*$/;var j2=/^https?$/,q2=/^\+[1-9]\d{6,14}$/,H2="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",G2=new RegExp(`^${H2}$`);function V2(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Z2(e){return new RegExp(`^${V2(e)}$`)}function W2(e){let t=V2({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${H2}T(?:${n})$`)}var K2=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Y2=/^-?\d+n?$/,J2=/^-?\d+$/,M1=/^-?\d+(?:\.\d+)?$/,Q2=/^(?:true|false)$/i,X2=/^null$/i;var e6=/^[^A-Z]*$/,t6=/^[^a-z]*$/;var yr=D("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),r6={number:"number",bigint:"bigint",object:"date"},$1=D("$ZodCheckLessThan",(e,t)=>{yr.init(e,t);let r=r6[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)o.maximum=t.value;else o.exclusiveMaximum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),N1=D("$ZodCheckGreaterThan",(e,t)=>{yr.init(e,t);let r=r6[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)o.minimum=t.value;else o.exclusiveMinimum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),n6=D("$ZodCheckMultipleOf",(e,t)=>{yr.init(e,t),e._zod.onattach.push((r)=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):r2(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),o6=D("$ZodCheckNumberFormat",(e,t)=>{yr.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=a2[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=o,a.maximum=i,r)a.pattern=J2}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var i6=D("$ZodCheckMaxLength",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Hh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)n._zod.bag.maximum=t.maximum}),e._zod.check=(n)=>{let o=n.value;if(o.length<=t.maximum)return;let s=Zh(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),s6=D("$ZodCheckMinLength",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Hh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)n._zod.bag.minimum=t.minimum}),e._zod.check=(n)=>{let o=n.value;if(o.length>=t.minimum)return;let s=Zh(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),a6=D("$ZodCheckLengthEquals",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Hh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(n)=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Zh(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ip=D("$ZodCheckStringFormat",(e,t)=>{var r,n;if(yr.init(e,t),e._zod.onattach.push((o)=>{let i=o._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),c6=D("$ZodCheckRegex",(e,t)=>{Ip.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),u6=D("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=e6),Ip.init(e,t)}),d6=D("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=t6),Ip.init(e,t)}),l6=D("$ZodCheckIncludes",(e,t)=>{yr.init(e,t);let r=Bs(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),p6=D("$ZodCheckStartsWith",(e,t)=>{yr.init(e,t);let r=new RegExp(`^${Bs(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),f6=D("$ZodCheckEndsWith",(e,t)=>{yr.init(e,t);let r=new RegExp(`.*${Bs(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var m6=D("$ZodCheckOverwrite",(e,t)=>{yr.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class z1{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
68
68
|
`).filter((i)=>i),n=Math.min(...r.map((i)=>i.length-i.trimStart().length)),o=r.map((i)=>i.slice(n)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[""]).map((o)=>` ${o}`)];return new e(...t,n.join(`
|
|
@@ -133,13 +133,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
133
133
|
`:`[${n[c]}\r
|
|
134
134
|
]`;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 Lg(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===se.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Ht(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===se.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Bg(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===se.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===se.ZodBranded&&e.keyType._def.type._def.typeName===se.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=zg(e.keyType._def,t);return{...r,propertyNames:o}}return r}function wO(e,t){if(t.mapStrategy==="record")return Lg(e,t);let r=De(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ht(t),n=De(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ht(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function SO(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 vO(e){return e.target==="openAi"?void 0:{not:Ht({...e,currentPath:[...e.currentPath,"not"]})}}function TO(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Wp={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function PO(e,t){if(t.target==="openApi3")return EO(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in Wp)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Wp[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 EO(e,t)}var EO=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>De(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 AO(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:Wp[e.innerType._def.typeName],nullable:!0};return{type:[Wp[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=De(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=De(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function IO(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",sS(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"minimum",n.value,n.message,t);else at(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;at(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"maximum",n.value,n.message,t);else at(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;at(r,"maximum",n.value,n.message,t)}break;case"multipleOf":at(r,"multipleOf",n.value,n.message,t);break}return r}function kO(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 d=BY(c);if(d&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();d=!1}let l=De(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(l===void 0)continue;if(n.properties[a]=l,!d)o.push(a)}if(o.length)n.required=o;let s=zY(e,t);if(s!==void 0)n.additionalProperties=s;return n}function zY(e,t){if(e.catchall._def.typeName!=="ZodNever")return De(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 BY(e){try{return e.isOptional()}catch{return!0}}var RO=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return De(e.innerType._def,t);let r=De(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ht(t)},r]}:Ht(t)};var OO=(e,t)=>{if(t.pipeStrategy==="input")return De(e.in._def,t);else if(t.pipeStrategy==="output")return De(e.out._def,t);let r=De(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=De(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function CO(e,t){return De(e.type._def,t)}function MO(e,t){let n={type:"array",uniqueItems:!0,items:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)at(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)at(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function $O(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>De(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:De(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)=>De(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function NO(e){return{not:Ht(e)}}function zO(e){return Ht(e)}var BO=(e,t)=>De(e.innerType._def,t);var LO=(e,t,r)=>{switch(t){case se.ZodString:return Bg(e,r);case se.ZodNumber:return IO(e,r);case se.ZodObject:return kO(e,r);case se.ZodBigInt:return pO(e,r);case se.ZodBoolean:return fO();case se.ZodDate:return aS(e,r);case se.ZodUndefined:return NO(r);case se.ZodNull:return TO(r);case se.ZodArray:return lO(e,r);case se.ZodUnion:case se.ZodDiscriminatedUnion:return PO(e,r);case se.ZodIntersection:return bO(e,r);case se.ZodTuple:return $O(e,r);case se.ZodRecord:return Lg(e,r);case se.ZodLiteral:return xO(e,r);case se.ZodEnum:return yO(e);case se.ZodNativeEnum:return SO(e);case se.ZodNullable:return AO(e,r);case se.ZodOptional:return RO(e,r);case se.ZodMap:return wO(e,r);case se.ZodSet:return MO(e,r);case se.ZodLazy:return()=>e.getter()._def;case se.ZodPromise:return CO(e,r);case se.ZodNaN:case se.ZodNever:return vO(r);case se.ZodEffects:return gO(e,r);case se.ZodAny:return Ht(r);case se.ZodUnknown:return zO(r);case se.ZodDefault:return hO(e,r);case se.ZodBranded:return zg(e,r);case se.ZodReadonly:return BO(e,r);case se.ZodCatch:return mO(e,r);case se.ZodPipeline:return OO(e,r);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return((n)=>{return})(t)}};function De(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==cO)return a}if(n&&!r){let a=LY(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=LO(e,e.typeName,t),s=typeof i==="function"?De(i(),t):i;if(s)DY(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var LY=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ng(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`),Ht(t);return t.$refStrategy==="seen"?Ht(t):void 0}}},DY=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var dS=(e,t)=>{let r=dO(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,l])=>({...c,[d]:De(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??Ht(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=De(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ht(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 UY(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 lS(e,t){if(jn(e))return Bw(e,{target:UY(t?.target),io:t?.pipeStrategy??"input"});return dS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function pS(e){let r=js(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=dg(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function fS(e,t){let r=Fs(e,t);if(!r.success)throw r.error;return r.data}var FY=60000;class mS{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(bg,(t)=>{this._oncancel(t)}),this.setNotificationHandler(_g,(t)=>{this._onprogress(t)}),this.setRequestHandler(xg,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(wg,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new ve(Me.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(vg,async(t,r)=>{let n=async()=>{let o=t.params.taskId;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,d=this._requestResolvers.get(c);if(d)if(this._requestResolvers.delete(c),s.type==="response")d(a);else{let l=a,p=new ve(l.error.code,l.error.message,l.error.data);d(p)}else{let l=s.type==="response"?"Response":"Error";this._onerror(Error(`${l} 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 ve(Me.InvalidParams,`Task not found: ${o}`);if(!Hs(i.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(Hs(i.status)){let s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[qs]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Tg,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 ve(Me.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Pg,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new ve(Me.InvalidParams,`Task not found: ${t.params.taskId}`);if(Hs(n.status))throw new ve(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);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new ve(Me.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof ve)throw n;throw new ve(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),ve.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),Dp(o)||K5(o))this._onresponse(o);else if(Vw(o))this._onrequest(o,i);else if(W5(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=ve.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?.[qs]?.taskId;if(r===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:Me.MethodNotFound,message:"Method not found"}};if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId).catch((l)=>this._onerror(Error(`Failed to enqueue error response: ${l}`)));else n?.send(d).catch((l)=>this._onerror(Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let s=G5(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,c={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(d)=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};if(o)l.relatedTask={taskId:o};await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new ve(Me.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};if(o&&!m.relatedTask)m.relatedTask={taskId:o};let h=m.relatedTask?.taskId??o;if(h&&a)await a.updateTaskStatus(h,"input_required");return await this.request(d,l,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(s)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,c)).then(async(d)=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},n?.sessionId);else await n?.send(l)},async(d)=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:Me.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId);else await n?.send(l)}).catch((d)=>this._onerror(Error(`Failed to send response: ${d}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)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),Dp(e))r(e);else{let i=new ve(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(Dp(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(Dp(e))n(e);else{let i=ve.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 ve?i:new ve(Me.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Mu,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new ve(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},Hs(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 ve(Me.InternalError,`Task ${o} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new ve(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 ve?i:new ve(Me.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,d)=>{let l=(w)=>{d(w)};if(!this._transport){l(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(w){l(w);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};if(r?.onprogress)this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(s)m.params={...m.params,task:s};if(a)m.params={...m.params,_meta:{...m.params?._meta||{},[qs]:a}};let h=(w)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let A=w instanceof ve?w:new ve(Me.RequestTimeout,String(w));d(A)};this._responseHandlers.set(p,(w)=>{if(r?.signal?.aborted)return;if(w instanceof Error)return d(w);try{let A=Fs(t,w.result);if(!A.success)d(A.error);else c(A.data)}catch(A){d(A)}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});let y=r?.timeout??FY,x=()=>h(ve.fromError(Me.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,r?.maxTotalTimeout,x,r?.resetTimeoutOnProgress??!1);let _=a?.taskId;if(_){let w=(A)=>{let S=this._responseHandlers.get(p);if(S)S(A);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(_,{type:"request",message:m,timestamp:Date.now()}).catch((A)=>{this._cleanupTimeout(p),d(A)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((w)=>{this._cleanupTimeout(p),d(w)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Sg,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},Eg,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Q5,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||{},[qs]: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||{},[qs]: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||{},[qs]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=pS(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let i=fS(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=pS(e);this._notificationHandlers.set(r,(n)=>{let o=fS(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,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"&&Vw(n.message)){let o=n.message.id,i=this._requestResolvers.get(o);if(i)i(new ve(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){let r=this._options?.defaultTaskPollInterval??1000;try{let n=await this._taskStore?.getTask(e);if(n?.pollInterval)r=n.pollInterval}catch{}return new Promise((n,o)=>{if(t.aborted){o(new ve(Me.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(i),o(new ve(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 ve(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=Hp.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),Hs(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 ve(Me.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Hs(s.status))throw new ve(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=Hp.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Hs(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function DO(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function UO(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(DO(s)&&DO(i))r[o]={...s,...i};else r[o]=i}return r}var S4=Vr(uv(),1),v4=Vr(w4(),1);function uie(){let e=new S4.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return v4.default(e),e}class xv{constructor(e){this._ajv=e??uie()}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 _v{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((d)=>d.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((d)=>d.type==="tool_use");if(i){if(o.some((d)=>d.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 d=new Set(a.filter((p)=>p.type==="tool_use").map((p)=>p.id)),l=new Set(o.filter((p)=>p.type==="tool_result").map((p)=>p.toolUseId));if(d.size!==l.size||![...d].every((p)=>l.has(p)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Zp,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},zu,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 T4(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 E4(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 wv extends mS{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Vp.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 xv,this.setRequestHandler(Kw,(r)=>this._oninitialize(r)),this.setNotificationHandler(Yw,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(nS,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=Vp.safeParse(i);if(s.success)this._loggingLevels.set(o,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new _v(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=UO(this._capabilities,e)}setRequestHandler(e,t){let n=js(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o;if(jn(n)){let s=n;o=s._zod?.def?.value??s.value}else{let s=n;o=s._def?.value??s.value}if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(a,c)=>{let d=Fs(Nu,a);if(!d.success){let h=d.error instanceof Error?d.error.message:String(d.error);throw new ve(Me.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:l}=d.data,p=await Promise.resolve(t(a,c));if(l.task){let h=Fs(Mu,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new ve(Me.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let m=Fs(Mg,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new ve(Me.InvalidParams,`Invalid tools/call result: ${h}`)}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){E4(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;T4(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:j5.includes(t)?t:Hw,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"},yg)}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((l)=>l.type==="tool_use").map((l)=>l.id)),d=new Set(n.filter((l)=>l.type==="tool_result").map((l)=>l.toolUseId));if(c.size!==d.size||![...c].every((l)=>d.has(l)))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},oS,t);return this.request({method:"sampling/createMessage",params:e},Zp,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},zu,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},zu,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new ve(Me.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof ve)throw i;throw new ve(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},iS,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 A4=Symbol.for("mcp.completable");function Sv(e){return!!e&&typeof e==="object"&&A4 in e}function I4(e){return e[A4]?.complete}var P4;(function(e){e.Completable="McpCompletable"})(P4||(P4={}));var die=/^[A-Za-z0-9._-]{1,128}$/;function lie(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(!die.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 pie(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 vv(e){let t=lie(e);return pie(e,t.warnings),t.isValid}class Tv{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)}}class Pv{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new wv(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new Tv(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(Qs(Cg)),this.server.assertCanSetRequestHandler(Qs(Nu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Cg,()=>({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=Ru(t.inputSchema);return n?lS(n,{strictUnions:!0,pipeStrategy:"input"}):fie})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=Ru(t.outputSchema);if(n)r.outputSchema=lS(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Nu,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new ve(Me.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new ve(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 ve(Me.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new ve(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 ve){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(!e.inputSchema)return;let o=Ru(e.inputSchema)??e.inputSchema,i=await cg(o,t);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ug(s);throw new ve(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 ve(Me.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=Ru(e.outputSchema),o=await cg(n,t.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",s=ug(i);throw new ve(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,d=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((p)=>setTimeout(p,d));let l=await r.taskStore.getTask(a);if(!l)throw new ve(Me.InternalError,`Task ${a} not found during polling`);c=l}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(Qs($g)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler($g,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return oO(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return iO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new ve(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 ve(Me.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new ve(Me.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return xf;let o=js(r.argsSchema)?.[e.params.argument.name];if(!Sv(o))return xf;let i=I4(o);if(!i)return xf;let s=await i(e.params.argument.value,e.params.context);return R4(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 xf;throw new ve(Me.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return xf;let o=await n(e.params.argument.value,e.params.context);return R4(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(Qs(Ag)),this.server.assertCanSetRequestHandler(Qs(Ig)),this.server.assertCanSetRequestHandler(Qs(kg)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ag,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(Ig,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(kg,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new ve(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 ve(Me.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(Qs(Rg)),this.server.assertCanSetRequestHandler(Qs(Og)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Rg,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?mie(t.argsSchema):void 0}))})),this.server.setRequestHandler(Og,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new ve(Me.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new ve(Me.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=Ru(r.argsSchema),o=await cg(n,e.params.arguments);if(!o.success){let a="error"in o?o.error:"Unknown error",c=ug(a);throw new ve(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:nc(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=nc(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 fg?a._def?.innerType:a;return Sv(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,n,o,i,s,a,c){vv(e);let d={title:t,description:r,inputSchema:k4(n),outputSchema:k4(o),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:(l)=>{if(typeof l.name<"u"&&l.name!==e){if(typeof l.name==="string")vv(l.name);if(delete this._registeredTools[e],l.name)this._registeredTools[l.name]=d}if(typeof l.title<"u")d.title=l.title;if(typeof l.description<"u")d.description=l.description;if(typeof l.paramsSchema<"u")d.inputSchema=nc(l.paramsSchema);if(typeof l.outputSchema<"u")d.outputSchema=nc(l.outputSchema);if(typeof l.callback<"u")d.handler=l.callback;if(typeof l.annotations<"u")d.annotations=l.annotations;if(typeof l._meta<"u")d._meta=l._meta;if(typeof l.enabled<"u")d.enabled=l.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}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(Ev(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!Ev(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 fie={type:"object",properties:{}};function O4(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function C4(e){return"_def"in e||"_zod"in e||O4(e)}function Ev(e){if(typeof e!=="object"||e===null)return!1;if(C4(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(O4)}function k4(e){if(!e)return;if(Ev(e))return nc(e);if(!C4(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function mie(e){let t=js(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=i5(n),i=s5(n);return{name:r,description:o,required:!i}})}function Qs(e){let r=js(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=dg(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function R4(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var xf={completion:{values:[],hasMore:!1}};import $4 from"node:process";class Av{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
135
135
|
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),hie(t)}clear(){this._buffer=void 0}}function hie(e){return Y5.parse(JSON.parse(e))}function M4(e){return JSON.stringify(e)+`
|
|
136
|
-
`}class Iv{constructor(e=$4.stdin,t=$4.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Av,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=M4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var w0={name:"@0xmonaco/mcp-server",version:"1.0.58",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.58","@0xmonaco/types":"1.0.58","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.56.3",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var S0=["read","market-maker","full"],Wo=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours 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 24 hours 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:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],m_e=Wo.map((e)=>e.name),N4=Wo.filter((e)=>e.authMode==="public").map((e)=>e.name),h_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),g_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),y_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),b_e=Wo.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),z4=Wo.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var yie=new Map(Wo.map((e)=>[e.name,e.sideEffect]));function B4(e){let t=yie.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var L4={read:0,"market-maker":1,full:2},kv=N4,Rv=Object.fromEntries(Wo.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),D4=Object.fromEntries(Object.entries(Rv).map(([e,t])=>[e,t.capability])),w_e=new Set(z4);function U4(e){let t=Rv[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function F4(e){return U4(e)==="read"}function j4(e,t){if(t.network==="mainnet"&&Rv[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(kv.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return L4[t.capability]>=L4[U4(e)]}var bie=new Set([...kv,...Object.keys(D4)]),xie={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 q4(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function lc(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&&!S0.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${S0.join(", ")}.`);let c=a||"read",d=q4(e.MONACO_TOOL_ALLOWLIST),l=q4(e.MONACO_TOOL_DENYLIST),p=[...d,...l].filter((y)=>!bie.has(y)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||xie[s],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");h=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:d,deny:l,delegatedOwnerUserId:h}}function _ie(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function en(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>en(r));let t={};for(let[r,n]of Object.entries(e))t[_ie(r)]=typeof n==="object"&&n!==null?en(n):n;return t}function H4(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ov=(e)=>e?`"${e}" `:"";function wie(e,t=""){if(typeof e!=="number")throw TypeError(Ov(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Ov(t)+"expected integer >= 0, got "+e);return e}function v0(e,t,r=""){if(H4(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)wie(t,"length");let n=H4(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=Ov(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var Sie=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},G4=(e,t)=>{Sie(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 Cv(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function Z4(e,t){v0(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function T0(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function E0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function xo(e,t){return e<<32-t|e>>>t}var W4=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),vie=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Li(e){if(v0(e),W4)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=vie[e[r]];return t}function V4(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function _f(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(W4)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=V4(e.charCodeAt(i)),a=V4(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 pc(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{T0(t)}}function Tie(e,t,r="opts"){if(G4(e,"defaults"),t!==void 0)G4(t,r);return Object.assign(Object.create(null),e,t)}function K4(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=Tie({},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)}var Y4=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Bv();hc();Jv();td();Af();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Jo=BigInt(0),rn=BigInt(1),z8=BigInt(2),jie=BigInt(8),qie={zip215:!0};function Hie(e){let t=If(e);return Hi(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function B8(e){let t=Hie(e),{Fp:r,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,d=z8<<BigInt(a*8)-rn,l=r.create,p=Gi(t.n,t.nBitLength);function m(z,F){let Y=r.sqr(z),we=r.sqr(F),te=r.add(r.mul(t.a,Y),we),$e=r.add(r.ONE,r.mul(t.d,r.mul(Y,we)));return r.eql(te,$e)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((z,F)=>{try{return{isValid:!0,value:r.sqrt(z*r.inv(F))}}catch(Y){return{isValid:!1,value:Jo}}}),y=t.adjustScalarBytes||((z)=>z),x=t.domain||((z,F,Y)=>{if(Yo("phflag",Y),F.length||Y)throw Error("Contexts/pre-hash are not supported");return z});function _(z,F,Y=!1){let we=Y?rn:Jo;Rn("coordinate "+z,F,we,d)}function w(z){if(!(z instanceof v))throw Error("ExtendedPoint expected")}let A=Xu((z,F)=>{let{ex:Y,ey:we,ez:te}=z,$e=z.is0();if(F==null)F=$e?jie:r.inv(te);let Te=l(Y*F),Pe=l(we*F),tt=l(te*F);if($e)return{x:Jo,y:rn};if(tt!==rn)throw Error("invZ was invalid");return{x:Te,y:Pe}}),S=Xu((z)=>{let{a:F,d:Y}=t;if(z.is0())throw Error("bad point: ZERO");let{ex:we,ey:te,ez:$e,et:Te}=z,Pe=l(we*we),tt=l(te*te),yt=l($e*$e),ft=l(yt*yt),q=l(Pe*F),ne=l(yt*l(q+tt)),ce=l(ft+l(Y*l(Pe*tt)));if(ne!==ce)throw Error("bad point: equation left != right (1)");let he=l(we*te),Q=l($e*Te);if(he!==Q)throw Error("bad point: equation left != right (2)");return!0});class v{constructor(z,F,Y,we){_("x",z),_("y",F),_("z",Y,!0),_("t",we),this.ex=z,this.ey=F,this.ez=Y,this.et=we,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(z){if(z instanceof v)throw Error("extended point not allowed");let{x:F,y:Y}=z||{};return _("x",F),_("y",Y),new v(F,Y,rn,l(F*Y))}static normalizeZ(z){let F=ed(r,z.map((Y)=>Y.ez));return z.map((Y,we)=>Y.toAffine(F[we])).map(v.fromAffine)}static msm(z,F){return $0(v,p,z,F)}_setWindowSize(z){O.setWindowSize(this,z)}assertValidity(){S(this)}equals(z){w(z);let{ex:F,ey:Y,ez:we}=this,{ex:te,ey:$e,ez:Te}=z,Pe=l(F*Te),tt=l(te*we),yt=l(Y*Te),ft=l($e*we);return Pe===tt&&yt===ft}is0(){return this.equals(v.ZERO)}negate(){return new v(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:z}=t,{ex:F,ey:Y,ez:we}=this,te=l(F*F),$e=l(Y*Y),Te=l(z8*l(we*we)),Pe=l(z*te),tt=F+Y,yt=l(l(tt*tt)-te-$e),ft=Pe+$e,q=ft-Te,ne=Pe-$e,ce=l(yt*q),he=l(ft*ne),Q=l(yt*ne),Be=l(q*ft);return new v(ce,he,Be,Q)}add(z){w(z);let{a:F,d:Y}=t,{ex:we,ey:te,ez:$e,et:Te}=this,{ex:Pe,ey:tt,ez:yt,et:ft}=z,q=l(we*Pe),ne=l(te*tt),ce=l(Te*Y*ft),he=l($e*yt),Q=l((we+te)*(Pe+tt)-q-ne),Be=he-ce,bt=he+ce,xt=l(ne-F*q),Qe=l(Q*Be),vt=l(bt*xt),wt=l(Q*xt),Hr=l(Be*bt);return new v(Qe,vt,Hr,wt)}subtract(z){return this.add(z.negate())}wNAF(z){return O.wNAFCached(this,z,v.normalizeZ)}multiply(z){let F=z;Rn("scalar",F,rn,n);let{p:Y,f:we}=this.wNAF(F);return v.normalizeZ([Y,we])[0]}multiplyUnsafe(z,F=v.ZERO){let Y=z;if(Rn("scalar",Y,Jo,n),Y===Jo)return k;if(this.is0()||Y===rn)return this;return O.wNAFCachedUnsafe(this,Y,v.normalizeZ,F)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(z){return A(this,z)}clearCofactor(){let{h:z}=t;if(z===rn)return this;return this.multiplyUnsafe(z)}static fromHex(z,F=!1){let{d:Y,a:we}=t,te=r.BYTES;z=Gt("pointHex",z,te),Yo("zip215",F);let $e=z.slice(),Te=z[te-1];$e[te-1]=Te&-129;let Pe=bc($e),tt=F?d:r.ORDER;Rn("pointHex.y",Pe,Jo,tt);let yt=l(Pe*Pe),ft=l(yt-rn),q=l(Y*yt-we),{isValid:ne,value:ce}=h(ft,q);if(!ne)throw Error("Point.fromHex: invalid y coordinate");let he=(ce&rn)===rn,Q=(Te&128)!==0;if(!F&&ce===Jo&&Q)throw Error("Point.fromHex: x=0 and x_0=1");if(Q!==he)ce=l(-ce);return v.fromAffine({x:ce,y:Pe})}static fromPrivateKey(z){let{scalar:F}=R(z);return P.multiply(F)}toRawBytes(){let{x:z,y:F}=this.toAffine(),Y=Qu(F,r.BYTES);return Y[Y.length-1]|=z&rn?128:0,Y}toHex(){return ra(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,rn,l(t.Gx*t.Gy)),v.ZERO=new v(Jo,rn,rn,Jo);let{BASE:P,ZERO:k}=v,O=M0(v,a*8);function N(z){return Et(z,n)}function j(z){return N(bc(z))}function R(z){let F=r.BYTES;z=Gt("private key",z,F);let Y=Gt("hashed private key",i(z),2*F),we=y(Y.slice(0,F)),te=Y.slice(F,2*F),$e=j(we);return{head:we,prefix:te,scalar:$e}}function K(z){let{head:F,prefix:Y,scalar:we}=R(z),te=P.multiply(we),$e=te.toRawBytes();return{head:F,prefix:Y,scalar:we,point:te,pointBytes:$e}}function Z(z){return K(z).pointBytes}function re(z=Uint8Array.of(),...F){let Y=na(...F);return j(i(x(Y,Gt("context",z),!!o)))}function pe(z,F,Y={}){if(z=Gt("message",z),o)z=o(z);let{prefix:we,scalar:te,pointBytes:$e}=K(F),Te=re(Y.context,we,z),Pe=P.multiply(Te).toRawBytes(),tt=re(Y.context,Pe,$e,z),yt=N(Te+tt*te);Rn("signature.s",yt,Jo,n);let ft=na(Pe,Qu(yt,r.BYTES));return Gt("result",ft,r.BYTES*2)}let U=qie;function ee(z,F,Y,we=U){let{context:te,zip215:$e}=we,Te=r.BYTES;if(z=Gt("signature",z,2*Te),F=Gt("message",F),Y=Gt("publicKey",Y,Te),$e!==void 0)Yo("zip215",$e);if(o)F=o(F);let Pe=bc(z.slice(Te,2*Te)),tt,yt,ft;try{tt=v.fromHex(Y,$e),yt=v.fromHex(z.slice(0,Te),$e),ft=P.multiplyUnsafe(Pe)}catch(ce){return!1}if(!$e&&tt.isSmallOrder())return!1;let q=re(te,yt.toRawBytes(),tt.toRawBytes(),F);return yt.add(tt.multiplyUnsafe(q)).subtract(ft).clearCofactor().equals(v.ZERO)}return P._setWindowSize(8),{CURVE:t,getPublicKey:Z,sign:pe,verify:ee,ExtendedPoint:v,utils:{getExtendedPublicKey:K,randomPrivateKey:()=>s(r.BYTES),precompute(z=8,F=v.BASE){return F._setWindowSize(z),F.multiply(BigInt(3)),F}}}}td();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Qv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),L8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),twe=BigInt(0),Gie=BigInt(1),D8=BigInt(2),rwe=BigInt(3),Vie=BigInt(5),Zie=BigInt(8);function Wie(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=Qv,a=e*e%i*e%i,c=Vt(a,D8,i)*a%i,d=Vt(c,Gie,i)*e%i,l=Vt(d,Vie,i)*d%i,p=Vt(l,t,i)*l%i,m=Vt(p,r,i)*p%i,h=Vt(m,n,i)*m%i,y=Vt(h,o,i)*h%i,x=Vt(y,o,i)*h%i,_=Vt(x,t,i)*l%i;return{pow_p_5_8:Vt(_,D8,i)*e%i,b2:a}}function Kie(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Yie(e,t){let r=Qv,n=Et(t*t*t,r),o=Et(n*n*t,r),i=Wie(e*o).pow_p_5_8,s=Et(e*n*i,r),a=Et(t*s*s,r),c=s,d=Et(s*L8,r),l=a===e,p=a===Et(-e,r),m=a===Et(-e*L8,r);if(l)s=c;if(p||m)s=d;if(k8(s,r))s=Et(-s,r);return{isValid:l||p,value:s}}var U8=(()=>Gi(Qv,void 0,!0))(),Jie=(()=>({a:U8.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:U8,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Zie,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:y8,randomBytes:I0,adjustScalarBytes:Kie,uvRatio:Yie}))(),rd=(()=>B8(Jie))();var Qie=(e)=>e/4294967296|0,Xie=(e)=>e>>>0;function F8(e,t,r,n){let o=Qie(r),i=Xie(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}function j8(e,t,r){return e&t^~e&r}function q8(e,t,r){return e&t^e&r^t&r}class Xv{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=E0(this.buffer)}update(e){Cv(this),v0(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=E0(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){Cv(this),Z4(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);F8(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:E0(e),a=this.outputLen,c=a/4,d=this.get();if(a%4||c>d.length)throw Error("invalid outputLen");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],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 H8=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ese=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]),oa=new Uint32Array(64);class G8 extends Xv{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 l=0;l<16;l++,t+=4)oa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=oa[l-15],m=oa[l-2],h=xo(p,7)^xo(p,18)^p>>>3,y=xo(m,17)^xo(m,19)^m>>>10;oa[l]=y+oa[l-7]+h+oa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=xo(s,6)^xo(s,11)^xo(s,25),m=d+p+j8(s,a,c)+ese[l]+oa[l]|0,y=(xo(r,2)^xo(r,13)^xo(r,22))+q8(r,n,o)|0;d=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,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){T0(oa)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),T0(this.buffer)}}class V8 extends G8{constructor(){super(32,H8)}}var N0=K4(()=>new V8,Y4(1));function z0(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=rd.utils.randomPrivateKey();return{publicKey:rd.getPublicKey(e),privateKey:e}}function B0(e){return Li(e.publicKey)}function L0(e){return Li(e.privateKey)}function Z8(e,t){return{publicKey:_f(e),privateKey:_f(t)}}function W8(e){return Li(N0(e))}function K8(e,t,r,n){return`${e.toUpperCase()}
|
|
136
|
+
`}class Iv{constructor(e=$4.stdin,t=$4.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Av,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=M4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var w0={name:"@0xmonaco/mcp-server",version:"1.0.59",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.59","@0xmonaco/types":"1.0.59","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.56.3",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var S0=["read","market-maker","full"],Wo=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours 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 24 hours 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:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],m_e=Wo.map((e)=>e.name),N4=Wo.filter((e)=>e.authMode==="public").map((e)=>e.name),h_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),g_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),y_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),b_e=Wo.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),z4=Wo.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var yie=new Map(Wo.map((e)=>[e.name,e.sideEffect]));function B4(e){let t=yie.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var L4={read:0,"market-maker":1,full:2},kv=N4,Rv=Object.fromEntries(Wo.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),D4=Object.fromEntries(Object.entries(Rv).map(([e,t])=>[e,t.capability])),w_e=new Set(z4);function U4(e){let t=Rv[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function F4(e){return U4(e)==="read"}function j4(e,t){if(t.network==="mainnet"&&Rv[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(kv.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return L4[t.capability]>=L4[U4(e)]}var bie=new Set([...kv,...Object.keys(D4)]),xie={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 q4(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function lc(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&&!S0.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${S0.join(", ")}.`);let c=a||"read",d=q4(e.MONACO_TOOL_ALLOWLIST),l=q4(e.MONACO_TOOL_DENYLIST),p=[...d,...l].filter((y)=>!bie.has(y)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||xie[s],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");h=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:d,deny:l,delegatedOwnerUserId:h}}function _ie(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function en(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>en(r));let t={};for(let[r,n]of Object.entries(e))t[_ie(r)]=typeof n==="object"&&n!==null?en(n):n;return t}function H4(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ov=(e)=>e?`"${e}" `:"";function wie(e,t=""){if(typeof e!=="number")throw TypeError(Ov(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Ov(t)+"expected integer >= 0, got "+e);return e}function v0(e,t,r=""){if(H4(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)wie(t,"length");let n=H4(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=Ov(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var Sie=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},G4=(e,t)=>{Sie(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 Cv(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function Z4(e,t){v0(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function T0(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function E0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function xo(e,t){return e<<32-t|e>>>t}var W4=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),vie=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Li(e){if(v0(e),W4)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=vie[e[r]];return t}function V4(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function _f(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(W4)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=V4(e.charCodeAt(i)),a=V4(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 pc(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{T0(t)}}function Tie(e,t,r="opts"){if(G4(e,"defaults"),t!==void 0)G4(t,r);return Object.assign(Object.create(null),e,t)}function K4(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=Tie({},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)}var Y4=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Bv();hc();Jv();td();Af();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Jo=BigInt(0),rn=BigInt(1),z8=BigInt(2),jie=BigInt(8),qie={zip215:!0};function Hie(e){let t=If(e);return Hi(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function B8(e){let t=Hie(e),{Fp:r,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,d=z8<<BigInt(a*8)-rn,l=r.create,p=Gi(t.n,t.nBitLength);function m(z,F){let Y=r.sqr(z),we=r.sqr(F),te=r.add(r.mul(t.a,Y),we),$e=r.add(r.ONE,r.mul(t.d,r.mul(Y,we)));return r.eql(te,$e)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((z,F)=>{try{return{isValid:!0,value:r.sqrt(z*r.inv(F))}}catch(Y){return{isValid:!1,value:Jo}}}),y=t.adjustScalarBytes||((z)=>z),x=t.domain||((z,F,Y)=>{if(Yo("phflag",Y),F.length||Y)throw Error("Contexts/pre-hash are not supported");return z});function _(z,F,Y=!1){let we=Y?rn:Jo;Rn("coordinate "+z,F,we,d)}function w(z){if(!(z instanceof v))throw Error("ExtendedPoint expected")}let A=Xu((z,F)=>{let{ex:Y,ey:we,ez:te}=z,$e=z.is0();if(F==null)F=$e?jie:r.inv(te);let Ee=l(Y*F),Ae=l(we*F),tt=l(te*F);if($e)return{x:Jo,y:rn};if(tt!==rn)throw Error("invZ was invalid");return{x:Ee,y:Ae}}),S=Xu((z)=>{let{a:F,d:Y}=t;if(z.is0())throw Error("bad point: ZERO");let{ex:we,ey:te,ez:$e,et:Ee}=z,Ae=l(we*we),tt=l(te*te),yt=l($e*$e),ft=l(yt*yt),q=l(Ae*F),ne=l(yt*l(q+tt)),ce=l(ft+l(Y*l(Ae*tt)));if(ne!==ce)throw Error("bad point: equation left != right (1)");let he=l(we*te),Q=l($e*Ee);if(he!==Q)throw Error("bad point: equation left != right (2)");return!0});class v{constructor(z,F,Y,we){_("x",z),_("y",F),_("z",Y,!0),_("t",we),this.ex=z,this.ey=F,this.ez=Y,this.et=we,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(z){if(z instanceof v)throw Error("extended point not allowed");let{x:F,y:Y}=z||{};return _("x",F),_("y",Y),new v(F,Y,rn,l(F*Y))}static normalizeZ(z){let F=ed(r,z.map((Y)=>Y.ez));return z.map((Y,we)=>Y.toAffine(F[we])).map(v.fromAffine)}static msm(z,F){return $0(v,p,z,F)}_setWindowSize(z){O.setWindowSize(this,z)}assertValidity(){S(this)}equals(z){w(z);let{ex:F,ey:Y,ez:we}=this,{ex:te,ey:$e,ez:Ee}=z,Ae=l(F*Ee),tt=l(te*we),yt=l(Y*Ee),ft=l($e*we);return Ae===tt&&yt===ft}is0(){return this.equals(v.ZERO)}negate(){return new v(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:z}=t,{ex:F,ey:Y,ez:we}=this,te=l(F*F),$e=l(Y*Y),Ee=l(z8*l(we*we)),Ae=l(z*te),tt=F+Y,yt=l(l(tt*tt)-te-$e),ft=Ae+$e,q=ft-Ee,ne=Ae-$e,ce=l(yt*q),he=l(ft*ne),Q=l(yt*ne),Be=l(q*ft);return new v(ce,he,Be,Q)}add(z){w(z);let{a:F,d:Y}=t,{ex:we,ey:te,ez:$e,et:Ee}=this,{ex:Ae,ey:tt,ez:yt,et:ft}=z,q=l(we*Ae),ne=l(te*tt),ce=l(Ee*Y*ft),he=l($e*yt),Q=l((we+te)*(Ae+tt)-q-ne),Be=he-ce,bt=he+ce,xt=l(ne-F*q),Qe=l(Q*Be),vt=l(bt*xt),wt=l(Q*xt),Hr=l(Be*bt);return new v(Qe,vt,Hr,wt)}subtract(z){return this.add(z.negate())}wNAF(z){return O.wNAFCached(this,z,v.normalizeZ)}multiply(z){let F=z;Rn("scalar",F,rn,n);let{p:Y,f:we}=this.wNAF(F);return v.normalizeZ([Y,we])[0]}multiplyUnsafe(z,F=v.ZERO){let Y=z;if(Rn("scalar",Y,Jo,n),Y===Jo)return k;if(this.is0()||Y===rn)return this;return O.wNAFCachedUnsafe(this,Y,v.normalizeZ,F)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(z){return A(this,z)}clearCofactor(){let{h:z}=t;if(z===rn)return this;return this.multiplyUnsafe(z)}static fromHex(z,F=!1){let{d:Y,a:we}=t,te=r.BYTES;z=Gt("pointHex",z,te),Yo("zip215",F);let $e=z.slice(),Ee=z[te-1];$e[te-1]=Ee&-129;let Ae=bc($e),tt=F?d:r.ORDER;Rn("pointHex.y",Ae,Jo,tt);let yt=l(Ae*Ae),ft=l(yt-rn),q=l(Y*yt-we),{isValid:ne,value:ce}=h(ft,q);if(!ne)throw Error("Point.fromHex: invalid y coordinate");let he=(ce&rn)===rn,Q=(Ee&128)!==0;if(!F&&ce===Jo&&Q)throw Error("Point.fromHex: x=0 and x_0=1");if(Q!==he)ce=l(-ce);return v.fromAffine({x:ce,y:Ae})}static fromPrivateKey(z){let{scalar:F}=R(z);return P.multiply(F)}toRawBytes(){let{x:z,y:F}=this.toAffine(),Y=Qu(F,r.BYTES);return Y[Y.length-1]|=z&rn?128:0,Y}toHex(){return ra(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,rn,l(t.Gx*t.Gy)),v.ZERO=new v(Jo,rn,rn,Jo);let{BASE:P,ZERO:k}=v,O=M0(v,a*8);function N(z){return Et(z,n)}function j(z){return N(bc(z))}function R(z){let F=r.BYTES;z=Gt("private key",z,F);let Y=Gt("hashed private key",i(z),2*F),we=y(Y.slice(0,F)),te=Y.slice(F,2*F),$e=j(we);return{head:we,prefix:te,scalar:$e}}function K(z){let{head:F,prefix:Y,scalar:we}=R(z),te=P.multiply(we),$e=te.toRawBytes();return{head:F,prefix:Y,scalar:we,point:te,pointBytes:$e}}function Z(z){return K(z).pointBytes}function re(z=Uint8Array.of(),...F){let Y=na(...F);return j(i(x(Y,Gt("context",z),!!o)))}function pe(z,F,Y={}){if(z=Gt("message",z),o)z=o(z);let{prefix:we,scalar:te,pointBytes:$e}=K(F),Ee=re(Y.context,we,z),Ae=P.multiply(Ee).toRawBytes(),tt=re(Y.context,Ae,$e,z),yt=N(Ee+tt*te);Rn("signature.s",yt,Jo,n);let ft=na(Ae,Qu(yt,r.BYTES));return Gt("result",ft,r.BYTES*2)}let U=qie;function ee(z,F,Y,we=U){let{context:te,zip215:$e}=we,Ee=r.BYTES;if(z=Gt("signature",z,2*Ee),F=Gt("message",F),Y=Gt("publicKey",Y,Ee),$e!==void 0)Yo("zip215",$e);if(o)F=o(F);let Ae=bc(z.slice(Ee,2*Ee)),tt,yt,ft;try{tt=v.fromHex(Y,$e),yt=v.fromHex(z.slice(0,Ee),$e),ft=P.multiplyUnsafe(Ae)}catch(ce){return!1}if(!$e&&tt.isSmallOrder())return!1;let q=re(te,yt.toRawBytes(),tt.toRawBytes(),F);return yt.add(tt.multiplyUnsafe(q)).subtract(ft).clearCofactor().equals(v.ZERO)}return P._setWindowSize(8),{CURVE:t,getPublicKey:Z,sign:pe,verify:ee,ExtendedPoint:v,utils:{getExtendedPublicKey:K,randomPrivateKey:()=>s(r.BYTES),precompute(z=8,F=v.BASE){return F._setWindowSize(z),F.multiply(BigInt(3)),F}}}}td();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Qv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),L8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),twe=BigInt(0),Gie=BigInt(1),D8=BigInt(2),rwe=BigInt(3),Vie=BigInt(5),Zie=BigInt(8);function Wie(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=Qv,a=e*e%i*e%i,c=Vt(a,D8,i)*a%i,d=Vt(c,Gie,i)*e%i,l=Vt(d,Vie,i)*d%i,p=Vt(l,t,i)*l%i,m=Vt(p,r,i)*p%i,h=Vt(m,n,i)*m%i,y=Vt(h,o,i)*h%i,x=Vt(y,o,i)*h%i,_=Vt(x,t,i)*l%i;return{pow_p_5_8:Vt(_,D8,i)*e%i,b2:a}}function Kie(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Yie(e,t){let r=Qv,n=Et(t*t*t,r),o=Et(n*n*t,r),i=Wie(e*o).pow_p_5_8,s=Et(e*n*i,r),a=Et(t*s*s,r),c=s,d=Et(s*L8,r),l=a===e,p=a===Et(-e,r),m=a===Et(-e*L8,r);if(l)s=c;if(p||m)s=d;if(k8(s,r))s=Et(-s,r);return{isValid:l||p,value:s}}var U8=(()=>Gi(Qv,void 0,!0))(),Jie=(()=>({a:U8.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:U8,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Zie,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:y8,randomBytes:I0,adjustScalarBytes:Kie,uvRatio:Yie}))(),rd=(()=>B8(Jie))();var Qie=(e)=>e/4294967296|0,Xie=(e)=>e>>>0;function F8(e,t,r,n){let o=Qie(r),i=Xie(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}function j8(e,t,r){return e&t^~e&r}function q8(e,t,r){return e&t^e&r^t&r}class Xv{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=E0(this.buffer)}update(e){Cv(this),v0(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=E0(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){Cv(this),Z4(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);F8(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:E0(e),a=this.outputLen,c=a/4,d=this.get();if(a%4||c>d.length)throw Error("invalid outputLen");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],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 H8=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ese=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]),oa=new Uint32Array(64);class G8 extends Xv{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 l=0;l<16;l++,t+=4)oa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=oa[l-15],m=oa[l-2],h=xo(p,7)^xo(p,18)^p>>>3,y=xo(m,17)^xo(m,19)^m>>>10;oa[l]=y+oa[l-7]+h+oa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=xo(s,6)^xo(s,11)^xo(s,25),m=d+p+j8(s,a,c)+ese[l]+oa[l]|0,y=(xo(r,2)^xo(r,13)^xo(r,22))+q8(r,n,o)|0;d=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,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){T0(oa)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),T0(this.buffer)}}class V8 extends G8{constructor(){super(32,H8)}}var N0=K4(()=>new V8,Y4(1));function z0(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=rd.utils.randomPrivateKey();return{publicKey:rd.getPublicKey(e),privateKey:e}}function B0(e){return Li(e.publicKey)}function L0(e){return Li(e.privateKey)}function Z8(e,t){return{publicKey:_f(e),privateKey:_f(t)}}function W8(e){return Li(N0(e))}function K8(e,t,r,n){return`${e.toUpperCase()}
|
|
137
137
|
${t}
|
|
138
138
|
${r}
|
|
139
139
|
${n}`}function Y8(e,t){return`WS-AUTH
|
|
140
140
|
${e}
|
|
141
|
-
${t}`}function D0(e,t){return Li(rd.sign(pc(t),e))}var kf=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var tse=1e4,rse=15000,nse=30000,ose=1000;function or(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function le(e,t){let r=e[t];if(typeof r!=="string"||r.length===0)throw Error(`Invalid WebSocket event: ${t} must be a non-empty string`);return r}function Oe(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function So(e,t){if(!Object.hasOwn(e,t))throw Error(`Invalid WebSocket event: ${t} is missing`);let r=e[t];if(r===null||r===void 0)return null;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function eT(e,t){let r=e[t];if(typeof r!=="boolean")throw Error(`Invalid WebSocket event: ${t} must be a boolean`);return r}function X8(e,t){let r=e[t];if(typeof r!=="number"||!Number.isSafeInteger(r)||r<0)throw Error(`Invalid WebSocket event: ${t} must be a non-negative safe integer`);return r}function Rf(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="number"||!Number.isFinite(r))throw Error(`Invalid WebSocket event: ${t} must be a finite number`);return r}function ez(e,t){let r=e[t];if(r===void 0||r===null)return;return X8(e,t)}function ise(e,t){let r=e[t];if(!Array.isArray(r)||r.some((n)=>typeof n!=="string"))throw Error(`Invalid WebSocket event: ${t} must be an array of strings`);return r}function U0(e,t,r){let n=le(e,t);if(!r.includes(n))throw Error(`Invalid WebSocket event: ${t} must be one of ${r.join(", ")}`);return n}function J8(e,t){let r=Oe(e,t);return r===void 0||r.length===0?void 0:r}function tz(e){if(!or(e))throw Error("Invalid conditional order event: data must be an object");let t=en(e);return{conditionalOrderId:le(t,"conditionalOrderId"),tradingPairId:le(t,"tradingPairId"),marginAccountId:le(t,"marginAccountId"),positionId:Oe(t,"positionId"),parentOrderId:Oe(t,"parentOrderId"),associationType:J8(t,"associationType"),linkedGroupId:Oe(t,"linkedGroupId"),conditionType:le(t,"conditionType"),triggerSource:le(t,"triggerSource"),triggerPrice:le(t,"triggerPrice"),side:le(t,"side"),positionSide:le(t,"positionSide"),orderType:le(t,"orderType"),limitPrice:Oe(t,"limitPrice"),quantity:Oe(t,"quantity"),slippageToleranceBps:Rf(t,"slippageToleranceBps"),reduceOnly:eT(t,"reduceOnly"),timeInForce:J8(t,"timeInForce"),state:le(t,"state"),triggeredOrderId:Oe(t,"triggeredOrderId"),triggeredAt:Oe(t,"triggeredAt"),activatedAt:Oe(t,"activatedAt"),cancelledAt:Oe(t,"cancelledAt"),expiresAt:Oe(t,"expiresAt"),failureReason:Oe(t,"failureReason"),reason:le(t,"reason"),updatedAt:le(t,"updatedAt"),version:Rf(t,"version")}}function sse(e){if(!or(e))throw Error("Invalid conditional order event: payload must be an object");return{eventType:U0(e,"event_type",["conditional_order_update"]),userId:le(e,"user_id"),data:tz(e.data)}}function rz(e){if(!or(e))throw Error("Invalid position event: data must be an object");let t=en(e);return{positionId:le(t,"positionId"),marginAccountId:le(t,"marginAccountId"),tradingPairId:le(t,"tradingPairId"),side:le(t,"side"),status:le(t,"status"),size:le(t,"size"),entryPrice:le(t,"entryPrice"),markPrice:Oe(t,"markPrice"),unrealizedPnl:Oe(t,"unrealizedPnl"),liquidationPrice:Oe(t,"liquidationPrice"),isolatedMargin:le(t,"isolatedMargin"),leverage:le(t,"leverage"),tradeId:Oe(t,"tradeId"),orderId:Oe(t,"orderId"),reason:le(t,"reason"),updatedAt:le(t,"updatedAt"),version:ez(t,"version")}}function ase(e){if(!or(e))throw Error("Invalid position event: payload must be an object");return{eventType:U0(e,"event_type",["position_update"]),userId:le(e,"user_id"),data:rz(e.data)}}function nz(e){if(!or(e))throw Error("Invalid liquidation event: data must be an object");let t=en(e);return{liquidationId:le(t,"liquidationId"),marginAccountId:le(t,"marginAccountId"),positionId:Oe(t,"positionId"),tradingPairId:Oe(t,"tradingPairId"),status:le(t,"status"),accountState:le(t,"accountState"),liquidationPrice:Oe(t,"liquidationPrice"),markPrice:Oe(t,"markPrice"),estimatedShortfall:le(t,"estimatedShortfall"),message:le(t,"message"),triggeredAt:le(t,"triggeredAt")}}function cse(e){if(!or(e))throw Error("Invalid liquidation event: payload must be an object");return{eventType:U0(e,"event_type",["liquidation_alert"]),userId:le(e,"user_id"),data:nz(e.data)}}function oz(e){if(!or(e))throw Error("Invalid account event: data must be an object");let t=en(e);return{marginAccountId:le(t,"marginAccountId"),sequence:X8(t,"sequence"),equity:le(t,"equity"),collateral:le(t,"collateral"),freeCollateral:le(t,"freeCollateral"),marginRatio:le(t,"marginRatio"),maintenanceRequirement:le(t,"maintenanceRequirement"),updatedAt:le(t,"updatedAt")}}function use(e){if(!or(e))throw Error("Invalid account event: payload must be an object");return{eventType:U0(e,"event_type",["account_update"]),userId:le(e,"user_id"),data:oz(e.data)}}function iz(e){if(!or(e))throw Error("Invalid market stats event: data must be an object");let t=en(e);return{symbol:le(t,"symbol"),tradingPairId:le(t,"tradingPairId"),indexPrice:Oe(t,"indexPrice"),markPrice:Oe(t,"markPrice"),midPrice:Oe(t,"midPrice"),bestBidPrice:Oe(t,"bestBidPrice"),bestAskPrice:Oe(t,"bestAskPrice"),openInterest:Oe(t,"openInterest"),openInterestLimit:Oe(t,"openInterestLimit"),lastTradePrice:Oe(t,"lastTradePrice"),dailyBaseTokenVolume:Oe(t,"dailyBaseTokenVolume"),dailyQuoteTokenVolume:Oe(t,"dailyQuoteTokenVolume"),dailyPriceLow:Oe(t,"dailyPriceLow"),dailyPriceHigh:Oe(t,"dailyPriceHigh"),dailyPriceChange:Oe(t,"dailyPriceChange"),dailyPriceChangePercent:Oe(t,"dailyPriceChangePercent"),currentFundingRate:Oe(t,"currentFundingRate"),fundingRate:Oe(t,"fundingRate"),fundingTimestamp:Rf(t,"fundingTimestamp"),premium:Oe(t,"premium"),baseInterestRate:Oe(t,"baseInterestRate"),fundingClampSmall:Oe(t,"fundingClampSmall"),fundingClampBig:Oe(t,"fundingClampBig")}}function dse(e){if(!or(e))throw Error("Invalid market stats event: payload must be an object");return{tradingPairId:le(e,"trading_pair_id"),data:iz(e.data)}}function sz(e){if(!or(e))throw Error("Invalid market stats summary: entry must be an object");let t=en(e);return{tradingPairId:le(t,"tradingPairId"),symbol:le(t,"symbol"),lastTradePrice:Oe(t,"lastTradePrice"),markPrice:Oe(t,"markPrice"),dailyPriceChange:Oe(t,"dailyPriceChange"),dailyPriceChangePercent:Oe(t,"dailyPriceChangePercent"),dailyBaseTokenVolume:Oe(t,"dailyBaseTokenVolume"),dailyQuoteTokenVolume:Oe(t,"dailyQuoteTokenVolume"),dailyPriceHigh:Oe(t,"dailyPriceHigh"),dailyPriceLow:Oe(t,"dailyPriceLow"),openInterest:Oe(t,"openInterest"),currentFundingRate:Oe(t,"currentFundingRate"),fundingTimestamp:Rf(t,"fundingTimestamp"),marketStatus:le(t,"marketStatus")}}function lse(e){if(!or(e)||!Array.isArray(e.markets))throw Error("Invalid market stats all event: markets must be an array");return{markets:e.markets.map(sz)}}function az(e){if(!or(e))throw Error("Invalid instrument event: data must be an object");let t=en(e);return{change:le(t,"change"),tradingPairId:le(t,"tradingPairId"),symbol:le(t,"symbol"),isActive:eT(t,"isActive"),tickSize:le(t,"tickSize"),quantityStepSize:le(t,"quantityStepSize"),minOrderSize:le(t,"minOrderSize"),maxOrderSize:le(t,"maxOrderSize"),marketType:le(t,"marketType"),category:le(t,"category"),maxLeverage:Oe(t,"maxLeverage"),initialMarginRate:Oe(t,"initialMarginRate"),maintenanceMarginRate:Oe(t,"maintenanceMarginRate"),changedFields:ise(t,"changedFields"),updatedAt:le(t,"updatedAt")}}function pse(e){if(!or(e))throw Error("Invalid instrument event: payload must be an object");return{tradingPairId:le(e,"trading_pair_id"),data:az(e.data)}}function fse(e){if(!or(e))throw Error("Invalid TWAP order event: payload must be an object");if(!or(e.data))throw Error("Invalid TWAP order event: data must be an object");if(e.event_type!=="twap_order_update")throw Error("Invalid TWAP order event: event_type must be twap_order_update");let r=e.user_id;if(typeof r!=="string"||r.length===0)throw Error("Invalid TWAP order event: user_id must be a non-empty string");return{eventType:"twap_order_update",userId:r,data:cz(e.data)}}function cz(e){if(!or(e))throw Error("Invalid TWAP order event: data must be an object");let t=en(e);for(let o of Object.keys(t))if(t[o]===null)delete t[o];let r=t.twapOrderId;if(typeof r!=="string"||r.length===0)throw Error("Invalid TWAP order event: twapOrderId must be a non-empty string");let n=t.state;if(typeof n!=="string"||n.length===0)throw Error("Invalid TWAP order event: state must be a non-empty string");return t}function uz(e){if(!or(e))throw Error("Invalid balance event: data must be an object");let t=en(e);return{tokenAddress:le(t,"tokenAddress"),tokenSymbol:So(t,"tokenSymbol"),available:le(t,"available"),availableRaw:le(t,"availableRaw"),locked:le(t,"locked"),lockedRaw:le(t,"lockedRaw"),total:le(t,"total"),totalRaw:le(t,"totalRaw"),version:ez(t,"version"),reason:le(t,"reason"),referenceId:So(t,"referenceId"),updatedAt:le(t,"updatedAt")}}function mse(e){return uz(e)}function Q8(e){if(!or(e))throw Error("Invalid order snapshot: item must be an object");let t=en(e),r=Oe(t,"clientOrderId"),n=Oe(t,"selfTradePreventionMode"),o=Rf(t,"version");return{orderId:le(t,"orderId"),userId:le(t,"userId"),applicationId:le(t,"applicationId"),tradingPairId:le(t,"tradingPairId"),tradingPair:le(t,"tradingPair"),tradingMode:le(t,"tradingMode"),side:le(t,"side"),orderType:le(t,"orderType"),price:So(t,"price"),quantity:le(t,"quantity"),quantityRaw:le(t,"quantityRaw"),filledQuantity:le(t,"filledQuantity"),filledQuantityRaw:le(t,"filledQuantityRaw"),remainingQuantity:So(t,"remainingQuantity"),remainingQuantityRaw:So(t,"remainingQuantityRaw"),status:le(t,"status"),timeInForce:So(t,"timeInForce"),averageFillPrice:So(t,"averageFillPrice"),createdAt:le(t,"createdAt"),updatedAt:So(t,"updatedAt"),marginAccountId:So(t,"marginAccountId"),positionId:So(t,"positionId"),leverage:So(t,"leverage"),reduceOnly:eT(t,"reduceOnly"),...r===void 0?{}:{clientOrderId:r},...n===void 0?{}:{selfTradePreventionMode:n},...o===void 0?{}:{version:o}}}function wo(e,t,r){return(n)=>{try{if(!Array.isArray(n))throw Error(`Invalid ${e} snapshot: data must be an array`);let o=n.map(t);r(o)}catch(o){console.error(`WebSocket: Error processing ${e} snapshot`,o)}}}function tT(e,t={}){let r=null,n=t.session,o=0,i=null,s=null,a=t.autoReconnect??!0,c=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=Number.isFinite(t.reconnectBaseDelayMs)&&t.reconnectBaseDelayMs>0?t.reconnectBaseDelayMs:ose,l=Number.isFinite(t.connectionTimeoutMs)&&t.connectionTimeoutMs>0?t.connectionTimeoutMs:tse,p=null,m=new Map,h=new Map,y=new Map,x=()=>{if(!r)return i?"reconnecting":"disconnected";switch(r.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return i?"reconnecting":"disconnected"}},_=()=>e,w=()=>{if(!n||r?.readyState!==WebSocket.OPEN)return;let q=Date.now(),ne=D0(_f(n.privateKey),Y8(n.publicKey,q));r.send(JSON.stringify({type:"Authenticate",public_key:n.publicKey,timestamp:q,signature:ne}))},A=()=>{if(s)clearInterval(s),s=null},S=()=>{A(),s=setInterval(()=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify({type:"Ping"}))},rse)},v=()=>{if(i)clearTimeout(i),i=null},P=()=>{if(i)return;if(!a||o>=c){console.error("WebSocket: Max reconnect attempts reached");return}let q=Math.min(d*2**o,nse);o++;let ne=Math.random()*q;i=setTimeout(()=>{if(i=null,!a)return;K().catch((ce)=>{console.warn("WebSocket: Failed to reconnect:",ce),P()})},ne),t.onStatusChange?.("reconnecting")},k=(q)=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify(q))},O=()=>{y.clear();let q=Array.from(m.keys());if(q.length>0)k({type:"Subscribe",channels:q})},N=(q)=>q.startsWith("ohlcv:")&&q.split(":").length===4,j=(q,ne)=>{if(q.endsWith(":*"))return ne.startsWith(q.slice(0,-1));if(N(q))return ne===q||ne===`${q}:trade`;return ne===q||ne.startsWith(`${q}:`)},R=(q)=>{if(q.type==="Error"){if(typeof q.code==="string"&&typeof q.message==="string")t.onError?.({code:q.code,message:q.message});return}if(!q.channel)return;if(q.type==="Snapshot"){for(let ne of h.get(q.channel)??[])ne(q.data);return}if(q.type!=="Event")return;for(let[ne,ce]of m)if(j(ne,q.channel))for(let he of ce)he(q.data)},K=()=>new Promise((q,ne)=>{if(r?.readyState===WebSocket.CONNECTING||r?.readyState===WebSocket.OPEN){q();return}try{let ce=new WebSocket(_());r=ce;let he=setTimeout(()=>{if(r!==ce){q();return}if(ce.readyState===WebSocket.CONNECTING)ce.close(1000,"Connection timeout"),ne(Error("WebSocket connection timeout"))},l);ce.onopen=()=>{if(clearTimeout(he),r!==ce){q();return}if(o=0,v(),S(),w(),O(),t.onStatusChange?.("connected"),p!==null){let Q=p;p=null,t.onResync?.({code:Q,slowClient:Q===1013})}q()},ce.onmessage=(Q)=>{if(r!==ce)return;try{let Be=JSON.parse(Q.data);if(Be.type==="Pong")return;if(Be.type==="Ping"){k({type:"Pong"});return}R(Be)}catch(Be){console.warn("WebSocket: Failed to parse message",Be)}},ce.onclose=(Q)=>{if(clearTimeout(he),r!==ce){q();return}if(r=null,A(),a&&Q.code!==1000){if(p===null||Q.code===1013)p=Q.code;P()}if(!i)t.onStatusChange?.("disconnected")},ce.onerror=()=>clearTimeout(he)}catch(ce){t.onStatusChange?.("disconnected"),ne(ce)}}),Z=()=>{a=!1,v(),A(),p=null,m.clear(),h.clear(),y.clear(),r?.close(1000,"Client disconnect"),r=null,t.onStatusChange?.("disconnected")},re=(q,ne,ce)=>{let he=!m.has(q);if(!m.has(q))m.set(q,new Set);if(m.get(q)?.add(ne),ce){if(!h.has(q))h.set(q,new Set);h.get(q)?.add(ce)}if(he&&r?.readyState===WebSocket.OPEN)k({type:"Subscribe",channels:[q]});return()=>{if(ce){let Be=h.get(q);if(Be?.delete(ce),Be?.size===0)h.delete(q)}let Q=m.get(q);if(Q){if(Q.delete(ne),Q.size===0){if(m.delete(q),r?.readyState===WebSocket.OPEN)k({type:"Unsubscribe",channels:[q]})}}}};return{connect:K,disconnect:Z,isConnected:()=>r?.readyState===WebSocket.OPEN,getStatus:x,setSessionKeypair:(q)=>{if(n=q??void 0,n&&r?.readyState===WebSocket.OPEN)w();else if(n&&(!r||r.readyState===WebSocket.CLOSED))K().catch((ne)=>{console.warn("WebSocket: Failed to connect after session update:",ne)})},orders:(q,ne,ce,he)=>{let Q=`orders:${q}:${ne}`;return re(Q,(Be)=>{try{let bt=Be,xt={orderId:bt.order_id,eventType:bt.event_type,timestamp:bt.timestamp,data:en(bt.data)};ce(xt)}catch(bt){console.error("WebSocket: Error processing order event",bt)}},he&&wo("orders",Q8,he))},orderbook:(q,ne,ce,he,Q)=>{if(!q||!ne||ce===void 0||!he)throw Error(`orderbook subscription requires all params: tradingPairId="${q}", tradingMode="${ne}", magnitude=${ce} (valid: ${kf.join(", ")}), quotationMode="${he}" (valid: "BASE", "QUOTE")`);if(!kf.includes(ce))throw Error(`Invalid magnitude: ${ce}. Must be one of: ${kf.join(", ")}`);let Be=`orderbook:${q}:${ne}:${ce}:${he.toLowerCase()}`;return re(Be,(bt)=>{try{let xt=bt,Qe=xt.data,vt={tradingPairId:xt.trading_pair_id,tradingMode:xt.trading_mode,bids:(Qe?.bids||[]).map((wt)=>({price:wt.price,quantity:wt.quantity,orderCount:wt.order_count||0})),asks:(Qe?.asks||[]).map((wt)=>({price:wt.price,quantity:wt.quantity,orderCount:wt.order_count||0})),bestBid:Qe?.best_bid??void 0,bestAsk:Qe?.best_ask??void 0,bidVolume:Qe?.bid_volume||void 0,askVolume:Qe?.ask_volume||void 0,priceChange:Qe?.price_change?{side:Qe.price_change.side,oldPrice:Qe.price_change.old_price??void 0,newPrice:Qe.price_change.new_price??void 0,levelRemoved:Qe.price_change.level_removed||!1,levelAdded:Qe.price_change.level_added||!1}:void 0,baseDecimals:xt.base_decimals||0,quoteDecimals:xt.quote_decimals||0,timestamp:xt.timestamp||new Date().toISOString(),sequence:xt.sequence_number||0};Q(vt)}catch(xt){console.error("WebSocket: Error processing orderbook event",xt)}})},ohlcv:(q,ne,ce,he,Q)=>{let Be=Q===void 0?`ohlcv:${q}:${ne}:${ce}`:`ohlcv:${q}:${ne}:${ce}:${Q}`;return re(Be,(bt)=>{try{let xt=bt,{data:Qe,price_type:vt}=xt,wt=typeof vt==="string"&&vt!==""?vt:void 0,Hr={tradingPairId:xt.trading_pair_id,tradingMode:xt.trading_mode,interval:xt.interval,priceType:wt,candlestick:{T:Qe.period_start||0,t:Qe.period_end||0,o:Qe.open||"0",h:Qe.high||"0",l:Qe.low||"0",c:Qe.close||"0",v:Qe.volume||"0",s:xt.symbol,i:xt.interval,n:Qe.trades_count||0}};he(Hr)}catch(xt){console.error("WebSocket: Error processing OHLCV event",xt)}})},trades:(q,ne)=>{let ce=`trades:${q}`;return re(ce,(he)=>{try{let Q=he,Be=Q.data,bt={eventType:"trade",tradingPairId:Q.trading_pair_id,tradingMode:Q.trading_mode.toUpperCase(),data:{tradeId:Be.trade_id,price:Be.price,quantity:Be.quantity,makerSide:Be.maker_side.toUpperCase(),executedAt:Be.executed_at}};ne(bt)}catch(Q){console.error("WebSocket: Error processing trade event",Q)}})},movements:(q)=>re("movements",(ce)=>{try{let he=ce,Q=he.data,Be={eventType:"movement",userId:he.user_id,data:{id:Q.id,entryType:Q.entry_type,transactionType:Q.transaction_type,status:Q.status,token:Q.token??Q.token_address,tokenAddress:Q.token??Q.token_address,assetId:Q.asset_id,symbol:Q.symbol,amount:String(Q.amount),amountRaw:Q.amount_raw,balanceBefore:Q.balance_before!=null?String(Q.balance_before):void 0,balanceBeforeRaw:Q.balance_before_raw,balanceAfter:Q.balance_after!=null?String(Q.balance_after):void 0,balanceAfterRaw:Q.balance_after_raw,lockedBefore:Q.locked_before!=null?String(Q.locked_before):void 0,lockedBeforeRaw:Q.locked_before_raw,lockedAfter:Q.locked_after!=null?String(Q.locked_after):void 0,lockedAfterRaw:Q.locked_after_raw,referenceId:Q.reference_id,referenceType:Q.reference_type,description:Q.description,txHash:Q.tx_hash,blockNumber:Q.block_number,createdAt:Q.created_at,decimals:Q.decimals}};q(Be)}catch(he){console.error("WebSocket: Error processing movement event",he)}}),userOrders:(q,ne)=>re("orders",(he)=>{try{let Q=he,Be={orderId:Q.order_id,eventType:Q.event_type,timestamp:Q.timestamp,data:en(Q.data)};q(Be)}catch(Q){console.error("WebSocket: Error processing user order event",Q)}},ne&&wo("orders",Q8,ne)),balances:(q,ne)=>re("balances",(he)=>{try{if(!or(he))throw Error("Invalid balance event: payload must be an object");let Q={eventType:"balance_update",userId:le(he,"user_id"),data:uz(he.data)};q(Q)}catch(Q){console.error("WebSocket: Error processing balance event",Q)}},ne&&wo("balances",mse,ne)),conditionalOrders:(q,ne,ce)=>{if(!q)throw Error("conditionalOrders subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let he=ne?`conditional_orders:${ne}`:"conditional_orders";return re(he,(Q)=>{try{q(sse(Q))}catch(Be){console.error("WebSocket: Error processing conditional order event",Be)}},ce&&wo("conditional orders",tz,ce))},twapOrders:(q,ne,ce)=>{if(!q)throw Error("twapOrders subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("twapOrders tradingPairId cannot be empty");let he=ne?`twap_orders:${ne}`:"twap_orders";return re(he,(Q)=>{try{q(fse(Q))}catch(Be){console.error("WebSocket: Error processing TWAP order event",Be)}},ce&&wo("TWAP orders",cz,ce))},positions:(q,ne,ce)=>{if(!q)throw Error("positions subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("positions tradingPairId cannot be empty");let he=ne?`positions:${ne}`:"positions";return re(he,(Q)=>{try{q(ase(Q))}catch(Be){console.error("WebSocket: Error processing position event",Be)}},ce&&wo("positions",rz,ce))},liquidations:(q,ne,ce)=>{if(!q)throw Error("liquidations subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("liquidations tradingPairId cannot be empty");let he=ne?`liquidations:${ne}`:"liquidations";return re(he,(Q)=>{try{q(cse(Q))}catch(Be){console.error("WebSocket: Error processing liquidation event",Be)}},ce&&wo("liquidations",nz,ce))},account:(q,ne)=>{if(!q)throw Error("account subscription requires a handler");return re("account",(ce)=>{try{q(use(ce))}catch(he){console.error("WebSocket: Error processing account event",he)}},ne&&wo("account",oz,ne))},instruments:(q,ne,ce)=>{if(!q)throw Error("instruments subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("instruments tradingPairId cannot be empty");let he=ne?`instrument:${ne}`:"instrument",Q=(Qe)=>{let vt=y.get(he);if(!vt)vt=new Map,y.set(he,vt);vt.set(Qe.tradingPairId,Qe)},Be=m.has(he),bt=!1,xt=re(he,(Qe)=>{try{let vt=pse(Qe);Q(vt),q(vt)}catch(vt){console.error("WebSocket: Error processing instrument event",vt)}},wo("instrument",az,(Qe)=>{let vt=Qe.map((wt)=>({tradingPairId:wt.tradingPairId,data:wt}));if(y.set(he,new Map(vt.map((wt)=>[wt.tradingPairId,wt]))),ce){ce(Qe);return}for(let wt of vt)q(wt)}));if(Be&&r?.readyState===WebSocket.OPEN){if(y.has(he))queueMicrotask(()=>{if(bt)return;let Qe=y.get(he);if(!Qe||r?.readyState!==WebSocket.OPEN)return;let vt=[...Qe.values()];if(ce){try{ce(vt.filter((wt)=>wt.data.isActive).map((wt)=>wt.data))}catch(wt){console.error("WebSocket: Error processing instrument baseline replay",wt)}return}for(let wt of vt)try{q(wt)}catch(Hr){console.error("WebSocket: Error processing instrument baseline replay",Hr)}})}return()=>{if(bt=!0,xt(),!m.has(he))y.delete(he)}},marketStats:(q,ne,ce)=>{if(!q)throw Error("marketStats subscription requires a tradingPairId");if(!ne)throw Error("marketStats subscription requires a handler");return re(`market_stats:${q}`,(he)=>{try{ne(dse(he))}catch(Q){console.error("WebSocket: Error processing market stats event",Q)}},ce&&wo("market stats",iz,ce))},marketStatsAll:(q,ne)=>{if(!q)throw Error("marketStatsAll subscription requires a handler");return re("market_stats",(ce)=>{if(!or(ce)||!Array.isArray(ce.markets))return;try{q(lse(ce))}catch(he){console.error("WebSocket: Error processing market stats all event",he)}},ne&&wo("all-markets stats",sz,ne))}}}var ia=Vr(j0(),1),wB=["token","accessToken","access_token","refreshToken","refresh_token","authToken","auth_token","bearerToken","bearer_token","jwtToken","jwt_token","apiKey","api_key","apikey","clientSecret","client_secret","clientId","client_id","secret","password","authorization","bearer","auth","credentials","credential","email","phone","phoneNumber","phone_number","ssn","socialSecurity","social_security","address","passport","passportNumber","passport_number","driversLicense","drivers_license","cardNumber","card_number","creditCard","credit_card","cvv","pin","signature","privateKey","private_key","publicKey","public_key","mnemonic","seed","salt","hash","certificate","cert","fingerprint","cookie","session","sessionId","session_id","sessionToken","session_token","ipAddress","ip_address","deviceId","device_id","userId","user_id","accountId","account_id"];function nd(e,t=5,r=0){if(r>=t)return"[Max depth reached]";if(e===null||e===void 0)return e;if(Array.isArray(e)){let o=e.slice(0,10).map((i)=>nd(i,t,r+1));if(e.length>10)o.push(`[... ${e.length-10} more items]`);return o}if(typeof e==="object"){let n={};for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(wB.some((c)=>s.includes(c.toLowerCase())))n[o]="[REDACTED]";else if(typeof i==="string"&&i.length>500)n[o]=`${i.substring(0,500)}... [truncated]`;else n[o]=nd(i,t,r+1)}return n}if(typeof e==="string"){if(e.length>1000)return`${e.substring(0,1000)}... [truncated]`;return e}return e}class od extends Error{cause;suggestion;retryable=!1;timestamp;constructor(e,t){super(e);if(this.name=this.constructor.name,this.timestamp=Date.now(),t?.cause)this.cause=t.cause;if(t?.suggestion)this.suggestion=t.suggestion;if(t?.retryable!==void 0)this.retryable=t.retryable}toJSON(){return{name:this.name,code:this.code,message:this.message,suggestion:this.suggestion,retryable:this.retryable,timestamp:this.timestamp,cause:this.cause instanceof Error?this.cause.message:this.cause}}}class Pt extends od{code="INVALID_CONFIG";field;value;constructor(e,t,r,n){let o=t?`Check the '${t}' configuration parameter. ${kse(t)}`:"Review your SDK configuration and ensure all required fields are provided correctly.";super(e,{cause:n,suggestion:o,retryable:!1});this.field=t,this.value=r}toJSON(){let e;if(this.field){let t=this.field.toLowerCase();if(wB.some((n)=>t.includes(n.toLowerCase())))e="[REDACTED]";else e=nd(this.value)}else e=nd(this.value);return{...super.toJSON(),field:this.field,value:e}}}function kse(e){switch(e.toLowerCase()){case"walletclient":return"Ensure you're creating the wallet client with a valid account and chain configuration.";case"seirpcurl":return"Use 'https://evm-rpc-testnet.sei-apis.com' for testnet or 'https://evm-rpc.sei-apis.com' for mainnet.";case"wsurl":return"Use 'wss://ws-develop.apimonaco.xyz/ws' for testnet or 'wss://ws.apimonaco.xyz/ws' for mainnet.";case"network":return"Valid networks are: 'mainnet', 'development', 'staging', 'local'.";default:return"Refer to the SDK documentation for correct configuration format."}}class Of extends od{code="INVALID_STATE";currentState;expectedState;constructor(e,t,r,n){let o=r?`${t?`Current state is '${t}', `:""}Expected state is '${r}'. Ensure operations are performed in the correct order.`:"Check that prerequisites are met before calling this method.";super(e,{cause:n,suggestion:o,retryable:!1});this.currentState=t,this.expectedState=r}toJSON(){return{...super.toJSON(),currentState:this.currentState,expectedState:this.expectedState}}}class Zt extends od{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor(e,t){let{suggestion:r,retryable:n}=Rse(t?.statusCode,e,t?.responseBody);super(e,{cause:t?.cause,suggestion:r,retryable:n});this.endpoint=t?.endpoint,this.statusCode=t?.statusCode,this.responseBody=t?.responseBody,this.requestBody=t?.requestBody,this.requestId=t?.requestId,this.retryAfter=t?.retryAfter}toJSON(){return{...super.toJSON(),endpoint:this.endpoint,statusCode:this.statusCode,responseBody:nd(this.responseBody),requestBody:nd(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function Rse(e,t,r){if(!e)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if(e===ia.StatusCodes.UNAUTHORIZED){if(t?.toLowerCase().includes("expired"))return{suggestion:"Access token has expired. Call sdk.refreshAuth() to get a new token, or call sdk.login() to re-authenticate.",retryable:!1};return{suggestion:"Authentication required. Call sdk.login(clientId) to authenticate before making this request.",retryable:!1}}if(e===ia.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if(e===ia.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if(e===ia.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if(e===ia.StatusCodes.BAD_REQUEST){if(t?.toLowerCase().includes("insufficient balance"))return{suggestion:"Insufficient balance. Deposit more funds using sdk.vault.deposit() or reduce the order size.",retryable:!1};if(t?.toLowerCase().includes("invalid"))return{suggestion:"Invalid request parameters. Check the API documentation for correct parameter format and values.",retryable:!1};return{suggestion:"Bad request. Verify that all required parameters are provided and correctly formatted.",retryable:!1}}if(e===ia.StatusCodes.TOO_MANY_REQUESTS){let n;if(typeof r==="object"&&r!==null&&"retry_after"in r&&r.retry_after){let o=r.retry_after;n=` Wait ${String(o)} seconds before retrying.`}else n=" Wait a moment before retrying.";return{suggestion:`Rate limit exceeded.${n} Consider implementing exponential backoff for retries.`,retryable:!0}}if(e>=ia.StatusCodes.INTERNAL_SERVER_ERROR&&e<600)return{suggestion:"Server error occurred. This is likely a temporary issue. Try again in a few moments.",retryable:!0};return{suggestion:void 0,retryable:!1}}class Vi extends od{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor(e,t){let r=Ose(t?.revertReason);super(e,{cause:t?.cause,suggestion:r,retryable:!1});this.revertReason=t?.revertReason,this.transactionHash=t?.transactionHash,this.contractAddress=t?.contractAddress}toJSON(){return{...super.toJSON(),revertReason:this.revertReason,transactionHash:this.transactionHash,contractAddress:this.contractAddress}}}function Ose(e){if(!e)return"Smart contract execution failed. Check transaction parameters and try again.";let t=e.toLowerCase();if(t.includes("insufficient allowance"))return"Token allowance is insufficient. Call sdk.vault.approve() to increase the token allowance for the vault contract.";if(t.includes("insufficient balance"))return"Wallet balance is insufficient for this transaction. Ensure you have enough tokens and native currency for gas fees.";if(t.includes("nonce"))return"Transaction nonce error. This may be due to a pending transaction. Wait for pending transactions to complete or reset your account nonce.";if(t.includes("gas"))return"Transaction ran out of gas. Try increasing the gas limit for this transaction.";return}var Cse={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},Mse={local:"ws://localhost:8085/ws",development:"wss://ws-develop.apimonaco.xyz/ws",staging:"wss://ws-staging.apimonaco.xyz/ws",mainnet:"wss://ws.apimonaco.xyz/ws"};function cT(e){return Cse[e]}function uT(e){return Mse[e]}var HA=Vr(j0(),1);var q0=256,H0;function G0(e=11){if(!H0||q0+e>512){H0="",q0=0;for(let t=0;t<256;t++)H0+=(256+Math.random()*256|0).toString(16).substring(1)}return H0.substring(q0,q0+++e)}function V0(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:i="base",name:s="Base Client",tokens:a,type:c="base"}=e,d=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),l=r?.blockTime??12000,p=Math.min(Math.max(Math.floor(l/2),500),4000),m=e.pollingInterval??p,h=e.cacheTime??m,y=e.account?ze(e.account):void 0,{config:x,request:_,value:w}=e.transport({account:y,chain:r,pollingInterval:m}),A={...x,...w},S={account:y,batch:t,cacheTime:h,ccipRead:n,chain:r,dataSuffix:o,key:i,name:s,pollingInterval:m,request:_,tokens:a,transport:A,type:c,uid:G0(),...d?{experimental_blockTag:d}:{}};function v(P){return(k)=>{let O=k(P);for(let j in S)delete O[j];let N={...P,...O};for(let j in O){let R=P[j],K=O[j];if(SB(R)&&SB(K))N[j]={...R,...K}}return Object.assign(N,{extend:v(N)})}}return Object.assign(S,{extend:v(S)})}function SB(e){if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Qo(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(i={})=>{if(o.length===1)return o(i);return o(e,i)}}for(let n of["extractEvent","extractEvents"])if(Object.hasOwn(t,n))r[n]=t[n];return r}Mr();rs();xn();ri();Ac();mn();Fe();He();os();function xd(e){if(!(e instanceof C))return!1;let t=e.walk((r)=>r instanceof bd);if(!(t instanceof bd))return!1;if(t.data?.errorName==="HttpError")return!0;if(t.data?.errorName==="ResolverError")return!0;if(t.data?.errorName==="ResolverNotContract")return!0;if(t.data?.errorName==="ResolverNotFound")return!0;if(t.data?.errorName==="ReverseAddressMismatch")return!0;if(t.data?.errorName==="UnsupportedResolverProfile")return!0;return!1}rm();xr();Fe();Kn();function Ry(e){if(e.length!==66)return null;if(e.indexOf("[")!==0)return null;if(e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;if(!Kt(t))return null;return t}function nm(e){let t=new Uint8Array(32).fill(0);if(!e)return mt(t);let r=e.split(".");for(let n=r.length-1;n>=0;n-=1){let o=Ry(r[n]),i=o?Wn(o):St(To(r[n]),"bytes");t=St(fr([t,i]),"bytes")}return mt(t)}xr();function eL(e){return`[${e.slice(2)}]`}xr();Fe();Kn();function tL(e){let t=new Uint8Array(32).fill(0);if(!e)return mt(t);return Ry(e)||St(To(e))}function _d(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(To(t).byteLength+2),n=0,o=t.split(".");for(let i=0;i<o.length;i++){let s=To(o[i]);if(s.byteLength>255)s=To(eL(tL(o[i])));r[n]=s.length,r.set(s,n+1),n+=s.length+1}if(r.byteLength!==n+1)return r.slice(0,n+1);return r}function J(e,t,r){let n=e[t.name];if(typeof n==="function")return n;let o=e[r];if(typeof o==="function")return o;return(i)=>t(e,i)}rs();xn();ir();He();os();Mc();Fd();var Bae=3;function $n(e,{abi:t,address:r,args:n,docsPath:o,functionName:i,sender:s}){let a=e instanceof ns?e:e instanceof C?e.walk((y)=>("data"in y))||e.walk():{},{code:c,data:d,details:l,message:p,shortMessage:m}=a,h=(()=>{if(e instanceof vo)return new AE({functionName:i,cause:e});if([Bae,ss.code].includes(c)&&(d||l||p||m)||c===Jn.code&&l==="execution reverted"&&d)return new bd({abi:t,data:typeof d==="object"?d.data:d,functionName:i,message:a instanceof Cc?l:m??p,cause:e});return e})();return new tm(h,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:i,sender:s})}ga();async function gt(e,t){let{abi:r,address:n,args:o,functionName:i,...s}=t,a=At({abi:r,args:o,functionName:i});try{let{data:c}=await J(e,Sn,"call")({...s,data:a,to:n});return Dr({abi:r,args:o,functionName:i,data:c||"0x"})}catch(c){throw $n(c,{abi:r,address:n,args:o,docsPath:"/docs/contract/readContract",functionName:i})}}async function zL(e,t){let{blockNumber:r,blockTag:n,coinType:o,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Yn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c?.ensTlds;if(l&&!l.some((m)=>i.endsWith(m)))return null;let p=(()=>{if(o!=null)return[nm(i),BigInt(o)];return[nm(i)]})();try{let m=At({abi:lT,functionName:"addr",args:p}),h={address:d,abi:W0,functionName:"resolveWithGateways",args:[Jt(_d(i)),m,s??[is]],blockNumber:r,blockTag:n},x=await J(e,gt,"readContract")(h);if(x[0]==="0x")return null;let _=sce({coinType:o,data:x[0],args:p});if(_==="0x")return null;if($r(_)==="0x00")return null;return _}catch(m){if(a)throw m;if(xd(m))return null;throw m}}function sce({coinType:e,data:t,args:r}){try{return Dr({abi:lT,args:r,functionName:"addr",data:t})}catch(n){if(e==null)throw n;let o=$r(t);if(et(o)===20)return Po(o);throw n}}He();class rP extends C{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class Dc extends C{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class mm extends C{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class nP extends C{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var ace=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,cce=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,uce=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,dce=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function lce(e){try{let t=await fetch(e,{method:"HEAD"});if(t.status===200)return t.headers.get("content-type")?.startsWith("image/");return!1}catch(t){if(typeof t==="object"&&typeof t.response<"u")return!1;if(!Object.hasOwn(globalThis,"Image"))return!1;return new Promise((r)=>{let n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function BL(e,t){if(!e)return t;if(e.endsWith("/"))return e.slice(0,-1);return e}function oP({uri:e,gatewayUrls:t}){let r=uce.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let n=BL(t?.ipfs,"https://ipfs.io"),o=BL(t?.arweave,"https://arweave.net"),i=e.match(ace),{protocol:s,subpath:a,target:c,subtarget:d=""}=i?.groups||{},l=s==="ipns:/"||a==="ipns/",p=s==="ipfs:/"||a==="ipfs/"||cce.test(e);if(e.startsWith("http")&&!l&&!p){let h=e;if(t?.arweave)h=e.replace(/https:\/\/arweave.net/g,t?.arweave);return{uri:h,isOnChain:!1,isEncoded:!1}}if((l||p)&&c)return{uri:`${n}/${l?"ipns":"ipfs"}/${c}${d}`,isOnChain:!1,isEncoded:!1};if(s==="ar:/"&&c)return{uri:`${o}/${c}${d||""}`,isOnChain:!1,isEncoded:!1};let m=e.replace(dce,"");if(m.startsWith("<svg"))m=`data:image/svg+xml;base64,${btoa(m)}`;if(m.startsWith("data:")||m.startsWith("{"))return{uri:m,isOnChain:!0,isEncoded:!1};throw new mm({uri:e})}function iP(e){if(typeof e!=="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new rP({data:e});return e.image||e.image_url||e.image_data}async function LL({gatewayUrls:e,uri:t}){try{let r=await fetch(t).then((o)=>o.json());return await Hy({gatewayUrls:e,uri:iP(r)})}catch{throw new mm({uri:t})}}async function Hy({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:n}=oP({uri:t,gatewayUrls:e});if(n)return r;if(await lce(r))return r;throw new mm({uri:t})}function DL(e){let t=e;if(t.startsWith("did:nft:"))t=t.replace("did:nft:","").replace(/_/g,"/");let[r,n,o]=t.split("/"),[i,s]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Dc({reason:"Only EIP-155 supported"});if(!s)throw new Dc({reason:"Chain ID not found"});if(!c)throw new Dc({reason:"Contract address not found"});if(!o)throw new Dc({reason:"Token ID not found"});if(!a)throw new Dc({reason:"ERC namespace not found"});return{chainID:Number.parseInt(s,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:o}}async function UL(e,{nft:t}){if(t.namespace==="erc721")return gt(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return gt(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new nP({namespace:t.namespace})}async function FL(e,{gatewayUrls:t,record:r}){if(/eip155:/i.test(r))return pce(e,{gatewayUrls:t,record:r});return Hy({uri:r,gatewayUrls:t})}async function pce(e,{gatewayUrls:t,record:r}){let n=DL(r),o=await UL(e,{nft:n}),{uri:i,isOnChain:s,isEncoded:a}=oP({uri:o,gatewayUrls:t});if(s&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){let d=a?atob(i.replace("data:application/json;base64,","")):i,l=JSON.parse(d);return Hy({uri:iP(l),gatewayUrls:t})}let c=n.tokenID;if(n.namespace==="erc1155")c=c.replace("0x","").padStart(64,"0");return LL({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}Mr();rs();xn();Ac();Fe();rm();async function Gy(e,t){let{blockNumber:r,blockTag:n,key:o,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Yn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c?.ensTlds;if(l&&!l.some((p)=>i.endsWith(p)))return null;try{let p={address:d,abi:W0,args:[Jt(_d(i)),At({abi:dT,functionName:"text",args:[nm(i),o]}),s??[is]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},h=await J(e,gt,"readContract")(p);if(h[0]==="0x")return null;let y=Dr({abi:dT,functionName:"text",data:h[0]});return y===""?null:y}catch(p){if(a)throw p;if(xd(p))return null;throw p}}async function jL(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:o,gatewayUrls:i,strict:s,universalResolverAddress:a}){let c=await J(e,Gy,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:o,universalResolverAddress:a,gatewayUrls:i,strict:s});if(!c)return null;try{return await FL(e,{record:c,gatewayUrls:n})}catch{return null}}Mr();Ac();rm();async function qL(e,t){let{address:r,blockNumber:n,blockTag:o,coinType:i=60n,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Yn({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{let l={address:d,abi:TB,args:[r,i,s??[is]],functionName:"reverseWithGateways",blockNumber:n,blockTag:o},p=J(e,gt,"readContract"),[m]=await p(l);return m||null}catch(l){if(a)throw l;if(xd(l))return null;throw l}}Ac();Fe();async function HL(e,t){let{blockNumber:r,blockTag:n,name:o}=t,{chain:i}=e,s=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!i)throw Error("client chain not configured. universalResolverAddress is required.");return Yn({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i?.ensTlds;if(a&&!a.some((d)=>o.endsWith(d)))throw Error(`${o} is not a valid ENS TLD (${a?.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);let[c]=await J(e,gt,"readContract")({address:s,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Jt(_d(o))],blockNumber:r,blockTag:n});return c}ga();He();Fe();YE();ps();ci();async function GL(e,t){let{account:r=e.account,blockNumber:n,blockTag:o="latest",blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:d,maxFeePerGas:l,maxPriorityFeePerGas:p,to:m,value:h,...y}=t,x=r?ze(r):void 0;try{Sr(t);let w=(typeof n==="bigint"?H(n):void 0)||o,A=e.chain?.formatters?.transactionRequest?.format,v=(A||jr)({...eo(y,{format:A}),account:x,blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:d,maxFeePerGas:l,maxPriorityFeePerGas:p,to:m,value:h},"createAccessList"),P=await e.request({method:"eth_createAccessList",params:[v,w]});if(P.error)throw new C(P.error,{details:P.error});return{accessList:P.accessList,gasUsed:BigInt(P.gasUsed)}}catch(_){throw Fy(_,{...t,account:x,chain:e.chain})}}function ya(e,{method:t}){let r={};if(e.transport.type==="fallback")e.transport.onResponse?.(({method:n,response:o,status:i,transport:s})=>{if(i==="success"&&t===n)r[o]=s.request});return(n)=>r[n]||e.request}async function VL(e){let t=ya(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}ir();He();class sP extends C{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}xr();Kn();Yf();Qi();Zi();la();var ZL="/docs/contract/encodeEventTopics";function ui(e){let{abi:t,eventName:r,args:n}=e,o=t[0];if(r){let c=bn({abi:t,name:r});if(!c)throw new J0(r,{docsPath:ZL});o=c}if(o.type!=="event")throw new J0(void 0,{docsPath:ZL});let i=[];if(n&&"inputs"in o){let c=o.inputs?.filter((l)=>("indexed"in l)&&l.indexed),d=Array.isArray(n)?n:Object.values(n).length>0?c?.map((l)=>n[l.name])??[]:[];if(d.length>0)i=c?.map((l,p)=>{if(Array.isArray(d[p]))return d[p].map((m,h)=>WL({param:l,value:d[p][h]}));return typeof d[p]<"u"&&d[p]!==null?WL({param:l,value:d[p]}):null})??[]}if(o.anonymous)return i;let s=dr(o);return[da(s),...i]}function WL({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return St(Wn(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new sP(e.type);return nn([e],[t])}Fe();async function Vy(e,t){let{address:r,abi:n,args:o,eventName:i,fromBlock:s,strict:a,toBlock:c}=t,d=ya(e,{method:"eth_newFilter"}),l=i?ui({abi:n,args:o,eventName:i}):void 0,p=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof s==="bigint"?H(s):s,toBlock:typeof c==="bigint"?H(c):c,topics:l}]});return{abi:n,args:o,eventName:i,id:p,request:d(p),strict:Boolean(a),type:"event"}}Fe();async function Zy(e,{address:t,args:r,event:n,events:o,fromBlock:i,strict:s,toBlock:a}={}){let c=o??(n?[n]:void 0),d=ya(e,{method:"eth_newFilter"}),l=[];if(c){if(l=[c.flatMap((h)=>ui({abi:[h],eventName:h.name,args:r}))],n)l=l[0]}let p=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i==="bigint"?H(i):i,toBlock:typeof a==="bigint"?H(a):a,...l.length?{topics:l}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:p,request:d(p),strict:Boolean(s),toBlock:a,type:"event"}}async function Wy(e){let t=ya(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}xn();He();ri();Kn();function Ky(e){let t=St(`0x${e.substring(4)}`).substring(26);return Yi(`0x${t}`)}mn();lr();Fe();async function s9({hash:e,signature:t}){let r=Kt(e)?e:Jt(e);await Promise.resolve().then(() => hm());return`0x${(()=>{if(typeof t==="object"&&"r"in t&&"s"in t){let{r:d,s:l,v:p,yParity:m}=t,h=Number(m??p),y=i9(h);return new hs.Signature(er(d),er(l)).addRecoveryBit(y)}let s=Kt(t)?t:Jt(t);if(et(s)!==65)throw Error("invalid signature length");let a=Yt(`0x${s.slice(130)}`),c=i9(a);return hs.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function i9(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw Error("Invalid yParityOrV value")}async function gm({hash:e,signature:t}){return Ky(await s9({hash:e,signature:t}))}xr();Fe();He();cy();xr();Fe();function gs(e,t="hex"){let r=a9(e),n=sd(new Uint8Array(r.length));if(r.encode(n),t==="hex")return mt(n.bytes);return n.bytes}function a9(e){if(Array.isArray(e))return wce(e.map((t)=>a9(t)));return Sce(e)}function wce(e){let t=e.reduce((o,i)=>o+i.length,0),r=c9(t);return{length:(()=>{if(t<=55)return 1+t;return 1+r+t})(),encode(o){if(t<=55)o.pushByte(192+t);else if(o.pushByte(247+r),r===1)o.pushUint8(t);else if(r===2)o.pushUint16(t);else if(r===3)o.pushUint24(t);else o.pushUint32(t);for(let{encode:i}of e)i(o)}}}function Sce(e){let t=typeof e==="string"?pr(e):e,r=c9(t.length);return{length:(()=>{if(t.length===1&&t[0]<128)return 1;if(t.length<=55)return 1+t.length;return 1+r+t.length})(),encode(o){if(t.length===1&&t[0]<128)o.pushBytes(t);else if(t.length<=55)o.pushByte(128+t.length),o.pushBytes(t);else{if(o.pushByte(183+r),r===1)o.pushUint8(t.length);else if(r===2)o.pushUint16(t.length);else if(r===3)o.pushUint24(t.length);else o.pushUint32(t.length);o.pushBytes(t)}}}}function c9(e){if(e<256)return 1;if(e<65536)return 2;if(e<16777216)return 3;if(e<4294967296)return 4;throw new C("Length is too large.")}Kn();function Yy(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,i=St(Qt(["0x05",gs([t?H(t):"0x",o,r?H(r):"0x"])]));if(n==="bytes")return pr(i);return i}async function ba(e){let{authorization:t,signature:r}=e;return gm({hash:Yy(t),signature:r??t})}Fe();ky();gd();He();on();class fP extends C{constructor(e,{account:t,docsPath:r,chain:n,data:o,gas:i,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:d,to:l,value:p}){let m=Ic({from:t?.address,to:l,value:typeof p<"u"&&`${hd(p)} ${n?.nativeCurrency?.symbol||"ETH"}`,data:o,gas:i,gasPrice:typeof s<"u"&&`${mr(s)} gwei`,maxFeePerGas:typeof a<"u"&&`${mr(a)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${mr(c)} gwei`,nonce:d});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",m].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}ls();fm();function u9(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Oo)return e;return o})();return new fP(n,{docsPath:t,...r})}ps();qy();ci();gd();He();class ym extends C{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Uc extends C{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class mP extends C{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${mr(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}lr();He();class Fc extends C{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}Fe();lr();var hP={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Yd(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?Yt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Yt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?hP[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=vce(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function vce(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function Jd(e,t){let r=(e.transactions??[]).map((n)=>{if(typeof n==="string")return n;return Yd(n)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function ar(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let i=o??!1,s=r!==void 0?H(r):void 0,a=null;if(t)a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else a=await e.request({method:"eth_getBlockByNumber",params:[s||n,i]},{dedupe:Boolean(s)});if(!a)throw new Fc({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||Jd)(a,"getBlock")}async function Qd(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function d9(e,t){return gP(e,t)}async function gP(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let i=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof i==="function"){let a=r||await J(e,ar,"getBlock")({}),c=await i({block:a,client:e,request:o});if(c===null)throw Error();return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return er(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):J(e,ar,"getBlock")({}),J(e,Qd,"getGasPrice")({})]);if(typeof i.baseFeePerGas!=="bigint")throw new Uc;let a=s-i.baseFeePerGas;if(a<0n)return 0n;return a}}async function l9(e,t){return Jy(e,t)}async function Jy(e,t){let{block:r,chain:n=e.chain,request:o,type:i="eip1559"}=t||{},s=await(async()=>{if(typeof n?.fees?.baseFeeMultiplier==="function")return n.fees.baseFeeMultiplier({block:r,client:e,request:o});return n?.fees?.baseFeeMultiplier??1.2})();if(s<1)throw new ym;let c=10**(s.toString().split(".")[1]?.length??0),d=(m)=>m*BigInt(Math.round(s*c))/BigInt(c),l=r?r:await J(e,ar,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas==="function"){let m=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:d,request:o,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof l.baseFeePerGas!=="bigint")throw new Uc;let m=typeof o?.maxPriorityFeePerGas==="bigint"?o.maxPriorityFeePerGas:await gP(e,{block:l,chain:n,request:o}),h=d(l.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??h+m,maxPriorityFeePerGas:m}}return{gasPrice:o?.gasPrice??d(await J(e,Qd,"getGasPrice")({}))}}Lc();lr();async function Xd(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getTransactionCount",params:[t,s]},{dedupe:typeof n==="bigint"||r!==void 0});return Yt(a)}on();xr();Fe();function el(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),n=typeof e.blobs[0]==="string"?e.blobs.map((i)=>pr(i)):e.blobs,o=[];for(let i of n)o.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?o:o.map((i)=>mt(i))}xr();Fe();function tl(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),n=typeof e.blobs[0]==="string"?e.blobs.map((s)=>pr(s)):e.blobs,o=typeof e.commitments[0]==="string"?e.commitments.map((s)=>pr(s)):e.commitments,i=[];for(let s=0;s<n.length;s++){let a=n[s],c=o[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map((s)=>mt(s))}Fe();sy();function Tce(e,t,r,n){if(typeof e.setBigUint64==="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,d=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+d,a,n)}function p9(e,t,r){return e&t^~e&r}function f9(e,t,r){return e&t^e&r^t&r}class yP extends Ff{constructor(e,t,r,n){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=oy(this.buffer)}update(e){id(this),e=Uf(e),Tc(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){let a=oy(e);for(;n<=o-i;i+=n)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){id(this),ny(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,ca(this.buffer.subarray(i)),this.padOffset>n-i)this.process(r,0),i=0;for(let l=i;l<n;l++)t[l]=0;Tce(r,n-8,BigInt(this.length*8),o),this.process(r,0);let s=oy(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");let c=a/4,d=this.get();if(c>d.length)throw Error("_sha2: outputLen bigger than state");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=o,e.length=n,e.pos=s,n%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var ys=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);sy();var Ece=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]),xa=new Uint32Array(64);class bP extends yP{constructor(e=32){super(64,e,8,!1);this.A=ys[0]|0,this.B=ys[1]|0,this.C=ys[2]|0,this.D=ys[3]|0,this.E=ys[4]|0,this.F=ys[5]|0,this.G=ys[6]|0,this.H=ys[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}process(e,t){for(let l=0;l<16;l++,t+=4)xa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=xa[l-15],m=xa[l-2],h=Eo(p,7)^Eo(p,18)^p>>>3,y=Eo(m,17)^Eo(m,19)^m>>>10;xa[l]=y+xa[l-7]+h+xa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=Eo(s,6)^Eo(s,11)^Eo(s,25),m=d+p+p9(s,a,c)+Ece[l]+xa[l]|0,y=(Eo(r,2)^Eo(r,13)^Eo(r,22))+f9(r,n,o)|0;d=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,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){ca(xa)}destroy(){this.set(0,0,0,0,0,0,0,0),ca(this.buffer)}}var m9=iy(()=>new bP);var h9=m9;xr();Fe();function g9(e,t){let r=t||"hex",n=h9(Kt(e,{strict:!1})?Wn(e):e);if(r==="bytes")return n;return Jt(n)}function y9(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t==="string"?"hex":"bytes"),o=g9(t,"bytes");return o.set([r],0),n==="bytes"?o:mt(o)}function Qy(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]==="string"?"hex":"bytes"),o=[];for(let i of t)o.push(y9({commitment:i,to:n,version:r}));return o}var b9=32,x9=4096,_9=131072,xP=761855;var Xy=1;He();class _P extends C{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class bm extends C{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class wP extends C{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class SP extends C{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${Xy}`,`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}cy();mn();xr();Fe();function w9(e){let t=e.to??(typeof e.data==="string"?"hex":"bytes"),r=typeof e.data==="string"?pr(e.data):e.data,n=et(r);if(!n)throw new bm;if(n>xP)throw new _P({maxSize:xP,size:n});let o=[],i=!0,s=0;while(i){let a=sd(new Uint8Array(_9)),c=0;while(c<x9){let d=r.slice(s,s+(b9-1));if(a.pushByte(0),a.pushBytes(d),d.length<31){a.pushByte(128),i=!1;break}c++,s+=31}o.push(a)}return t==="bytes"?o.map((a)=>a.bytes):o.map((a)=>mt(a.bytes))}function eb(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??w9({data:t,to:n}),i=e.commitments??el({blobs:o,kzg:r,to:n}),s=e.proofs??tl({blobs:o,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<o.length;c++)a.push({blob:o[c],commitment:i[c],proof:s[c]});return a}Ec();ci();on();function tb(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u"){if(typeof e.accessList<"u")return"eip2930";return"legacy"}throw new vE({transaction:e})}on();ls();on();fm();function _a(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Oo)return e;return o})();return new EE(n,{docsPath:t,...r})}ps();ci();lr();async function qr(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return Yt(t)}async function rl(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:d,gasPrice:l,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:y,nonceManager:x,to:_,type:w,value:A,...S}=t,v=await(async()=>{if(!r)return y;if(!x)return y;if(typeof y<"u")return y;let N=ze(r),j=i?i.id:await J(e,qr,"getChainId")({});return await x.consume({address:N.address,chainId:j,client:e})})();Sr(t);let P=i?.formatters?.transactionRequest?.format,O=(P||jr)({...eo(S,{format:P}),account:r?ze(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:s,data:c,gas:d,gasPrice:l,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:v,to:_,type:w,value:A},"fillTransaction");try{let N=await e.request({method:"eth_fillTransaction",params:[O]}),R=(i?.formatters?.transaction?.format||Yd)(N.tx);delete R.blockHash,delete R.blockNumber,delete R.r,delete R.s,delete R.transactionIndex,delete R.v,delete R.yParity,R.data=R.input;let K=typeof R.feePayerSignature<"u"&&R.feePayerSignature!==null;if(K&&typeof v<"u"&&R.nonce!==v)throw new Xf({filledNonce:R.nonce,requestedNonce:v});if(!K){if(R.gas)R.gas=t.gas??R.gas;if(R.gasPrice)R.gasPrice=t.gasPrice??R.gasPrice;if(R.maxFeePerBlobGas)R.maxFeePerBlobGas=t.maxFeePerBlobGas??R.maxFeePerBlobGas;if(R.maxFeePerGas)R.maxFeePerGas=t.maxFeePerGas??R.maxFeePerGas;if(R.maxPriorityFeePerGas)R.maxPriorityFeePerGas=t.maxPriorityFeePerGas??R.maxPriorityFeePerGas;if(typeof R.nonce<"u")R.nonce=t.nonce??R.nonce;let Z=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let ee=await J(e,ar,"getBlock")({});return i.fees.baseFeeMultiplier({block:ee,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(Z<1)throw new ym;let pe=10**(Z.toString().split(".")[1]?.length??0),U=(ee)=>ee*BigInt(Math.round(Z*pe))/BigInt(pe);if(R.maxFeePerGas&&!t.maxFeePerGas)R.maxFeePerGas=U(R.maxFeePerGas);if(R.gasPrice&&!t.gasPrice)R.gasPrice=U(R.gasPrice)}return{raw:N.raw,transaction:{from:O.from,...R},...N.capabilities?{capabilities:N.capabilities}:{}}}catch(N){throw _a(N,{...t,chain:e.chain})}}var xm=["blobVersionedHashes","chainId","fees","gas","nonce","type"],S9=new Map,vP=new On(128);async function di(e,t){let r=t;r.account??=e.account,r.parameters??=xm;let{account:n,chain:o=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof o?.prepareTransactionRequest==="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt};return})(),c;async function d(){if(c)return c;if(typeof r.chainId<"u")return r.chainId;if(o)return o.id;return c=await J(e,qr,"getChainId")({}),c}let l=n?ze(n):n,p=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"}),p??=r.nonce;let v=r.account??r.from;l=v?ze(v):void 0}if(s.includes("nonce")&&typeof p>"u"&&l&&i){let v=await d();p=await i.consume({address:l.address,chainId:v,client:e})}let h=(()=>{if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs)return!1;if(s.length>0&&"feePayer"in r&&r.feePayer&&!(("feePayerSignature"in r)&&r.feePayerSignature))return!0;if(vP.get(e.uid)===!1)return!1;if(!["fees","gas"].some((P)=>s.includes(P)))return!1;if(s.includes("chainId")&&typeof r.chainId!=="number")return!0;if(s.includes("nonce")&&typeof p!=="number")return!0;if(s.includes("fees")&&typeof r.gasPrice!=="bigint"&&(typeof r.maxFeePerGas!=="bigint"||typeof r.maxPriorityFeePerGas!=="bigint"))return!0;if(s.includes("gas")&&typeof r.gas!=="bigint")return!0;return!1})()?await J(e,rl,"fillTransaction")({...r,nonce:p}).then((v)=>{let{chainId:P,from:k,gas:O,gasPrice:N,nonce:j,maxFeePerBlobGas:R,maxFeePerGas:K,maxPriorityFeePerGas:Z,type:re,...pe}=v.transaction,U="feeToken"in pe?pe.feeToken:void 0,ee="feePayerSignature"in pe&&pe.feePayerSignature!==null&&typeof pe.feePayerSignature<"u",me=typeof U<"u"&&U!==null&&(!("feeToken"in r)||ee);return vP.set(e.uid,!0),{...r,...k?{from:k}:{},...re&&!r.type?{type:re}:{},...typeof P<"u"?{chainId:P}:{},...typeof O<"u"?{gas:O}:{},...typeof N<"u"?{gasPrice:N}:{},...typeof j<"u"?{nonce:j}:{},...typeof R<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:R}:{},...typeof K<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:K}:{},...typeof Z<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:Z}:{},..."nonceKey"in pe&&typeof pe.nonceKey<"u"?{nonceKey:pe.nonceKey}:{},..."keyAuthorization"in pe&&typeof pe.keyAuthorization<"u"&&pe.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:pe.keyAuthorization}:{},..."feePayerSignature"in pe&&typeof pe.feePayerSignature<"u"&&pe.feePayerSignature!==null?{feePayerSignature:pe.feePayerSignature}:{},...me?{feeToken:U}:{},...v.capabilities?{_capabilities:v.capabilities}:{}}}).catch((v)=>{let P=v;if(P.name!=="TransactionExecutionError")return r;if(P.walk?.((j)=>j instanceof Xf))throw v;if(P.walk?.((j)=>j.name==="ExecutionRevertedError"))throw v;if(P.walk?.((j)=>{let R=j;return R.name==="MethodNotFoundRpcError"||R.name==="MethodNotSupportedRpcError"||R.message?.includes("eth_fillTransaction is not available")}))vP.set(e.uid,!1);return r}):r;p??=h.nonce,r={...h,...l?{from:l?.address}:{},...typeof p<"u"?{nonce:p}:{}};let{blobs:y,gas:x,kzg:_,type:w}=r;if(a?.fn&&a.runAt?.includes("beforeFillParameters"))r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"});let A;async function S(){if(A)return A;return A=await J(e,ar,"getBlock")({blockTag:"latest"}),A}if(s.includes("nonce")&&typeof p>"u"&&l&&!i)r.nonce=await J(e,Xd,"getTransactionCount")({address:l.address,blockTag:"pending"});if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&y&&_){let v=el({blobs:y,kzg:_});if(s.includes("blobVersionedHashes")){let P=Qy({commitments:v,to:"hex"});r.blobVersionedHashes=P}if(s.includes("sidecars")){let P=tl({blobs:y,commitments:v,kzg:_}),k=eb({blobs:y,commitments:v,proofs:P,to:"hex"});r.sidecars=k}}if(s.includes("chainId"))r.chainId=await d();if((s.includes("fees")||s.includes("type"))&&typeof w>"u")try{r.type=tb(r)}catch{let v=S9.get(e.uid);if(typeof v>"u")v=typeof(await S())?.baseFeePerGas==="bigint",S9.set(e.uid,v);r.type=v?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let v=await S(),{maxFeePerGas:P,maxPriorityFeePerGas:k}=await Jy(e,{block:v,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<k)throw new mP({maxPriorityFeePerGas:k});r.maxPriorityFeePerGas=k,r.maxFeePerGas=P}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Uc;if(typeof r.gasPrice>"u"){let v=await S(),{gasPrice:P}=await Jy(e,{block:v,chain:o,request:r,type:"legacy"});r.gasPrice=P}}if(s.includes("gas")&&typeof x>"u")r.gas=await J(e,nl,"estimateGas")({...r,account:l,prepare:l?.type==="local"?[]:["blobVersionedHashes"]});if(a?.fn&&a.runAt?.includes("afterFillParameters"))r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"});return Sr(r),delete r.parameters,r}async function nl(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ze(r):void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local")return["blobVersionedHashes"];return})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await ba({authorization:t.authorizationList[0]}).catch(()=>{throw new C("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:l,blockNumber:p,blockTag:m,data:h,gas:y,gasPrice:x,maxFeePerBlobGas:_,maxFeePerGas:w,maxPriorityFeePerGas:A,nonce:S,value:v,stateOverride:P,...k}=n?await di(e,{...t,parameters:i,to:s}):t;if(y&&t.gas!==y)return y;let N=(typeof p==="bigint"?H(p):void 0)||m,j=Wd(P);Sr(t);let R=e.chain?.formatters?.transactionRequest?.format,Z=(R||jr)({...eo(k,{format:R}),account:o,accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:l,data:h,gasPrice:x,maxFeePerBlobGas:_,maxFeePerGas:w,maxPriorityFeePerGas:A,nonce:S,to:s,value:v},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:j?[Z,N??e.experimental_blockTag??"latest",j]:N?[Z,N]:[Z]}))}catch(s){throw u9(s,{...t,account:o,chain:e.chain})}}async function ol(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=At({abi:r,args:o,functionName:i});try{return await J(e,nl,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:n,...a})}catch(d){let l=a.account?ze(a.account):void 0;throw $n(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:l?.address})}}Mr();rs();xn();Lc();ga();async function v9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o=e.experimental_blockTag??"latest",requireCanonical:i}){let s=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let c=e.chain.contracts.multicall3.address,d=At({abi:Zn,functionName:"getEthBalance",args:[t]}),{data:l}=await J(e,Sn,"call")({to:c,data:d,blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});return Dr({abi:Zn,functionName:"getEthBalance",args:[t],data:l||"0x"})}let a=await e.request({method:"eth_getBalance",params:[t,s]});return BigInt(a)}async function T9(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var Pce=new Map,Ace=new Map;function E9(e){let t=(o,i)=>({clear:()=>i.delete(o),get:()=>i.get(o),set:(s)=>i.set(o,s)}),r=t(e,Pce),n=t(e,Ace);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function P9(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=E9(t),o=n.response.get();if(o&&r>0){if(Date.now()-o.created.getTime()<r)return o.data}let i=n.promise.get();if(!i)i=e(),n.promise.set(i);try{let s=await i;return n.response.set({created:new Date,data:s}),s}finally{n.promise.clear()}}var Ice=(e)=>`blockNumber.${e}`;async function to(e,{cacheTime:t=e.cacheTime}={}){let r=await P9(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Ice(e.uid),cacheTime:t});return BigInt(r)}Fe();lr();function Tr(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var TP={"0x0":"reverted","0x1":"success"};function il(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map((n)=>Tr(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Yt(e.transactionIndex):null,status:e.status?TP[e.status]:null,type:e.type?hP[e.type]||e.type:null};if(e.blobGasPrice)r.blobGasPrice=BigInt(e.blobGasPrice);if(e.blobGasUsed)r.blobGasUsed=BigInt(e.blobGasUsed);return r}async function A9(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}={}){let o=r!==void 0?H(r):void 0,i=await e.request({method:"eth_getBlockReceipts",params:[t||o||n]},{dedupe:Boolean(t||o)});if(!i)throw new Fc({blockHash:t,blockNumber:r});let s=e.chain?.formatters?.transactionReceipt?.format||il;return i.map((a)=>s(a,"getBlockReceipts"))}lr();Fe();async function I9(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){let o=r!==void 0?H(r):void 0,i;if(t)i=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0});else i=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[o||n]},{dedupe:Boolean(o)});return Yt(i)}Lc();async function jc(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getCode",params:[t,s]},{dedupe:typeof n==="bigint"||r!==void 0});if(a==="0x")return;return a}la();us();xr();Kn();Yf();ir();DT();mn();Yf();Vf();Zi();var k9="/docs/contract/decodeEventLog";function qc(e){let{abi:t,data:r,strict:n,topics:o}=e,i=n??!0,[s,...a]=o;if(!s)throw new wT({docsPath:k9});let c=t.find((w)=>w.type==="event"&&s===da(dr(w)));if(!(c&&("name"in c))||c.type!=="event")throw new ST(s,{docsPath:k9});let{name:d,inputs:l}=c,p=l?.some((w)=>!(("name"in w)&&w.name)),m=p?[]:{},h=l.map((w,A)=>[w,A]).filter(([w])=>("indexed"in w)&&w.indexed),y=[];for(let w=0;w<h.length;w++){let[A,S]=h[w],v=a[w];if(!v){if(i)throw new Sc({abiItem:c,param:A});y.push([A,S]);continue}m[p?S:A.name||S]=kce({param:A,value:v})}let x=l.filter((w)=>!(("indexed"in w)&&w.indexed)),_=i?x:[...y.map(([w])=>w),...x];if(_.length>0){if(r&&r!=="0x")try{let w=Xi(_,r);if(w){let A=0;if(!i)for(let[S,v]of y)m[p?v:S.name||v]=w[A++];if(p){for(let S=0;S<l.length;S++)if(m[S]===void 0&&A<w.length)m[S]=w[A++]}else for(let S=0;S<x.length;S++)m[x[S].name]=w[A++]}}catch(w){if(i){if(w instanceof $f||w instanceof qf)throw new sa({abiItem:c,data:r,params:_,size:et(r)});throw w}}else if(i)throw new sa({abiItem:c,data:"0x",params:_,size:0})}return{eventName:d,args:Object.values(m).length>0?m:void 0}}function kce({param:e,value:t}){if(e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))return t;return(Xi([e],t)||[])[0]}function li(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,i=(()=>{if(!e.eventName)return;if(Array.isArray(e.eventName))return e.eventName;return[e.eventName]})(),s=t.filter((a)=>a.type==="event").map((a)=>({abi:a,selector:da(a)}));return n.map((a)=>{let c=typeof a.blockNumber==="string"?Tr(a):a,d=s.filter((m)=>c.topics[0]===m.selector);if(d.length===0)return null;let l,p;for(let m of d)try{l=qc({...c,abi:[m.abi],strict:!0}),p=m;break}catch{}if(!l&&!o){p=d[0];try{l=qc({data:c.data,topics:c.topics,abi:[p.abi],strict:!1})}catch{let m=p.abi.inputs?.some((h)=>!(("name"in h)&&h.name));return{...c,args:m?[]:{},eventName:p.abi.name}}}if(!l||!p)return null;if(i&&!i.includes(l.eventName))return null;if(!Rce({args:l.args,inputs:p.abi.inputs,matchArgs:r}))return null;return{...l,...c}}).filter(Boolean)}function Rce(e){let{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function o(i,s,a){try{if(i.type==="address")return wr(s,a);if(i.type==="string"||i.type==="bytes")return St(Wn(s))===a;return s===a}catch{return!1}}if(Array.isArray(t)&&Array.isArray(n))return n.every((i,s)=>{if(i===null||i===void 0)return!0;let a=r[s];if(!a)return!1;return(Array.isArray(i)?i:[i]).some((d)=>o(a,d,t[s]))});if(typeof t==="object"&&!Array.isArray(t)&&typeof n==="object"&&!Array.isArray(n))return Object.entries(n).every(([i,s])=>{if(s===null||s===void 0)return!0;let a=r.find((d)=>d.name===i);if(!a)return!1;return(Array.isArray(s)?s:[s]).some((d)=>o(a,d,t[i]))});return!1}Fe();async function sl(e,{address:t,blockHash:r,fromBlock:n,toBlock:o,event:i,events:s,args:a,strict:c}={}){let d=c??!1,l=s??(i?[i]:void 0),p=[];if(l){if(p=[l.flatMap((x)=>ui({abi:[x],eventName:x.name,args:s?void 0:a}))],i)p=p[0]}let m;if(r)m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]});else m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof n==="bigint"?H(n):n,toBlock:typeof o==="bigint"?H(o):o}]});let h=m.map((y)=>Tr(y));if(!l)return h;return li({abi:l,args:a,logs:h,strict:d})}async function rb(e,t){let{abi:r,address:n,args:o,blockHash:i,eventName:s,fromBlock:a,toBlock:c,strict:d}=t,l=s?bn({abi:r,name:s}):void 0,p=!l?r.filter((m)=>m.type==="event"):void 0;return J(e,sl,"getLogs")({address:n,args:o,blockHash:i,event:l,events:p,fromBlock:a,toBlock:c,strict:d})}ri();mn();Ji();async function R9(e,{address:t,blockNumber:r,blockTag:n="latest"}){let o=await jc(e,{address:t,...r!==void 0?{blockNumber:r}:{blockTag:n}});if(!o)return;if(et(o)!==23)return;if(!o.startsWith("0xef0100"))return;return Po(gn(o,3,23))}He();class EP extends C{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function O9(e,t){let{address:r,factory:n,factoryData:o}=t;try{let[i,s,a,c,d,l,p]=await J(e,gt,"readContract")({abi:Oce,address:r,functionName:"eip712Domain",factory:n,factoryData:o});return{domain:{name:s,version:a,chainId:Number(c),verifyingContract:d,salt:l},extensions:p,fields:i}}catch(i){let s=i;if(s.name==="ContractFunctionExecutionError"&&s.cause.name==="ContractFunctionZeroDataError")throw new EP({address:r});throw s}}var Oce=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];Fe();function C9(e){return{baseFeePerGas:e.baseFeePerGas.map((t)=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map((t)=>t.map((r)=>BigInt(r)))}}async function M9(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:o}){let i=typeof r==="bigint"?H(r):void 0,s=await e.request({method:"eth_feeHistory",params:[H(t),i||n,o]},{dedupe:Boolean(i)});return C9(s)}async function wa(e,{filter:t}){let r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]==="string")return n;let o=n.map((i)=>Tr(i));if(!("abi"in t)||!t.abi)return o;return li({abi:t.abi,logs:o,strict:r})}async function $9(e,{filter:t}){let r=t.strict??!1,o=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map((i)=>Tr(i));if(!t.abi)return o;return li({abi:t.abi,logs:o,strict:r})}Lc();xn();lr();function Cce(e){return e.map((t)=>({...t,value:BigInt(t.value)}))}function N9(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?Yt(e.nonce):void 0,storageProof:e.storageProof?Cce(e.storageProof):void 0}}async function z9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i,storageKeys:s}){let a=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),c=await e.request({method:"eth_getProof",params:[t,s,a]});return N9(c)}on();async function B9(e,{hash:t}){let r=await e.request({method:"eth_getRawTransactionByHash",params:[t]},{dedupe:!0});if(!r)throw new kc({hash:t});return r}Lc();async function L9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i,slot:s}){let a=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});return await e.request({method:"eth_getStorageAt",params:[t,s,a]})}on();Fe();async function al(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:i,sender:s,nonce:a}){let c=n||"latest",d=r!==void 0?H(r):void 0,l=null;if(o)l=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0});else if(t)l=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,H(i)]},{dedupe:!0});else if((d||c)&&typeof i==="number")l=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[d||c,H(i)]},{dedupe:Boolean(d)});else if(s&&typeof a==="number")l=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,H(a)]},{dedupe:!0});if(!l)throw new kc({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:i});return(e.chain?.formatters?.transaction?.format||Yd)(l,"getTransaction")}async function D9(e,{hash:t,transactionReceipt:r}){let[n,o]=await Promise.all([J(e,to,"getBlockNumber")({}),t?J(e,al,"getTransaction")({hash:t}):void 0]),i=r?.blockNumber||o?.blockNumber;if(!i)return 0n;return n-i+1n}on();async function cl(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new em({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||il)(r,"getTransactionReceipt")}Mr();ir();He();os();rs();xn();Ac();jy();async function U9(e,t){let{account:r,authorizationList:n,allowFailure:o=!0,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,requireCanonical:d,stateOverride:l}=t,p=t.contracts,m=typeof e.batch?.multicall==="object"?e.batch.multicall:{},h=t.batchSize??m.batchSize??1024,y=t.deployless??m.deployless??!1,x=(()=>{if(t.multicallAddress)return t.multicallAddress;if(y)return null;if(e.chain)return Yn({blockNumber:s,chain:e.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),_=[[]],w=0,A=0;for(let O=0;O<p.length;O++){let{abi:N,address:j,args:R,functionName:K}=p[O];try{let Z=At({abi:N,args:R,functionName:K});if(A+=(Z.length-2)/2,h>0&&A>h&&_[w].length>0)w++,A=(Z.length-2)/2,_[w]=[];_[w]=[..._[w],{allowFailure:!0,callData:Z,target:j}]}catch(Z){let re=$n(Z,{abi:N,address:j,args:R,docsPath:"/docs/contract/multicall",functionName:K,sender:r});if(!o)throw re;_[w]=[..._[w],{allowFailure:!0,callData:"0x",target:j}]}}let S=Boolean(e.batch?.multicall),v=S?_.flatMap((O)=>O.map((N)=>[N])):_,P=await Promise.allSettled(v.map((O)=>{if(S)return Mce(e,{account:r,authorizationList:n,batchSize:h,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,call:O[0],multicallAddress:x,requireCanonical:d,stateOverride:l}).then((N)=>[N]);return J(e,gt,"readContract")({...x===null?{code:zc}:{address:x},abi:Zn,account:r,args:[O],authorizationList:n,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,functionName:"aggregate3",requireCanonical:d,stateOverride:l})})),k=[];for(let O=0;O<P.length;O++){let N=P[O];if(N.status==="rejected"){if(!o)throw N.reason;for(let R=0;R<v[O].length;R++)k.push({status:"failure",error:N.reason,result:void 0});continue}let j=N.value;for(let R=0;R<j.length;R++){let{returnData:K,success:Z}=j[R],{callData:re}=v[O][R],{abi:pe,address:U,functionName:ee,args:me}=p[k.length];try{if(re==="0x")throw new vo;if(!Z)throw new ns({data:K});let z=Dr({abi:pe,args:me,data:K,functionName:ee});k.push(o?{result:z,status:"success"}:z)}catch(z){let F=$n(z,{abi:pe,address:U,args:me,docsPath:"/docs/contract/multicall",functionName:ee});if(!o)throw F;k.push({error:F,result:void 0,status:"failure"})}}}if(k.length!==p.length)throw new C("multicall results mismatch");return k}async function Mce(e,t){let{batchSize:r,call:n,multicallAddress:o,...i}=t,{wait:s=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{schedule:a}=Zd({id:Je(["multicall",e.uid,r,o,i]),wait:s,shouldSplitBatch(d){if(r===0)return!1;return d.reduce((p,{callData:m})=>p+(m.length-2)/2,0)>r},fn:(d)=>J(e,gt,"readContract")({...o===null?{code:zc}:{address:o},...i,abi:Zn,args:[d],functionName:"aggregate3"})}),[c]=await a(n);return c}WE();ir();os();ls();rs();xn();Fe();fm();ps();qy();ci();async function ul(e,t){let{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:o,returnFullTransactions:i,traceTransfers:s,validation:a}=t;try{let c=[];for(let m of o){let h=m.blockOverrides?Ly(m.blockOverrides):void 0,y=m.calls.map((_)=>{let w=_,A=w.account?ze(w.account):void 0,S=w.abi?At(w):w.data,v={...w,account:A,data:w.dataSuffix?fr([S||"0x",w.dataSuffix]):S,from:w.from??A?.address};return Sr(v),jr(v)}),x=m.stateOverrides?Wd(m.stateOverrides):void 0;c.push({blockOverrides:h,calls:y,stateOverrides:x})}let l=(typeof r==="bigint"?H(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:s,validation:a},l]})).map((m,h)=>({...Jd(m),calls:m.calls.map((y,x)=>{let{abi:_,args:w,functionName:A,to:S}=o[h].calls[x],v=y.error?.data??y.returnData,P=BigInt(y.gasUsed),k=y.logs?.map((R)=>Tr(R)),O=y.status==="0x1"?"success":"failure",N=_&&O==="success"&&v!=="0x"?Dr({abi:_,data:v,functionName:A}):null,j=(()=>{if(O==="success")return;let R;if(v==="0x")R=new vo;else if(v)R=new ns({data:v});if(!R)return;return $n(R,{abi:_??[],address:S??"0x",args:w,functionName:A??"<unknown>"})})();return{data:v,gasUsed:P,logs:k,status:O,...O==="success"?{result:N}:{error:j}}})}))}catch(c){let d=c,l=ha(d,{});if(l instanceof Oo)throw d;throw l}}Kf();Qn();/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function $ce(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function PP(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function _m(e,...t){if(!$ce(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function AP(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function F9(e,t){_m(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function j9(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function IP(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Nce=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function zce(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Bce(e){for(let t=0;t<e.length;t++)e[t]=zce(e[t]);return e}var kP=Nce?(e)=>e:Bce;function Lce(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function RP(e){if(typeof e==="string")e=Lce(e);return _m(e),e}class OP{}function q9(e){let t=(n)=>e().update(RP(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}var nb=BigInt(4294967295),H9=BigInt(32);function Dce(e,t=!1){if(t)return{h:Number(e&nb),l:Number(e>>H9&nb)};return{h:Number(e>>H9&nb)|0,l:Number(e&nb)|0}}function G9(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}=Dce(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var V9=(e,t,r)=>e<<r|t>>>32-r,Z9=(e,t,r)=>t<<r|e>>>32-r,W9=(e,t,r)=>t<<r-32|e>>>64-r,K9=(e,t,r)=>e<<r-32|t>>>64-r;var Uce=BigInt(0),wm=BigInt(1),Fce=BigInt(2),jce=BigInt(7),qce=BigInt(256),Hce=BigInt(113),Q9=[],X9=[],eD=[];for(let e=0,t=wm,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Q9.push(2*(5*n+r)),X9.push((e+1)*(e+2)/2%64);let o=Uce;for(let i=0;i<7;i++)if(t=(t<<wm^(t>>jce)*Hce)%qce,t&Fce)o^=wm<<(wm<<BigInt(i))-wm;eD.push(o)}var tD=G9(eD,!0),Gce=tD[0],Vce=tD[1],Y9=(e,t,r)=>r>32?W9(e,t,r):V9(e,t,r),J9=(e,t,r)=>r>32?K9(e,t,r):Z9(e,t,r);function Zce(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,d=r[c],l=r[c+1],p=Y9(d,l,1)^r[a],m=J9(d,l,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=p,e[s+h+1]^=m}let o=e[2],i=e[3];for(let s=0;s<24;s++){let a=X9[s],c=Y9(o,i,a),d=J9(o,i,a),l=Q9[s];o=e[l],i=e[l+1],e[l]=c,e[l+1]=d}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=Gce[n],e[1]^=Vce[n]}IP(r)}class CP extends OP{constructor(e,t,r,n=!1,o=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=o,PP(r),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=j9(this.state)}clone(){return this._cloneInto()}keccak(){kP(this.state32),Zce(this.state32,this.rounds),kP(this.state32),this.posOut=0,this.pos=0}update(e){AP(this),e=RP(e),_m(e);let{blockLen:t,state:r}=this,n=e.length;for(let o=0;o<n;){let i=Math.min(t-this.pos,n-o);for(let s=0;s<i;s++)r[this.pos++]^=e[o++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:n}=this;if(e[r]^=t,(t&128)!==0&&r===n-1)this.keccak();e[n-1]^=128,this.keccak()}writeInto(e){AP(this,!1),_m(e),this.finish();let t=this.state,{blockLen:r}=this;for(let n=0,o=e.length;n<o;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,o-n);e.set(t.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return PP(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(F9(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,IP(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new CP(t,r,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}var Wce=(e,t,r)=>q9(()=>new CP(t,e,r));var rD=(()=>Wce(1,136,32))();qd();wn();function ob(e,t={}){let{as:r=typeof e==="string"?"Hex":"Bytes"}=t,n=rD(mL(e));if(r==="Bytes")return n;return Ur(n)}wn();qd();class MP extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e)&&t!==void 0)this.delete(e),super.set(e,t);return t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=this.keys().next().value;if(r)this.delete(r)}return this}}var Kce={checksum:new MP(8192)},ib=Kce.checksum;Qn();var Jce=/^0x[a-fA-F0-9]{40}$/;function dl(e,t={}){let{strict:r=!0}=t;if(!Jce.test(e))throw new $P({address:e,cause:new oD});if(r){if(e.toLowerCase()===e)return;if(NP(e)!==e)throw new $P({address:e,cause:new iD})}}function NP(e){if(ib.has(e))return ib.get(e);dl(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=ob(hL(t),{as:"Bytes"}),n=t.split("");for(let i=0;i<40;i+=2){if(r[i>>1]>>4>=8&&n[i])n[i]=n[i].toUpperCase();if((r[i>>1]&15)>=8&&n[i+1])n[i+1]=n[i+1].toUpperCase()}let o=`0x${n.join("")}`;return ib.set(e,o),o}function sb(e,t={}){let{strict:r=!0}=t??{};try{return dl(e,{strict:r}),!0}catch{return!1}}class $P extends Ee{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class oD extends Ee{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class iD extends Ee{constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}Qn();function cb(e){let t=!0,r="",n=0,o="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a))t=!0;if(a==="(")n++;if(a===")")n--;if(!t)continue;if(n===0){if(a===" "&&["event","function","error",""].includes(o))o="";else if(o+=a,a===")"){i=!0;break}continue}if(a===" "){if(e[s-1]!==","&&r!==","&&r!==",(")r="",t=!1;continue}o+=a,r+=a}if(!i)throw new Ee("Unable to normalize signature.");return o}function ab(e,t){let r=typeof e,n=t.type;switch(n){case"address":return sb(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(n==="tuple"&&"components"in t)return Object.values(t.components).every((o,i)=>ab(Object.values(e)[i],o));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n))return r==="number"||r==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n))return r==="string"||e instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n))return Array.isArray(e)&&e.every((o)=>ab(o,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function BP(e,t,r){for(let n in e){let o=e[n],i=t[n];if(o.type==="tuple"&&i.type==="tuple"&&"components"in o&&"components"in i)return BP(o.components,i.components,r[n]);let s=[o.type,i.type];if((()=>{if(s.includes("address")&&s.includes("bytes20"))return!0;if(s.includes("address")&&s.includes("string"))return sb(r[n],{strict:!1});if(s.includes("address")&&s.includes("bytes"))return sb(r[n],{strict:!1});return!1})())return s}return}function ll(e,t={}){let{prepare:r=!0}=t,n=(()=>{if(Array.isArray(e))return xy(e);if(typeof e==="string")return xy(e);return e})();return{...n,...r?{hash:Sa(n)}:{}}}function pl(e,t,r){let{args:n=[],prepare:o=!0}=r??{},i=ZE(t,{strict:!1}),s=e.filter((d)=>{if(i){if(d.type==="function"||d.type==="error")return LP(d)===Fr(t,0,4);if(d.type==="event")return Sa(d)===t;return!1}return"name"in d&&d.name===t});if(s.length===0)throw new va({name:t});if(s.length===1)return{...s[0],...o?{hash:Sa(s[0])}:{}};let a;for(let d of s){if(!("inputs"in d))continue;if(!n||n.length===0){if(!d.inputs||d.inputs.length===0)return{...d,...o?{hash:Sa(d)}:{}};continue}if(!d.inputs)continue;if(d.inputs.length===0)continue;if(d.inputs.length!==n.length)continue;if(n.every((p,m)=>{let h="inputs"in d&&d.inputs[m];if(!h)return!1;return ab(p,h)})){if(a&&"inputs"in a&&a.inputs){let p=BP(d.inputs,a.inputs,n);if(p)throw new sD({abiItem:d,type:p[0]},{abiItem:a,type:p[1]})}a=d}}let c=(()=>{if(a)return a;let[d,...l]=s;return{...d,overloads:l}})();if(!c)throw new va({name:t});return{...c,...o?{hash:Sa(c)}:{}}}function LP(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return pl(r,n)}return e[0]})();return Fr(Sa(t),0,4)}function Xce(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,o]=e;return pl(n,o)}return e[0]})(),r=(()=>{if(typeof t==="string")return t;return Pc(t)})();return cb(r)}function Sa(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return pl(r,n)}return e[0]})();if(typeof t!=="string"&&"hash"in t&&t.hash)return t.hash;return ob(Gd(Xce(t)))}class sD extends Ee{constructor(e,t){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${cb(Pc(e.abiItem))}\`, and`,`\`${t.type}\` in \`${cb(Pc(t.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class va extends Ee{constructor({name:e,data:t,type:r="item"}){let n=(()=>{if(e)return` with name "${e}"`;if(t)return` with data "${t}"`;return""})();super(`ABI ${r}${n} not found.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}Kf();qd();Qn();wn();qd();Qn();wn();var aD=/^(.*)\[([0-9]*)\]$/,cD=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,ub=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,MBe=2n**(8n-1n)-1n,$Be=2n**(16n-1n)-1n,NBe=2n**(24n-1n)-1n,zBe=2n**(32n-1n)-1n,BBe=2n**(40n-1n)-1n,LBe=2n**(48n-1n)-1n,DBe=2n**(56n-1n)-1n,UBe=2n**(64n-1n)-1n,FBe=2n**(72n-1n)-1n,jBe=2n**(80n-1n)-1n,qBe=2n**(88n-1n)-1n,HBe=2n**(96n-1n)-1n,GBe=2n**(104n-1n)-1n,VBe=2n**(112n-1n)-1n,ZBe=2n**(120n-1n)-1n,WBe=2n**(128n-1n)-1n,KBe=2n**(136n-1n)-1n,YBe=2n**(144n-1n)-1n,JBe=2n**(152n-1n)-1n,QBe=2n**(160n-1n)-1n,XBe=2n**(168n-1n)-1n,e3e=2n**(176n-1n)-1n,t3e=2n**(184n-1n)-1n,r3e=2n**(192n-1n)-1n,n3e=2n**(200n-1n)-1n,o3e=2n**(208n-1n)-1n,i3e=2n**(216n-1n)-1n,s3e=2n**(224n-1n)-1n,a3e=2n**(232n-1n)-1n,c3e=2n**(240n-1n)-1n,u3e=2n**(248n-1n)-1n,d3e=2n**(256n-1n)-1n,l3e=-(2n**(8n-1n)),p3e=-(2n**(16n-1n)),f3e=-(2n**(24n-1n)),m3e=-(2n**(32n-1n)),h3e=-(2n**(40n-1n)),g3e=-(2n**(48n-1n)),y3e=-(2n**(56n-1n)),b3e=-(2n**(64n-1n)),x3e=-(2n**(72n-1n)),_3e=-(2n**(80n-1n)),w3e=-(2n**(88n-1n)),S3e=-(2n**(96n-1n)),v3e=-(2n**(104n-1n)),T3e=-(2n**(112n-1n)),E3e=-(2n**(120n-1n)),P3e=-(2n**(128n-1n)),A3e=-(2n**(136n-1n)),I3e=-(2n**(144n-1n)),k3e=-(2n**(152n-1n)),R3e=-(2n**(160n-1n)),O3e=-(2n**(168n-1n)),C3e=-(2n**(176n-1n)),M3e=-(2n**(184n-1n)),$3e=-(2n**(192n-1n)),N3e=-(2n**(200n-1n)),z3e=-(2n**(208n-1n)),B3e=-(2n**(216n-1n)),L3e=-(2n**(224n-1n)),D3e=-(2n**(232n-1n)),U3e=-(2n**(240n-1n)),F3e=-(2n**(248n-1n)),j3e=-(2n**(256n-1n)),q3e=2n**8n-1n,H3e=2n**16n-1n,G3e=2n**24n-1n,V3e=2n**32n-1n,Z3e=2n**40n-1n,W3e=2n**48n-1n,K3e=2n**56n-1n,Y3e=2n**64n-1n,J3e=2n**72n-1n,Q3e=2n**80n-1n,X3e=2n**88n-1n,eLe=2n**96n-1n,tLe=2n**104n-1n,rLe=2n**112n-1n,nLe=2n**120n-1n,oLe=2n**128n-1n,iLe=2n**136n-1n,sLe=2n**144n-1n,aLe=2n**152n-1n,cLe=2n**160n-1n,uLe=2n**168n-1n,dLe=2n**176n-1n,lLe=2n**184n-1n,pLe=2n**192n-1n,fLe=2n**200n-1n,mLe=2n**208n-1n,hLe=2n**216n-1n,gLe=2n**224n-1n,yLe=2n**232n-1n,bLe=2n**240n-1n,xLe=2n**248n-1n,UP=2n**256n-1n;function Hc(e,t,r){let{checksumAddress:n,staticPosition:o}=r,i=qP(t.type);if(i){let[s,a]=i;return tue(e,{...t,type:a},{checksumAddress:n,length:s,staticPosition:o})}if(t.type==="tuple")return iue(e,t,{checksumAddress:n,staticPosition:o});if(t.type==="address")return eue(e,{checksum:n});if(t.type==="bool")return rue(e);if(t.type.startsWith("bytes"))return nue(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return oue(e,t);if(t.type==="string")return sue(e,{staticPosition:o});throw new Sm(t.type)}var dD=32,FP=32;function eue(e,t={}){let{checksum:r=!1}=t,n=e.readBytes(32);return[((i)=>r?NP(i):i)(Ur(gL(n,-20))),32]}function tue(e,t,r){let{checksumAddress:n,length:o,staticPosition:i}=r;if(o===null){let c=ii(e.readBytes(FP)),d=i+c,l=d+dD;e.setPosition(d);let p=ii(e.readBytes(dD)),m=fl(t),h=0,y=[];for(let x=0;x<p;++x){e.setPosition(l+(m?x*32:h));let[_,w]=Hc(e,t,{checksumAddress:n,staticPosition:l});if(h+=w,y.push(_),w===0)e.assertReadLimit(),e._touch()}return e.setPosition(i+32),[y,32]}if(fl(t)){let c=ii(e.readBytes(FP)),d=i+c,l=[];for(let p=0;p<o;++p){e.setPosition(d+p*32);let[m]=Hc(e,t,{checksumAddress:n,staticPosition:d});l.push(m)}return e.setPosition(i+32),[l,32]}let s=0,a=[];for(let c=0;c<o;++c){let[d,l]=Hc(e,t,{checksumAddress:n,staticPosition:i+s});if(s+=l,a.push(d),l===0)e.assertReadLimit(),e._touch()}return[a,s]}function rue(e){return[bL(e.readBytes(32),{size:32}),32]}function nue(e,t,{staticPosition:r}){let[n,o]=t.type.split("bytes");if(!o){let s=ii(e.readBytes(32));e.setPosition(r+s);let a=ii(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[Ur(c),32]}return[Ur(e.readBytes(Number.parseInt(o,10),32)),32]}function oue(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?yL(o,{signed:r}):ii(o,{signed:r}),32]}function iue(e,t,r){let{checksumAddress:n,staticPosition:o}=r,i=t.components.length===0||t.components.some(({name:c})=>!c),s=i?[]:{},a=0;if(fl(t)){let c=ii(e.readBytes(FP)),d=o+c;for(let l=0;l<t.components.length;++l){let p=t.components[l];e.setPosition(d+a);let[m,h]=Hc(e,p,{checksumAddress:n,staticPosition:d});a+=h,s[i?l:p?.name]=m}return e.setPosition(o+32),[s,32]}for(let c=0;c<t.components.length;++c){let d=t.components[c],[l,p]=Hc(e,d,{checksumAddress:n,staticPosition:o});s[i?c:d?.name]=l,a+=p}return[s,a]}function sue(e,{staticPosition:t}){let r=ii(e.readBytes(32)),n=t+r;e.setPosition(n);let o=ii(e.readBytes(32));if(o===0)return e.setPosition(t+32),["",32];let i=e.readBytes(o,32),s=xL(qE(i));return e.setPosition(t+32),[s,32]}function lD({checksumAddress:e,parameters:t,values:r}){let n=[];for(let o=0;o<t.length;o++)n.push(jP({checksumAddress:e,parameter:t[o],value:r[o]}));return n}function jP({checksumAddress:e=!1,parameter:t,value:r}){let n=t,o=qP(n.type);if(o){let[i,s]=o;return cue(r,{checksumAddress:e,length:i,parameter:{...n,type:s}})}if(n.type==="tuple")return fue(r,{checksumAddress:e,parameter:n});if(n.type==="address")return aue(r,{checksum:e});if(n.type==="bool")return due(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){let i=n.type.startsWith("int"),[,,s="256"]=ub.exec(n.type)??[];return lue(r,{signed:i,size:Number(s)})}if(n.type.startsWith("bytes"))return uue(r,{type:n.type});if(n.type==="string")return pue(r);throw new Sm(n.type)}function db(e){let t=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)t+=32;else t+=sr(a)}let r=[],n=[],o=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)r.push(rr(t+o,{size:32})),n.push(a),o+=sr(a);else r.push(a)}return _r(...r,...n)}function aue(e,t){let{checksum:r=!1}=t;return dl(e,{strict:r}),{dynamic:!1,encoded:cs(e.toLowerCase())}}function cue(e,t){let{checksumAddress:r,length:n,parameter:o}=t,i=n===null;if(!Array.isArray(e))throw new GP(e);if(!i&&e.length!==n)throw new HP({expectedLength:n,givenLength:e.length,type:`${o.type}[${n}]`});let s=e.length===0&&fl(o),a=[];for(let c=0;c<e.length;c++){let d=jP({checksumAddress:r,parameter:o,value:e[c]});if(d.dynamic)s=!0;a.push(d)}if(i||s){let c=db(a);if(i){let d=rr(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?_r(d,c):d}}if(s)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:_r(...a.map(({encoded:c})=>c))}}function uue(e,{type:t}){let[,r]=t.split("bytes"),n=sr(e);if(!r){let o=e;if(n%32!==0)o=si(o,Math.ceil((e.length-2)/2/32)*32);return{dynamic:!0,encoded:_r(cs(rr(n,{size:32})),o)}}if(n!==Number.parseInt(r,10))throw new lb({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:si(e)}}function due(e){if(typeof e!=="boolean")throw new Ee(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:cs(zy(e))}}function lue(e,{signed:t,size:r}){if(typeof r==="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||e<o)throw new By({max:n.toString(),min:o.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:rr(e,{size:32,signed:t})}}function pue(e){let t=Gd(e),r=Math.ceil(sr(t)/32),n=[];for(let o=0;o<r;o++)n.push(si(Fr(t,o*32,(o+1)*32)));return{dynamic:!0,encoded:_r(si(rr(sr(t),{size:32})),...n)}}function fue(e,t){let{checksumAddress:r,parameter:n}=t,o=!1,i=[];for(let s=0;s<n.components.length;s++){let a=n.components[s],c=Array.isArray(e)?s:a.name,d=jP({checksumAddress:r,parameter:a,value:e[c]});if(i.push(d),d.dynamic)o=!0}return{dynamic:o,encoded:o?db(i):_r(...i.map(({encoded:s})=>s))}}function qP(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function fl(e){let{type:t}=e;if(t==="string")return!0;if(t==="bytes")return!0;if(t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(fl);let r=qP(e.type);if(r&&fl({...e,type:r[1]}))return!0;return!1}Qn();var hue={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new mD({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new fD({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new VP({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new VP({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();if(this.positionReadCount.set(this.position,e+1),e>0)this.recursiveReadCount++}};function pD(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(hue);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}class VP extends Ee{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class fD extends Ee{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class mD extends Ee{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function ml(e,t,r={}){let{as:n="Array",checksumAddress:o=!1}=r,i=typeof t==="string"?jE(t):t,s=pD(i);if(Xn(i)===0&&e.length>0)throw new gD;if(Xn(i)&&Xn(i)<32)throw new hD({data:typeof t==="string"?t:Ur(t),parameters:e,size:Xn(i)});let a=0,c=n==="Array"?[]:{};for(let d=0;d<e.length;++d){let l=e[d];if(a<i.length)s.setPosition(a);let[p,m]=Hc(s,l,{checksumAddress:o,staticPosition:0});if(a+=m,n==="Array")c.push(p);else c[l.name??d]=p}return c}function Gc(e,t,r){let{checksumAddress:n=!1}=r??{};if(e.length!==t.length)throw new WP({expectedLength:e.length,givenLength:t.length});let o=lD({checksumAddress:n,parameters:e,values:t}),i=db(o);if(i.length===0)return"0x";return i}function ZP(e,t){if(e.length!==t.length)throw new WP({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n];r.push(ZP.encode(o,i))}return _r(...r)}(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return dl(c),cs(c.toLowerCase(),o?32:0)}if(r==="string")return Gd(n);if(r==="bytes")return n;if(r==="bool")return cs(zy(n),o?32:1);let i=r.match(ub);if(i){let[c,d,l="256"]=i,p=Number.parseInt(l,10)/8;return rr(n,{size:o?32:p,signed:d==="int"})}let s=r.match(cD);if(s){let[c,d]=s;if(Number.parseInt(d,10)!==(n.length-2)/2)throw new lb({expectedSize:Number.parseInt(d,10),value:n});return si(n,o?32:0)}let a=r.match(aD);if(a&&Array.isArray(n)){let[c,d]=a,l=[];for(let p=0;p<n.length;p++)l.push(t(d,n[p],!0));if(l.length===0)return"0x";return _r(...l)}throw new Sm(r)}e.encode=t})(ZP||(ZP={}));function pb(e){if(Array.isArray(e)&&typeof e[0]==="string")return _y(e);if(typeof e==="string")return _y(e);return e}class hD extends Ee{constructor({data:e,parameters:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${es(t)})`,`Data: ${e} (${r} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class gD extends Ee{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class HP extends Ee{constructor({expectedLength:e,givenLength:t,type:r}){super(`Array length mismatch for type \`${r}\`. Expected: \`${e}\`. Given: \`${t}\`.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class lb extends Ee{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${sr(t)}) does not match expected size (bytes${e}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class WP extends Ee{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join(`
|
|
142
|
-
`));Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class GP extends Ee{constructor(e){super(`Value \`${e}\` is not a valid array.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class Sm extends Ee{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}wn();function yD(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[i,s]=e;return[yue(i),s]}return e})(),{bytecode:n,args:o}=r;return _r(n,t.inputs?.length&&o?.length?Gc(t.inputs,o):"0x")}function bD(e){return ll(e)}function yue(e){let t=e.find((r)=>r.type==="constructor");if(!t)throw new va({name:"constructor"});return t}function xD(e,t={}){return ll(e,t)}function _D(e){return Sa(e)}wn();function wD(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[i,s,a,c]=e;return[KP(i,s),a,c]}return e})(),o=ml(t.outputs,r,n);if(o&&Object.keys(o).length===0)return;if(o&&Object.keys(o).length===1){if(Array.isArray(o))return o[0];return Object.values(o)[0]}return o}function Ta(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[d,l,p]=e;return[KP(d,l,{args:p}),p]}let[a,c]=e;return[a,c]})(),{overloads:n}=t,o=n?KP([t,...n],t.name,{args:r}):t,i=_ue(o),s=r.length>0?Gc(o.inputs,r):void 0;return s?_r(i,s):i}function Vc(e,t={}){return ll(e,t)}function KP(e,t,r){let n=pl(e,t,r);if(n.type!=="function")throw new va({name:t,type:"function"});return n}function _ue(e){return LP(e)}var fb="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",mb="0x0000000000000000000000000000000000000000";He();os();ls();Lf();lr();ga();var Sue="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033",ID="0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063fd00430c1461002d575b5f5ffd5b6100476004803603810190610042919061012b565b610049565b005b80825f375f5f825f865afa610060573d5f5f3e3d5ffd5b3d5f5f3e3d5ff35b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61009982610070565b9050919050565b6100a98161008f565b81146100b3575f5ffd5b50565b5f813590506100c4816100a0565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f8401126100eb576100ea6100ca565b5b8235905067ffffffffffffffff811115610108576101076100ce565b5b602083019150836001820283011115610124576101236100d2565b5b9250929050565b5f5f5f6040848603121561014257610141610068565b5b5f61014f868287016100b6565b935050602084013567ffffffffffffffff8111156101705761016f61006c565b5b61017c868287016100d6565b9250925050925092509256fea2646970667358221220635ed99185cacf3f2acba6921f23687c969cec2bbaf5f9ad599f507e6e105e6964736f6c63430008230033",vue=0x00000000000000000000000000000000deadbeefn,Tue=_D(xD("event Transfer(address indexed from, address indexed to, uint256 value)")),SD=Vc("function balanceOf(address) returns (uint256)"),vD=Vc("function decimals() returns (uint256)"),TD=Vc("function tokenURI(uint256) returns (string)"),ED=Vc("function symbol() returns (string)"),Eue=Vc("function query(address target, bytes data)");async function kD(e,t){let{blockNumber:r,blockTag:n,calls:o,stateOverrides:i,traceAssetChanges:s,traceTransfers:a,validation:c}=t,d=t.account?ze(t.account):void 0;if(s&&!d)throw new C("`account` is required when `traceAssetChanges` is true");let l=d?yD(bD("constructor(bytes, bytes)"),{bytecode:Dy,args:[Sue,Ta(Vc("function getBalance(address)"),[d.address])]}):void 0,p=n??e.experimental_blockTag??"latest",m=r;if(s&&typeof m!=="bigint"&&p!=="earliest"&&p!=="pending")if(p==="latest")m=await to(e,{cacheTime:0});else{let te=await ar(e,{blockTag:p});if(typeof te.number!=="bigint")throw new C(`Block tag \`${p}\` did not resolve to a number.`);m=te.number}let h=typeof m==="bigint"?{blockNumber:m}:{blockTag:p},y=s?await ul(e,{...h,blocks:[{calls:o.map((te)=>({...te,from:d.address})),stateOverrides:i}],traceTransfers:a,validation:c}):void 0,x=y?[...new Set([...Pue(y[0].calls.flatMap((te)=>te.logs??[]),d.address),...t.calls.map((te)=>te.to?.toLowerCase())])].filter((te)=>Boolean(te)&&te!==fb&&te!==mb):[],_=Aue([...d?[d.address]:[],...x,...i?.map(({address:te})=>te)??[]]),w=[{address:_,code:ID}],[A,S]=await Promise.all([s?Promise.all([AD(e,{account:d.address,...h,data:l,stateOverride:i}),...x.map((te)=>AD(e,{account:d.address,address:te,...h,data:Ta(SD,[d.address]),staticCallAddress:_,stateOverride:i}))]):[],ul(e,{...h,blocks:[{calls:[...o,{to:mb}].map((te)=>({...te,from:d?.address})),stateOverrides:i},...s?[{calls:[{data:l}]},{calls:x.map((te)=>({to:_,data:Tm(te,Ta(SD,[d.address]))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Tm(te,Ta(vD))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Tm(te,Ta(TD,[0n]))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Tm(te,Ta(ED))})),stateOverrides:w}]:[]],traceTransfers:a,validation:c})]),v=S[0],[P,k,O,N,j]=s?S.slice(1):[],{calls:R,...K}=v,Z=R.slice(0,-1),re=A.map((te)=>PD(te)?er(te.data):null),pe=P?.calls??[],U=k?.calls??[],me=[...pe,...U].map((te)=>PD(te)?er(te.data):null),z=(O?.calls??[]).map((te)=>YP(te,vD)),F=(j?.calls??[]).map((te)=>YP(te,ED)),Y=(N?.calls??[]).map((te)=>YP(te,TD)),we=[];for(let[te,$e]of me.entries()){let Te=re[te],Pe=A[te],tt=typeof Te==="bigint"?Te:te>0&&Pe?.status==="success"&&Pe.data==="0x"?0n:null;if(typeof $e!=="bigint")continue;if(typeof tt!=="bigint")continue;let yt=z[te-1],ft=F[te-1],q=Y[te-1],ne=(()=>{if(te===0)return{address:fb,decimals:18,symbol:"ETH"};return{address:x[te-1],decimals:q||yt?Number(yt??1):void 0,symbol:ft??void 0}})();we.push({token:ne,value:{pre:tt,post:$e,diff:$e-tt}})}return{assetChanges:we,block:K,results:Z}}function Tm(e,t){return Ta(Eue,[e,t])}function Pue(e,t){let r=ti(t.toLowerCase(),{size:32});return e.filter((n)=>{if(n.topics[0]?.toLowerCase()!==Tue)return!1;if(n.address.toLowerCase()===fb)return!1;return n.topics[1]?.toLowerCase()===r||n.topics[2]?.toLowerCase()===r}).map((n)=>n.address.toLowerCase())}function PD(e){return e.status==="success"&&/^0x[\da-f]{64}$/i.test(e.data)}function YP(e,t){if(e.status==="failure"||e.data==="0x")return null;try{return wD(t,e.data)}catch{return null}}async function AD(e,t){let{account:r,address:n,blockNumber:o,blockTag:i,data:s,staticCallAddress:a,stateOverride:c}=t;try{return{data:(await Sn({...e,ccipRead:!1},{account:n?mb:r,data:n?Tm(n,s):s,stateOverride:n&&a?[...c??[],{address:a,code:ID}]:c,...n?{to:a}:{},...typeof o==="bigint"?{blockNumber:o}:{blockTag:i}})).data??"0x",status:"success"}}catch(d){if(!(d instanceof Oc)||!(d.cause instanceof ai))throw d;return{data:"0x",status:"failure"}}}function Aue(e){let t=new Set(e.map((n)=>n.toLowerCase())),r=vue;while(t.has(`0x${r.toString(16).padStart(40,"0")}`))r++;return`0x${r.toString(16).padStart(40,"0")}`}rs();xn();ga();async function hl(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account?ze(a.account):e.account,d=At({abi:r,args:o,functionName:i});try{let{data:l}=await J(e,Sn,"call")({batch:!1,data:`${d}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),p=Dr({abi:r,args:o,functionName:i,data:l||"0x"}),m=r.filter((h)=>("name"in h)&&h.name===t.functionName);return{result:p,request:{abi:m,address:n,args:o,dataSuffix:s,functionName:i,...a,account:c}}}catch(l){throw $n(l,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:i,sender:c?.address})}}async function Ea(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}Qn();wn();var RD="0x6492649264926492649264926492649264926492649264926492649264926492";function Iue(e){if(Fr(e,-32)!==RD)throw new OD(e)}function kue(e){let{data:t,signature:r,to:n}=e;return _r(Gc(pb("address, bytes, bytes"),[n,t,r]),RD)}function Rue(e){try{return Iue(e),!0}catch{return!1}}class OD extends Ee{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}Qn();wn();function JP(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new hb({signature:e});if(typeof e.s>"u")throw new hb({signature:e});if(r&&typeof e.yParity>"u")throw new hb({signature:e});if(e.r<0n||e.r>UP)throw new BD({value:e.r});if(e.s<0n||e.s>UP)throw new LD({value:e.s});if(typeof e.yParity==="number"&&e.yParity!==0&&e.yParity!==1)throw new gb({value:e.yParity})}function Oue(e){return MD(Ur(e))}function MD(e){if(e.length!==130&&e.length!==132)throw new zD({signature:e});let t=BigInt(Fr(e,0,32)),r=BigInt(Fr(e,32,64)),n=(()=>{let o=Number(`0x${e.slice(130)}`);if(Number.isNaN(o))return;try{return QP(o)}catch{throw new gb({value:o})}})();if(typeof n>"u")return{r:t,s:r};return{r:t,s:r,yParity:n}}function $D(e){if(typeof e.r>"u")return;if(typeof e.s>"u")return;return ND(e)}function ND(e){let t=(()=>{if(typeof e==="string")return MD(e);if(e instanceof Uint8Array)return Oue(e);if(typeof e.r==="string")return Mue(e);if(e.v)return Cue(e);return{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}}})();return JP(t),t}function Cue(e){return{r:e.r,s:e.s,yParity:QP(e.v)}}function Mue(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r==="number"&&typeof n!=="number")n=QP(r);if(typeof n!=="number")throw new gb({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function QP(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new DD({value:e})}class zD extends Ee{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${sr(wL(e))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class hb extends Ee{constructor({signature:e}){super(`Signature \`${$y(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class BD extends Ee{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class LD extends Ee{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class gb extends Ee{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class DD extends Ee{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function FD(e,t={}){if(typeof e.chainId==="string")return $ue(e);return{...e,...t.signature}}function $ue(e){let{address:t,chainId:r,nonce:n}=e,o=$D(e);return{address:t,chainId:Number(r),nonce:BigInt(n),...o}}Qn();wn();var zue="0x8010801080108010801080108010801080108010801080108010801080108010",Bue=pb("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function jD(e){if(typeof e==="string"){if(Fr(e,-32)!==zue)throw new qD(e)}else JP(e.authorization)}function Lue(e){jD(e);let t=Ny(Fr(e,-64,-32)),r=Fr(e,-t-64,-64),n=Fr(e,0,-t-64),[o,i,s]=ml(Bue,r);return{authorization:FD({address:o.delegation,chainId:Number(o.chainId),nonce:o.nonce,yParity:o.yParity,r:o.r,s:o.s}),signature:n,...s&&s!=="0x"?{data:s,to:i}:{}}}function Due(e){try{return jD(e),!0}catch{return!1}}class qD extends Ee{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}Mr();os();Uy();xn();ri();us();ri();us();async function GD({address:e,authorization:t,signature:r}){return wr(Po(e),await ba({authorization:t,signature:r}))}lr();Fe();hm();lr();xr();function yb({r:e,s:t,to:r="hex",v:n,yParity:o}){let i=(()=>{if(o===0||o===1)return o;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw Error("Invalid `v` or `yParity` value")})(),s=`0x${new hs.Signature(er(e),er(t)).toCompactHex()}${i===0?"1b":"1c"}`;if(r==="hex")return s;return pr(s)}ga();async function Aa(e,t){let{address:r,chain:n=e.chain,hash:o,erc6492VerifierAddress:i=t.universalSignatureVerifierAddress??n?.contracts?.erc6492Verifier?.address,multicallAddress:s=t.multicallAddress??n?.contracts?.multicall3?.address,mode:a="auto"}=t;if(n?.verifyHash)return await n.verifyHash(e,t);let c=(()=>{let d=t.signature;if(Kt(d))return d;if(typeof d==="object"&&"r"in d&&"s"in d)return yb(d);return mt(d)})();try{if(a==="eoa")try{if(wr(Po(r),await gm({hash:o,signature:c})))return!0}catch{}if(Due(c))return await Uue(e,{...t,multicallAddress:s,signature:c});return await Fue(e,{...t,verifierAddress:i,signature:c})}catch(d){if(a!=="eoa")try{if(wr(Po(r),await gm({hash:o,signature:c})))return!0}catch{}if(d instanceof Pa)return!1;throw d}}async function Uue(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:i,hash:s,multicallAddress:a,requireCanonical:c}=t,{authorization:d,data:l,signature:p,to:m}=Lue(t.signature);if(await jc(e,{address:r,blockHash:n,blockNumber:o,blockTag:i,requireCanonical:c})===Qt(["0xef0100",d.address]))return await jue(e,{...t,signature:p});let y={address:d.address,chainId:Number(d.chainId),nonce:Number(d.nonce),r:H(d.r,{size:32}),s:H(d.s,{size:32}),yParity:d.yParity};if(!await GD({address:r,authorization:y}))throw new Pa;let _=await J(e,gt,"readContract")({...a?{address:a}:{code:zc},authorizationList:[y],abi:Zn,blockHash:n,blockNumber:o,blockTag:"pending",functionName:"aggregate3",requireCanonical:c,args:[[...l?[{allowFailure:!0,target:m??r,callData:l}]:[],{allowFailure:!0,target:r,callData:At({abi:pT,functionName:"isValidSignature",args:[s,p]})}]]});if(_[_.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new Pa}async function Fue(e,t){let{address:r,factory:n,factoryData:o,hash:i,signature:s,verifierAddress:a,...c}=t,d=await(async()=>{if(!n&&!o)return s;if(Rue(s))return s;return kue({data:o,signature:s,to:n})})(),l=a?{to:a,data:At({abi:Cf,functionName:"isValidSig",args:[r,i,d]}),...c}:{data:Bc({abi:Cf,args:[r,i,d],bytecode:AL}),...c},{data:p}=await J(e,Sn,"call")(l).catch((m)=>{if(m instanceof Oc)throw new Pa;throw m});if(OT(p??"0x0"))return!0;throw new Pa}async function jue(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:i,hash:s,requireCanonical:a,signature:c}=t;if((await J(e,gt,"readContract")({address:r,abi:pT,args:[s,c],blockHash:n,blockNumber:o,blockTag:i,functionName:"isValidSignature",requireCanonical:a}).catch((l)=>{if(l instanceof tm)throw new Pa;throw l})).startsWith("0x1626ba7e"))return!0;throw new Pa}class Pa extends Error{}Kn();var VD=`\x19Ethereum Signed Message:
|
|
141
|
+
${t}`}function D0(e,t){return Li(rd.sign(pc(t),e))}var kf=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var tse=1e4,rse=15000,nse=30000,ose=1000;function or(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function le(e,t){let r=e[t];if(typeof r!=="string"||r.length===0)throw Error(`Invalid WebSocket event: ${t} must be a non-empty string`);return r}function Te(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function So(e,t){if(!Object.hasOwn(e,t))throw Error(`Invalid WebSocket event: ${t} is missing`);let r=e[t];if(r===null||r===void 0)return null;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function eT(e,t){let r=e[t];if(typeof r!=="boolean")throw Error(`Invalid WebSocket event: ${t} must be a boolean`);return r}function X8(e,t){let r=e[t];if(typeof r!=="number"||!Number.isSafeInteger(r)||r<0)throw Error(`Invalid WebSocket event: ${t} must be a non-negative safe integer`);return r}function Rf(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="number"||!Number.isFinite(r))throw Error(`Invalid WebSocket event: ${t} must be a finite number`);return r}function ez(e,t){let r=e[t];if(r===void 0||r===null)return;return X8(e,t)}function ise(e,t){let r=e[t];if(!Array.isArray(r)||r.some((n)=>typeof n!=="string"))throw Error(`Invalid WebSocket event: ${t} must be an array of strings`);return r}function U0(e,t,r){let n=le(e,t);if(!r.includes(n))throw Error(`Invalid WebSocket event: ${t} must be one of ${r.join(", ")}`);return n}function J8(e,t){let r=Te(e,t);return r===void 0||r.length===0?void 0:r}function tz(e){if(!or(e))throw Error("Invalid conditional order event: data must be an object");let t=en(e);return{conditionalOrderId:le(t,"conditionalOrderId"),tradingPairId:le(t,"tradingPairId"),marginAccountId:le(t,"marginAccountId"),positionId:Te(t,"positionId"),parentOrderId:Te(t,"parentOrderId"),associationType:J8(t,"associationType"),linkedGroupId:Te(t,"linkedGroupId"),conditionType:le(t,"conditionType"),triggerSource:le(t,"triggerSource"),triggerPrice:le(t,"triggerPrice"),side:le(t,"side"),positionSide:le(t,"positionSide"),orderType:le(t,"orderType"),limitPrice:Te(t,"limitPrice"),quantity:Te(t,"quantity"),slippageToleranceBps:Rf(t,"slippageToleranceBps"),reduceOnly:eT(t,"reduceOnly"),timeInForce:J8(t,"timeInForce"),state:le(t,"state"),triggeredOrderId:Te(t,"triggeredOrderId"),triggeredAt:Te(t,"triggeredAt"),activatedAt:Te(t,"activatedAt"),cancelledAt:Te(t,"cancelledAt"),expiresAt:Te(t,"expiresAt"),failureReason:Te(t,"failureReason"),reason:le(t,"reason"),updatedAt:le(t,"updatedAt"),version:Rf(t,"version")}}function sse(e){if(!or(e))throw Error("Invalid conditional order event: payload must be an object");return{eventType:U0(e,"event_type",["conditional_order_update"]),userId:le(e,"user_id"),data:tz(e.data)}}function rz(e){if(!or(e))throw Error("Invalid position event: data must be an object");let t=en(e);return{positionId:le(t,"positionId"),marginAccountId:le(t,"marginAccountId"),tradingPairId:le(t,"tradingPairId"),side:le(t,"side"),status:le(t,"status"),size:le(t,"size"),entryPrice:le(t,"entryPrice"),markPrice:Te(t,"markPrice"),unrealizedPnl:Te(t,"unrealizedPnl"),liquidationPrice:Te(t,"liquidationPrice"),isolatedMargin:le(t,"isolatedMargin"),leverage:le(t,"leverage"),riskBucketId:Te(t,"riskBucketId"),marginMode:Te(t,"marginMode"),maintenanceMarginRequired:Te(t,"maintenanceMarginRequired"),initialMarginRequired:Te(t,"initialMarginRequired"),tradeId:Te(t,"tradeId"),orderId:Te(t,"orderId"),reason:le(t,"reason"),updatedAt:le(t,"updatedAt"),version:ez(t,"version")}}function ase(e){if(!or(e))throw Error("Invalid position event: payload must be an object");return{eventType:U0(e,"event_type",["position_update"]),userId:le(e,"user_id"),data:rz(e.data)}}function nz(e){if(!or(e))throw Error("Invalid liquidation event: data must be an object");let t=en(e);return{liquidationId:le(t,"liquidationId"),marginAccountId:le(t,"marginAccountId"),positionId:Te(t,"positionId"),tradingPairId:Te(t,"tradingPairId"),status:le(t,"status"),accountState:le(t,"accountState"),liquidationPrice:Te(t,"liquidationPrice"),markPrice:Te(t,"markPrice"),estimatedShortfall:le(t,"estimatedShortfall"),message:le(t,"message"),triggeredAt:le(t,"triggeredAt")}}function cse(e){if(!or(e))throw Error("Invalid liquidation event: payload must be an object");return{eventType:U0(e,"event_type",["liquidation_alert"]),userId:le(e,"user_id"),data:nz(e.data)}}function oz(e){if(!or(e))throw Error("Invalid account event: data must be an object");let t=en(e);return{marginAccountId:le(t,"marginAccountId"),sequence:X8(t,"sequence"),equity:le(t,"equity"),collateral:le(t,"collateral"),freeCollateral:le(t,"freeCollateral"),marginRatio:le(t,"marginRatio"),maintenanceRequirement:le(t,"maintenanceRequirement"),updatedAt:le(t,"updatedAt")}}function use(e){if(!or(e))throw Error("Invalid account event: payload must be an object");return{eventType:U0(e,"event_type",["account_update"]),userId:le(e,"user_id"),data:oz(e.data)}}function iz(e){if(!or(e))throw Error("Invalid market stats event: data must be an object");let t=en(e);return{symbol:le(t,"symbol"),tradingPairId:le(t,"tradingPairId"),indexPrice:Te(t,"indexPrice"),markPrice:Te(t,"markPrice"),midPrice:Te(t,"midPrice"),bestBidPrice:Te(t,"bestBidPrice"),bestAskPrice:Te(t,"bestAskPrice"),openInterest:Te(t,"openInterest"),openInterestLimit:Te(t,"openInterestLimit"),lastTradePrice:Te(t,"lastTradePrice"),dailyBaseTokenVolume:Te(t,"dailyBaseTokenVolume"),dailyQuoteTokenVolume:Te(t,"dailyQuoteTokenVolume"),dailyPriceLow:Te(t,"dailyPriceLow"),dailyPriceHigh:Te(t,"dailyPriceHigh"),dailyPriceChange:Te(t,"dailyPriceChange"),dailyPriceChangePercent:Te(t,"dailyPriceChangePercent"),currentFundingRate:Te(t,"currentFundingRate"),fundingRate:Te(t,"fundingRate"),fundingTimestamp:Rf(t,"fundingTimestamp"),premium:Te(t,"premium"),baseInterestRate:Te(t,"baseInterestRate"),fundingClampSmall:Te(t,"fundingClampSmall"),fundingClampBig:Te(t,"fundingClampBig")}}function dse(e){if(!or(e))throw Error("Invalid market stats event: payload must be an object");return{tradingPairId:le(e,"trading_pair_id"),data:iz(e.data)}}function sz(e){if(!or(e))throw Error("Invalid market stats summary: entry must be an object");let t=en(e);return{tradingPairId:le(t,"tradingPairId"),symbol:le(t,"symbol"),lastTradePrice:Te(t,"lastTradePrice"),markPrice:Te(t,"markPrice"),dailyPriceChange:Te(t,"dailyPriceChange"),dailyPriceChangePercent:Te(t,"dailyPriceChangePercent"),dailyBaseTokenVolume:Te(t,"dailyBaseTokenVolume"),dailyQuoteTokenVolume:Te(t,"dailyQuoteTokenVolume"),dailyPriceHigh:Te(t,"dailyPriceHigh"),dailyPriceLow:Te(t,"dailyPriceLow"),openInterest:Te(t,"openInterest"),currentFundingRate:Te(t,"currentFundingRate"),fundingTimestamp:Rf(t,"fundingTimestamp"),marketStatus:le(t,"marketStatus")}}function lse(e){if(!or(e)||!Array.isArray(e.markets))throw Error("Invalid market stats all event: markets must be an array");return{markets:e.markets.map(sz)}}function az(e){if(!or(e))throw Error("Invalid instrument event: data must be an object");let t=en(e);return{change:le(t,"change"),tradingPairId:le(t,"tradingPairId"),symbol:le(t,"symbol"),isActive:eT(t,"isActive"),tickSize:le(t,"tickSize"),quantityStepSize:le(t,"quantityStepSize"),minOrderSize:le(t,"minOrderSize"),maxOrderSize:le(t,"maxOrderSize"),marketType:le(t,"marketType"),category:le(t,"category"),maxLeverage:Te(t,"maxLeverage"),initialMarginRate:Te(t,"initialMarginRate"),maintenanceMarginRate:Te(t,"maintenanceMarginRate"),changedFields:ise(t,"changedFields"),updatedAt:le(t,"updatedAt")}}function pse(e){if(!or(e))throw Error("Invalid instrument event: payload must be an object");return{tradingPairId:le(e,"trading_pair_id"),data:az(e.data)}}function fse(e){if(!or(e))throw Error("Invalid TWAP order event: payload must be an object");if(!or(e.data))throw Error("Invalid TWAP order event: data must be an object");if(e.event_type!=="twap_order_update")throw Error("Invalid TWAP order event: event_type must be twap_order_update");let r=e.user_id;if(typeof r!=="string"||r.length===0)throw Error("Invalid TWAP order event: user_id must be a non-empty string");return{eventType:"twap_order_update",userId:r,data:cz(e.data)}}function cz(e){if(!or(e))throw Error("Invalid TWAP order event: data must be an object");let t=en(e);for(let o of Object.keys(t))if(t[o]===null)delete t[o];let r=t.twapOrderId;if(typeof r!=="string"||r.length===0)throw Error("Invalid TWAP order event: twapOrderId must be a non-empty string");let n=t.state;if(typeof n!=="string"||n.length===0)throw Error("Invalid TWAP order event: state must be a non-empty string");return t}function uz(e){if(!or(e))throw Error("Invalid balance event: data must be an object");let t=en(e);return{tokenAddress:le(t,"tokenAddress"),tokenSymbol:So(t,"tokenSymbol"),available:le(t,"available"),availableRaw:le(t,"availableRaw"),locked:le(t,"locked"),lockedRaw:le(t,"lockedRaw"),total:le(t,"total"),totalRaw:le(t,"totalRaw"),version:ez(t,"version"),reason:le(t,"reason"),referenceId:So(t,"referenceId"),updatedAt:le(t,"updatedAt")}}function mse(e){return uz(e)}function Q8(e){if(!or(e))throw Error("Invalid order snapshot: item must be an object");let t=en(e),r=Te(t,"clientOrderId"),n=Te(t,"selfTradePreventionMode"),o=Rf(t,"version");return{orderId:le(t,"orderId"),userId:le(t,"userId"),applicationId:le(t,"applicationId"),tradingPairId:le(t,"tradingPairId"),tradingPair:le(t,"tradingPair"),tradingMode:le(t,"tradingMode"),side:le(t,"side"),orderType:le(t,"orderType"),price:So(t,"price"),quantity:le(t,"quantity"),quantityRaw:le(t,"quantityRaw"),filledQuantity:le(t,"filledQuantity"),filledQuantityRaw:le(t,"filledQuantityRaw"),remainingQuantity:So(t,"remainingQuantity"),remainingQuantityRaw:So(t,"remainingQuantityRaw"),status:le(t,"status"),timeInForce:So(t,"timeInForce"),averageFillPrice:So(t,"averageFillPrice"),createdAt:le(t,"createdAt"),updatedAt:So(t,"updatedAt"),marginAccountId:So(t,"marginAccountId"),positionId:So(t,"positionId"),leverage:So(t,"leverage"),reduceOnly:eT(t,"reduceOnly"),...r===void 0?{}:{clientOrderId:r},...n===void 0?{}:{selfTradePreventionMode:n},...o===void 0?{}:{version:o}}}function wo(e,t,r){return(n)=>{try{if(!Array.isArray(n))throw Error(`Invalid ${e} snapshot: data must be an array`);let o=n.map(t);r(o)}catch(o){console.error(`WebSocket: Error processing ${e} snapshot`,o)}}}function tT(e,t={}){let r=null,n=t.session,o=0,i=null,s=null,a=t.autoReconnect??!0,c=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=Number.isFinite(t.reconnectBaseDelayMs)&&t.reconnectBaseDelayMs>0?t.reconnectBaseDelayMs:ose,l=Number.isFinite(t.connectionTimeoutMs)&&t.connectionTimeoutMs>0?t.connectionTimeoutMs:tse,p=null,m=new Map,h=new Map,y=new Map,x=()=>{if(!r)return i?"reconnecting":"disconnected";switch(r.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return i?"reconnecting":"disconnected"}},_=()=>e,w=()=>{if(!n||r?.readyState!==WebSocket.OPEN)return;let q=Date.now(),ne=D0(_f(n.privateKey),Y8(n.publicKey,q));r.send(JSON.stringify({type:"Authenticate",public_key:n.publicKey,timestamp:q,signature:ne}))},A=()=>{if(s)clearInterval(s),s=null},S=()=>{A(),s=setInterval(()=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify({type:"Ping"}))},rse)},v=()=>{if(i)clearTimeout(i),i=null},P=()=>{if(i)return;if(!a||o>=c){console.error("WebSocket: Max reconnect attempts reached");return}let q=Math.min(d*2**o,nse);o++;let ne=Math.random()*q;i=setTimeout(()=>{if(i=null,!a)return;K().catch((ce)=>{console.warn("WebSocket: Failed to reconnect:",ce),P()})},ne),t.onStatusChange?.("reconnecting")},k=(q)=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify(q))},O=()=>{y.clear();let q=Array.from(m.keys());if(q.length>0)k({type:"Subscribe",channels:q})},N=(q)=>q.startsWith("ohlcv:")&&q.split(":").length===4,j=(q,ne)=>{if(q.endsWith(":*"))return ne.startsWith(q.slice(0,-1));if(N(q))return ne===q||ne===`${q}:trade`;return ne===q||ne.startsWith(`${q}:`)},R=(q)=>{if(q.type==="Error"){if(typeof q.code==="string"&&typeof q.message==="string")t.onError?.({code:q.code,message:q.message});return}if(!q.channel)return;if(q.type==="Snapshot"){for(let ne of h.get(q.channel)??[])ne(q.data);return}if(q.type!=="Event")return;for(let[ne,ce]of m)if(j(ne,q.channel))for(let he of ce)he(q.data)},K=()=>new Promise((q,ne)=>{if(r?.readyState===WebSocket.CONNECTING||r?.readyState===WebSocket.OPEN){q();return}try{let ce=new WebSocket(_());r=ce;let he=setTimeout(()=>{if(r!==ce){q();return}if(ce.readyState===WebSocket.CONNECTING)ce.close(1000,"Connection timeout"),ne(Error("WebSocket connection timeout"))},l);ce.onopen=()=>{if(clearTimeout(he),r!==ce){q();return}if(o=0,v(),S(),w(),O(),t.onStatusChange?.("connected"),p!==null){let Q=p;p=null,t.onResync?.({code:Q,slowClient:Q===1013})}q()},ce.onmessage=(Q)=>{if(r!==ce)return;try{let Be=JSON.parse(Q.data);if(Be.type==="Pong")return;if(Be.type==="Ping"){k({type:"Pong"});return}R(Be)}catch(Be){console.warn("WebSocket: Failed to parse message",Be)}},ce.onclose=(Q)=>{if(clearTimeout(he),r!==ce){q();return}if(r=null,A(),a&&Q.code!==1000){if(p===null||Q.code===1013)p=Q.code;P()}if(!i)t.onStatusChange?.("disconnected")},ce.onerror=()=>clearTimeout(he)}catch(ce){t.onStatusChange?.("disconnected"),ne(ce)}}),Z=()=>{a=!1,v(),A(),p=null,m.clear(),h.clear(),y.clear(),r?.close(1000,"Client disconnect"),r=null,t.onStatusChange?.("disconnected")},re=(q,ne,ce)=>{let he=!m.has(q);if(!m.has(q))m.set(q,new Set);if(m.get(q)?.add(ne),ce){if(!h.has(q))h.set(q,new Set);h.get(q)?.add(ce)}if(he&&r?.readyState===WebSocket.OPEN)k({type:"Subscribe",channels:[q]});return()=>{if(ce){let Be=h.get(q);if(Be?.delete(ce),Be?.size===0)h.delete(q)}let Q=m.get(q);if(Q){if(Q.delete(ne),Q.size===0){if(m.delete(q),r?.readyState===WebSocket.OPEN)k({type:"Unsubscribe",channels:[q]})}}}};return{connect:K,disconnect:Z,isConnected:()=>r?.readyState===WebSocket.OPEN,getStatus:x,setSessionKeypair:(q)=>{if(n=q??void 0,n&&r?.readyState===WebSocket.OPEN)w();else if(n&&(!r||r.readyState===WebSocket.CLOSED))K().catch((ne)=>{console.warn("WebSocket: Failed to connect after session update:",ne)})},orders:(q,ne,ce,he)=>{let Q=`orders:${q}:${ne}`;return re(Q,(Be)=>{try{let bt=Be,xt={orderId:bt.order_id,eventType:bt.event_type,timestamp:bt.timestamp,data:en(bt.data)};ce(xt)}catch(bt){console.error("WebSocket: Error processing order event",bt)}},he&&wo("orders",Q8,he))},orderbook:(q,ne,ce,he,Q)=>{if(!q||!ne||ce===void 0||!he)throw Error(`orderbook subscription requires all params: tradingPairId="${q}", tradingMode="${ne}", magnitude=${ce} (valid: ${kf.join(", ")}), quotationMode="${he}" (valid: "BASE", "QUOTE")`);if(!kf.includes(ce))throw Error(`Invalid magnitude: ${ce}. Must be one of: ${kf.join(", ")}`);let Be=`orderbook:${q}:${ne}:${ce}:${he.toLowerCase()}`;return re(Be,(bt)=>{try{let xt=bt,Qe=xt.data,vt={tradingPairId:xt.trading_pair_id,tradingMode:xt.trading_mode,bids:(Qe?.bids||[]).map((wt)=>({price:wt.price,quantity:wt.quantity,orderCount:wt.order_count||0})),asks:(Qe?.asks||[]).map((wt)=>({price:wt.price,quantity:wt.quantity,orderCount:wt.order_count||0})),bestBid:Qe?.best_bid??void 0,bestAsk:Qe?.best_ask??void 0,bidVolume:Qe?.bid_volume||void 0,askVolume:Qe?.ask_volume||void 0,priceChange:Qe?.price_change?{side:Qe.price_change.side,oldPrice:Qe.price_change.old_price??void 0,newPrice:Qe.price_change.new_price??void 0,levelRemoved:Qe.price_change.level_removed||!1,levelAdded:Qe.price_change.level_added||!1}:void 0,baseDecimals:xt.base_decimals||0,quoteDecimals:xt.quote_decimals||0,timestamp:xt.timestamp||new Date().toISOString(),sequence:xt.sequence_number||0};Q(vt)}catch(xt){console.error("WebSocket: Error processing orderbook event",xt)}})},ohlcv:(q,ne,ce,he,Q)=>{let Be=Q===void 0?`ohlcv:${q}:${ne}:${ce}`:`ohlcv:${q}:${ne}:${ce}:${Q}`;return re(Be,(bt)=>{try{let xt=bt,{data:Qe,price_type:vt}=xt,wt=typeof vt==="string"&&vt!==""?vt:void 0,Hr={tradingPairId:xt.trading_pair_id,tradingMode:xt.trading_mode,interval:xt.interval,priceType:wt,candlestick:{T:Qe.period_start||0,t:Qe.period_end||0,o:Qe.open||"0",h:Qe.high||"0",l:Qe.low||"0",c:Qe.close||"0",v:Qe.volume||"0",s:xt.symbol,i:xt.interval,n:Qe.trades_count||0}};he(Hr)}catch(xt){console.error("WebSocket: Error processing OHLCV event",xt)}})},trades:(q,ne)=>{let ce=`trades:${q}`;return re(ce,(he)=>{try{let Q=he,Be=Q.data,bt={eventType:"trade",tradingPairId:Q.trading_pair_id,tradingMode:Q.trading_mode.toUpperCase(),data:{tradeId:Be.trade_id,price:Be.price,quantity:Be.quantity,makerSide:Be.maker_side.toUpperCase(),executedAt:Be.executed_at}};ne(bt)}catch(Q){console.error("WebSocket: Error processing trade event",Q)}})},movements:(q)=>re("movements",(ce)=>{try{let he=ce,Q=he.data,Be={eventType:"movement",userId:he.user_id,data:{id:Q.id,entryType:Q.entry_type,transactionType:Q.transaction_type,status:Q.status,token:Q.token??Q.token_address,tokenAddress:Q.token??Q.token_address,assetId:Q.asset_id,symbol:Q.symbol,amount:String(Q.amount),amountRaw:Q.amount_raw,balanceBefore:Q.balance_before!=null?String(Q.balance_before):void 0,balanceBeforeRaw:Q.balance_before_raw,balanceAfter:Q.balance_after!=null?String(Q.balance_after):void 0,balanceAfterRaw:Q.balance_after_raw,lockedBefore:Q.locked_before!=null?String(Q.locked_before):void 0,lockedBeforeRaw:Q.locked_before_raw,lockedAfter:Q.locked_after!=null?String(Q.locked_after):void 0,lockedAfterRaw:Q.locked_after_raw,referenceId:Q.reference_id,referenceType:Q.reference_type,description:Q.description,txHash:Q.tx_hash,blockNumber:Q.block_number,createdAt:Q.created_at,decimals:Q.decimals}};q(Be)}catch(he){console.error("WebSocket: Error processing movement event",he)}}),userOrders:(q,ne)=>re("orders",(he)=>{try{let Q=he,Be={orderId:Q.order_id,eventType:Q.event_type,timestamp:Q.timestamp,data:en(Q.data)};q(Be)}catch(Q){console.error("WebSocket: Error processing user order event",Q)}},ne&&wo("orders",Q8,ne)),balances:(q,ne)=>re("balances",(he)=>{try{if(!or(he))throw Error("Invalid balance event: payload must be an object");let Q={eventType:"balance_update",userId:le(he,"user_id"),data:uz(he.data)};q(Q)}catch(Q){console.error("WebSocket: Error processing balance event",Q)}},ne&&wo("balances",mse,ne)),conditionalOrders:(q,ne,ce)=>{if(!q)throw Error("conditionalOrders subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let he=ne?`conditional_orders:${ne}`:"conditional_orders";return re(he,(Q)=>{try{q(sse(Q))}catch(Be){console.error("WebSocket: Error processing conditional order event",Be)}},ce&&wo("conditional orders",tz,ce))},twapOrders:(q,ne,ce)=>{if(!q)throw Error("twapOrders subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("twapOrders tradingPairId cannot be empty");let he=ne?`twap_orders:${ne}`:"twap_orders";return re(he,(Q)=>{try{q(fse(Q))}catch(Be){console.error("WebSocket: Error processing TWAP order event",Be)}},ce&&wo("TWAP orders",cz,ce))},positions:(q,ne,ce)=>{if(!q)throw Error("positions subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("positions tradingPairId cannot be empty");let he=ne?`positions:${ne}`:"positions";return re(he,(Q)=>{try{q(ase(Q))}catch(Be){console.error("WebSocket: Error processing position event",Be)}},ce&&wo("positions",rz,ce))},liquidations:(q,ne,ce)=>{if(!q)throw Error("liquidations subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("liquidations tradingPairId cannot be empty");let he=ne?`liquidations:${ne}`:"liquidations";return re(he,(Q)=>{try{q(cse(Q))}catch(Be){console.error("WebSocket: Error processing liquidation event",Be)}},ce&&wo("liquidations",nz,ce))},account:(q,ne)=>{if(!q)throw Error("account subscription requires a handler");return re("account",(ce)=>{try{q(use(ce))}catch(he){console.error("WebSocket: Error processing account event",he)}},ne&&wo("account",oz,ne))},instruments:(q,ne,ce)=>{if(!q)throw Error("instruments subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("instruments tradingPairId cannot be empty");let he=ne?`instrument:${ne}`:"instrument",Q=(Qe)=>{let vt=y.get(he);if(!vt)vt=new Map,y.set(he,vt);vt.set(Qe.tradingPairId,Qe)},Be=m.has(he),bt=!1,xt=re(he,(Qe)=>{try{let vt=pse(Qe);Q(vt),q(vt)}catch(vt){console.error("WebSocket: Error processing instrument event",vt)}},wo("instrument",az,(Qe)=>{let vt=Qe.map((wt)=>({tradingPairId:wt.tradingPairId,data:wt}));if(y.set(he,new Map(vt.map((wt)=>[wt.tradingPairId,wt]))),ce){ce(Qe);return}for(let wt of vt)q(wt)}));if(Be&&r?.readyState===WebSocket.OPEN){if(y.has(he))queueMicrotask(()=>{if(bt)return;let Qe=y.get(he);if(!Qe||r?.readyState!==WebSocket.OPEN)return;let vt=[...Qe.values()];if(ce){try{ce(vt.filter((wt)=>wt.data.isActive).map((wt)=>wt.data))}catch(wt){console.error("WebSocket: Error processing instrument baseline replay",wt)}return}for(let wt of vt)try{q(wt)}catch(Hr){console.error("WebSocket: Error processing instrument baseline replay",Hr)}})}return()=>{if(bt=!0,xt(),!m.has(he))y.delete(he)}},marketStats:(q,ne,ce)=>{if(!q)throw Error("marketStats subscription requires a tradingPairId");if(!ne)throw Error("marketStats subscription requires a handler");return re(`market_stats:${q}`,(he)=>{try{ne(dse(he))}catch(Q){console.error("WebSocket: Error processing market stats event",Q)}},ce&&wo("market stats",iz,ce))},marketStatsAll:(q,ne)=>{if(!q)throw Error("marketStatsAll subscription requires a handler");return re("market_stats",(ce)=>{if(!or(ce)||!Array.isArray(ce.markets))return;try{q(lse(ce))}catch(he){console.error("WebSocket: Error processing market stats all event",he)}},ne&&wo("all-markets stats",sz,ne))}}}var ia=Vr(j0(),1),wB=["token","accessToken","access_token","refreshToken","refresh_token","authToken","auth_token","bearerToken","bearer_token","jwtToken","jwt_token","apiKey","api_key","apikey","clientSecret","client_secret","clientId","client_id","secret","password","authorization","bearer","auth","credentials","credential","email","phone","phoneNumber","phone_number","ssn","socialSecurity","social_security","address","passport","passportNumber","passport_number","driversLicense","drivers_license","cardNumber","card_number","creditCard","credit_card","cvv","pin","signature","privateKey","private_key","publicKey","public_key","mnemonic","seed","salt","hash","certificate","cert","fingerprint","cookie","session","sessionId","session_id","sessionToken","session_token","ipAddress","ip_address","deviceId","device_id","userId","user_id","accountId","account_id"];function nd(e,t=5,r=0){if(r>=t)return"[Max depth reached]";if(e===null||e===void 0)return e;if(Array.isArray(e)){let o=e.slice(0,10).map((i)=>nd(i,t,r+1));if(e.length>10)o.push(`[... ${e.length-10} more items]`);return o}if(typeof e==="object"){let n={};for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(wB.some((c)=>s.includes(c.toLowerCase())))n[o]="[REDACTED]";else if(typeof i==="string"&&i.length>500)n[o]=`${i.substring(0,500)}... [truncated]`;else n[o]=nd(i,t,r+1)}return n}if(typeof e==="string"){if(e.length>1000)return`${e.substring(0,1000)}... [truncated]`;return e}return e}class od extends Error{cause;suggestion;retryable=!1;timestamp;constructor(e,t){super(e);if(this.name=this.constructor.name,this.timestamp=Date.now(),t?.cause)this.cause=t.cause;if(t?.suggestion)this.suggestion=t.suggestion;if(t?.retryable!==void 0)this.retryable=t.retryable}toJSON(){return{name:this.name,code:this.code,message:this.message,suggestion:this.suggestion,retryable:this.retryable,timestamp:this.timestamp,cause:this.cause instanceof Error?this.cause.message:this.cause}}}class Pt extends od{code="INVALID_CONFIG";field;value;constructor(e,t,r,n){let o=t?`Check the '${t}' configuration parameter. ${kse(t)}`:"Review your SDK configuration and ensure all required fields are provided correctly.";super(e,{cause:n,suggestion:o,retryable:!1});this.field=t,this.value=r}toJSON(){let e;if(this.field){let t=this.field.toLowerCase();if(wB.some((n)=>t.includes(n.toLowerCase())))e="[REDACTED]";else e=nd(this.value)}else e=nd(this.value);return{...super.toJSON(),field:this.field,value:e}}}function kse(e){switch(e.toLowerCase()){case"walletclient":return"Ensure you're creating the wallet client with a valid account and chain configuration.";case"seirpcurl":return"Use 'https://evm-rpc-testnet.sei-apis.com' for testnet or 'https://evm-rpc.sei-apis.com' for mainnet.";case"wsurl":return"Use 'wss://ws-develop.apimonaco.xyz/ws' for testnet or 'wss://ws.apimonaco.xyz/ws' for mainnet.";case"network":return"Valid networks are: 'mainnet', 'development', 'staging', 'local'.";default:return"Refer to the SDK documentation for correct configuration format."}}class Of extends od{code="INVALID_STATE";currentState;expectedState;constructor(e,t,r,n){let o=r?`${t?`Current state is '${t}', `:""}Expected state is '${r}'. Ensure operations are performed in the correct order.`:"Check that prerequisites are met before calling this method.";super(e,{cause:n,suggestion:o,retryable:!1});this.currentState=t,this.expectedState=r}toJSON(){return{...super.toJSON(),currentState:this.currentState,expectedState:this.expectedState}}}class Zt extends od{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor(e,t){let{suggestion:r,retryable:n}=Rse(t?.statusCode,e,t?.responseBody);super(e,{cause:t?.cause,suggestion:r,retryable:n});this.endpoint=t?.endpoint,this.statusCode=t?.statusCode,this.responseBody=t?.responseBody,this.requestBody=t?.requestBody,this.requestId=t?.requestId,this.retryAfter=t?.retryAfter}toJSON(){return{...super.toJSON(),endpoint:this.endpoint,statusCode:this.statusCode,responseBody:nd(this.responseBody),requestBody:nd(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function Rse(e,t,r){if(!e)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if(e===ia.StatusCodes.UNAUTHORIZED){if(t?.toLowerCase().includes("expired"))return{suggestion:"Access token has expired. Call sdk.refreshAuth() to get a new token, or call sdk.login() to re-authenticate.",retryable:!1};return{suggestion:"Authentication required. Call sdk.login(clientId) to authenticate before making this request.",retryable:!1}}if(e===ia.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if(e===ia.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if(e===ia.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if(e===ia.StatusCodes.BAD_REQUEST){if(t?.toLowerCase().includes("insufficient balance"))return{suggestion:"Insufficient balance. Deposit more funds using sdk.vault.deposit() or reduce the order size.",retryable:!1};if(t?.toLowerCase().includes("invalid"))return{suggestion:"Invalid request parameters. Check the API documentation for correct parameter format and values.",retryable:!1};return{suggestion:"Bad request. Verify that all required parameters are provided and correctly formatted.",retryable:!1}}if(e===ia.StatusCodes.TOO_MANY_REQUESTS){let n;if(typeof r==="object"&&r!==null&&"retry_after"in r&&r.retry_after){let o=r.retry_after;n=` Wait ${String(o)} seconds before retrying.`}else n=" Wait a moment before retrying.";return{suggestion:`Rate limit exceeded.${n} Consider implementing exponential backoff for retries.`,retryable:!0}}if(e>=ia.StatusCodes.INTERNAL_SERVER_ERROR&&e<600)return{suggestion:"Server error occurred. This is likely a temporary issue. Try again in a few moments.",retryable:!0};return{suggestion:void 0,retryable:!1}}class Vi extends od{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor(e,t){let r=Ose(t?.revertReason);super(e,{cause:t?.cause,suggestion:r,retryable:!1});this.revertReason=t?.revertReason,this.transactionHash=t?.transactionHash,this.contractAddress=t?.contractAddress}toJSON(){return{...super.toJSON(),revertReason:this.revertReason,transactionHash:this.transactionHash,contractAddress:this.contractAddress}}}function Ose(e){if(!e)return"Smart contract execution failed. Check transaction parameters and try again.";let t=e.toLowerCase();if(t.includes("insufficient allowance"))return"Token allowance is insufficient. Call sdk.vault.approve() to increase the token allowance for the vault contract.";if(t.includes("insufficient balance"))return"Wallet balance is insufficient for this transaction. Ensure you have enough tokens and native currency for gas fees.";if(t.includes("nonce"))return"Transaction nonce error. This may be due to a pending transaction. Wait for pending transactions to complete or reset your account nonce.";if(t.includes("gas"))return"Transaction ran out of gas. Try increasing the gas limit for this transaction.";return}var Cse={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},Mse={local:"ws://localhost:8085/ws",development:"wss://ws-develop.apimonaco.xyz/ws",staging:"wss://ws-staging.apimonaco.xyz/ws",mainnet:"wss://ws.apimonaco.xyz/ws"};function cT(e){return Cse[e]}function uT(e){return Mse[e]}var HA=Vr(j0(),1);var q0=256,H0;function G0(e=11){if(!H0||q0+e>512){H0="",q0=0;for(let t=0;t<256;t++)H0+=(256+Math.random()*256|0).toString(16).substring(1)}return H0.substring(q0,q0+++e)}function V0(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:i="base",name:s="Base Client",tokens:a,type:c="base"}=e,d=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),l=r?.blockTime??12000,p=Math.min(Math.max(Math.floor(l/2),500),4000),m=e.pollingInterval??p,h=e.cacheTime??m,y=e.account?ze(e.account):void 0,{config:x,request:_,value:w}=e.transport({account:y,chain:r,pollingInterval:m}),A={...x,...w},S={account:y,batch:t,cacheTime:h,ccipRead:n,chain:r,dataSuffix:o,key:i,name:s,pollingInterval:m,request:_,tokens:a,transport:A,type:c,uid:G0(),...d?{experimental_blockTag:d}:{}};function v(P){return(k)=>{let O=k(P);for(let j in S)delete O[j];let N={...P,...O};for(let j in O){let R=P[j],K=O[j];if(SB(R)&&SB(K))N[j]={...R,...K}}return Object.assign(N,{extend:v(N)})}}return Object.assign(S,{extend:v(S)})}function SB(e){if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Qo(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(i={})=>{if(o.length===1)return o(i);return o(e,i)}}for(let n of["extractEvent","extractEvents"])if(Object.hasOwn(t,n))r[n]=t[n];return r}Mr();rs();xn();ri();Ac();mn();Fe();He();os();function xd(e){if(!(e instanceof C))return!1;let t=e.walk((r)=>r instanceof bd);if(!(t instanceof bd))return!1;if(t.data?.errorName==="HttpError")return!0;if(t.data?.errorName==="ResolverError")return!0;if(t.data?.errorName==="ResolverNotContract")return!0;if(t.data?.errorName==="ResolverNotFound")return!0;if(t.data?.errorName==="ReverseAddressMismatch")return!0;if(t.data?.errorName==="UnsupportedResolverProfile")return!0;return!1}rm();xr();Fe();Kn();function Ry(e){if(e.length!==66)return null;if(e.indexOf("[")!==0)return null;if(e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;if(!Kt(t))return null;return t}function nm(e){let t=new Uint8Array(32).fill(0);if(!e)return mt(t);let r=e.split(".");for(let n=r.length-1;n>=0;n-=1){let o=Ry(r[n]),i=o?Wn(o):St(To(r[n]),"bytes");t=St(fr([t,i]),"bytes")}return mt(t)}xr();function eL(e){return`[${e.slice(2)}]`}xr();Fe();Kn();function tL(e){let t=new Uint8Array(32).fill(0);if(!e)return mt(t);return Ry(e)||St(To(e))}function _d(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(To(t).byteLength+2),n=0,o=t.split(".");for(let i=0;i<o.length;i++){let s=To(o[i]);if(s.byteLength>255)s=To(eL(tL(o[i])));r[n]=s.length,r.set(s,n+1),n+=s.length+1}if(r.byteLength!==n+1)return r.slice(0,n+1);return r}function J(e,t,r){let n=e[t.name];if(typeof n==="function")return n;let o=e[r];if(typeof o==="function")return o;return(i)=>t(e,i)}rs();xn();ir();He();os();Mc();Fd();var Bae=3;function $n(e,{abi:t,address:r,args:n,docsPath:o,functionName:i,sender:s}){let a=e instanceof ns?e:e instanceof C?e.walk((y)=>("data"in y))||e.walk():{},{code:c,data:d,details:l,message:p,shortMessage:m}=a,h=(()=>{if(e instanceof vo)return new AE({functionName:i,cause:e});if([Bae,ss.code].includes(c)&&(d||l||p||m)||c===Jn.code&&l==="execution reverted"&&d)return new bd({abi:t,data:typeof d==="object"?d.data:d,functionName:i,message:a instanceof Cc?l:m??p,cause:e});return e})();return new tm(h,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:i,sender:s})}ga();async function gt(e,t){let{abi:r,address:n,args:o,functionName:i,...s}=t,a=At({abi:r,args:o,functionName:i});try{let{data:c}=await J(e,Sn,"call")({...s,data:a,to:n});return Dr({abi:r,args:o,functionName:i,data:c||"0x"})}catch(c){throw $n(c,{abi:r,address:n,args:o,docsPath:"/docs/contract/readContract",functionName:i})}}async function zL(e,t){let{blockNumber:r,blockTag:n,coinType:o,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Yn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c?.ensTlds;if(l&&!l.some((m)=>i.endsWith(m)))return null;let p=(()=>{if(o!=null)return[nm(i),BigInt(o)];return[nm(i)]})();try{let m=At({abi:lT,functionName:"addr",args:p}),h={address:d,abi:W0,functionName:"resolveWithGateways",args:[Jt(_d(i)),m,s??[is]],blockNumber:r,blockTag:n},x=await J(e,gt,"readContract")(h);if(x[0]==="0x")return null;let _=sce({coinType:o,data:x[0],args:p});if(_==="0x")return null;if($r(_)==="0x00")return null;return _}catch(m){if(a)throw m;if(xd(m))return null;throw m}}function sce({coinType:e,data:t,args:r}){try{return Dr({abi:lT,args:r,functionName:"addr",data:t})}catch(n){if(e==null)throw n;let o=$r(t);if(et(o)===20)return Po(o);throw n}}He();class rP extends C{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class Dc extends C{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class mm extends C{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class nP extends C{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var ace=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,cce=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,uce=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,dce=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function lce(e){try{let t=await fetch(e,{method:"HEAD"});if(t.status===200)return t.headers.get("content-type")?.startsWith("image/");return!1}catch(t){if(typeof t==="object"&&typeof t.response<"u")return!1;if(!Object.hasOwn(globalThis,"Image"))return!1;return new Promise((r)=>{let n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function BL(e,t){if(!e)return t;if(e.endsWith("/"))return e.slice(0,-1);return e}function oP({uri:e,gatewayUrls:t}){let r=uce.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let n=BL(t?.ipfs,"https://ipfs.io"),o=BL(t?.arweave,"https://arweave.net"),i=e.match(ace),{protocol:s,subpath:a,target:c,subtarget:d=""}=i?.groups||{},l=s==="ipns:/"||a==="ipns/",p=s==="ipfs:/"||a==="ipfs/"||cce.test(e);if(e.startsWith("http")&&!l&&!p){let h=e;if(t?.arweave)h=e.replace(/https:\/\/arweave.net/g,t?.arweave);return{uri:h,isOnChain:!1,isEncoded:!1}}if((l||p)&&c)return{uri:`${n}/${l?"ipns":"ipfs"}/${c}${d}`,isOnChain:!1,isEncoded:!1};if(s==="ar:/"&&c)return{uri:`${o}/${c}${d||""}`,isOnChain:!1,isEncoded:!1};let m=e.replace(dce,"");if(m.startsWith("<svg"))m=`data:image/svg+xml;base64,${btoa(m)}`;if(m.startsWith("data:")||m.startsWith("{"))return{uri:m,isOnChain:!0,isEncoded:!1};throw new mm({uri:e})}function iP(e){if(typeof e!=="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new rP({data:e});return e.image||e.image_url||e.image_data}async function LL({gatewayUrls:e,uri:t}){try{let r=await fetch(t).then((o)=>o.json());return await Hy({gatewayUrls:e,uri:iP(r)})}catch{throw new mm({uri:t})}}async function Hy({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:n}=oP({uri:t,gatewayUrls:e});if(n)return r;if(await lce(r))return r;throw new mm({uri:t})}function DL(e){let t=e;if(t.startsWith("did:nft:"))t=t.replace("did:nft:","").replace(/_/g,"/");let[r,n,o]=t.split("/"),[i,s]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Dc({reason:"Only EIP-155 supported"});if(!s)throw new Dc({reason:"Chain ID not found"});if(!c)throw new Dc({reason:"Contract address not found"});if(!o)throw new Dc({reason:"Token ID not found"});if(!a)throw new Dc({reason:"ERC namespace not found"});return{chainID:Number.parseInt(s,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:o}}async function UL(e,{nft:t}){if(t.namespace==="erc721")return gt(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return gt(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new nP({namespace:t.namespace})}async function FL(e,{gatewayUrls:t,record:r}){if(/eip155:/i.test(r))return pce(e,{gatewayUrls:t,record:r});return Hy({uri:r,gatewayUrls:t})}async function pce(e,{gatewayUrls:t,record:r}){let n=DL(r),o=await UL(e,{nft:n}),{uri:i,isOnChain:s,isEncoded:a}=oP({uri:o,gatewayUrls:t});if(s&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){let d=a?atob(i.replace("data:application/json;base64,","")):i,l=JSON.parse(d);return Hy({uri:iP(l),gatewayUrls:t})}let c=n.tokenID;if(n.namespace==="erc1155")c=c.replace("0x","").padStart(64,"0");return LL({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}Mr();rs();xn();Ac();Fe();rm();async function Gy(e,t){let{blockNumber:r,blockTag:n,key:o,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Yn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c?.ensTlds;if(l&&!l.some((p)=>i.endsWith(p)))return null;try{let p={address:d,abi:W0,args:[Jt(_d(i)),At({abi:dT,functionName:"text",args:[nm(i),o]}),s??[is]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},h=await J(e,gt,"readContract")(p);if(h[0]==="0x")return null;let y=Dr({abi:dT,functionName:"text",data:h[0]});return y===""?null:y}catch(p){if(a)throw p;if(xd(p))return null;throw p}}async function jL(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:o,gatewayUrls:i,strict:s,universalResolverAddress:a}){let c=await J(e,Gy,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:o,universalResolverAddress:a,gatewayUrls:i,strict:s});if(!c)return null;try{return await FL(e,{record:c,gatewayUrls:n})}catch{return null}}Mr();Ac();rm();async function qL(e,t){let{address:r,blockNumber:n,blockTag:o,coinType:i=60n,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Yn({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{let l={address:d,abi:TB,args:[r,i,s??[is]],functionName:"reverseWithGateways",blockNumber:n,blockTag:o},p=J(e,gt,"readContract"),[m]=await p(l);return m||null}catch(l){if(a)throw l;if(xd(l))return null;throw l}}Ac();Fe();async function HL(e,t){let{blockNumber:r,blockTag:n,name:o}=t,{chain:i}=e,s=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!i)throw Error("client chain not configured. universalResolverAddress is required.");return Yn({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i?.ensTlds;if(a&&!a.some((d)=>o.endsWith(d)))throw Error(`${o} is not a valid ENS TLD (${a?.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);let[c]=await J(e,gt,"readContract")({address:s,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Jt(_d(o))],blockNumber:r,blockTag:n});return c}ga();He();Fe();YE();ps();ci();async function GL(e,t){let{account:r=e.account,blockNumber:n,blockTag:o="latest",blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:d,maxFeePerGas:l,maxPriorityFeePerGas:p,to:m,value:h,...y}=t,x=r?ze(r):void 0;try{Sr(t);let w=(typeof n==="bigint"?H(n):void 0)||o,A=e.chain?.formatters?.transactionRequest?.format,v=(A||jr)({...eo(y,{format:A}),account:x,blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:d,maxFeePerGas:l,maxPriorityFeePerGas:p,to:m,value:h},"createAccessList"),P=await e.request({method:"eth_createAccessList",params:[v,w]});if(P.error)throw new C(P.error,{details:P.error});return{accessList:P.accessList,gasUsed:BigInt(P.gasUsed)}}catch(_){throw Fy(_,{...t,account:x,chain:e.chain})}}function ya(e,{method:t}){let r={};if(e.transport.type==="fallback")e.transport.onResponse?.(({method:n,response:o,status:i,transport:s})=>{if(i==="success"&&t===n)r[o]=s.request});return(n)=>r[n]||e.request}async function VL(e){let t=ya(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}ir();He();class sP extends C{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}xr();Kn();Yf();Qi();Zi();la();var ZL="/docs/contract/encodeEventTopics";function ui(e){let{abi:t,eventName:r,args:n}=e,o=t[0];if(r){let c=bn({abi:t,name:r});if(!c)throw new J0(r,{docsPath:ZL});o=c}if(o.type!=="event")throw new J0(void 0,{docsPath:ZL});let i=[];if(n&&"inputs"in o){let c=o.inputs?.filter((l)=>("indexed"in l)&&l.indexed),d=Array.isArray(n)?n:Object.values(n).length>0?c?.map((l)=>n[l.name])??[]:[];if(d.length>0)i=c?.map((l,p)=>{if(Array.isArray(d[p]))return d[p].map((m,h)=>WL({param:l,value:d[p][h]}));return typeof d[p]<"u"&&d[p]!==null?WL({param:l,value:d[p]}):null})??[]}if(o.anonymous)return i;let s=dr(o);return[da(s),...i]}function WL({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return St(Wn(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new sP(e.type);return nn([e],[t])}Fe();async function Vy(e,t){let{address:r,abi:n,args:o,eventName:i,fromBlock:s,strict:a,toBlock:c}=t,d=ya(e,{method:"eth_newFilter"}),l=i?ui({abi:n,args:o,eventName:i}):void 0,p=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof s==="bigint"?H(s):s,toBlock:typeof c==="bigint"?H(c):c,topics:l}]});return{abi:n,args:o,eventName:i,id:p,request:d(p),strict:Boolean(a),type:"event"}}Fe();async function Zy(e,{address:t,args:r,event:n,events:o,fromBlock:i,strict:s,toBlock:a}={}){let c=o??(n?[n]:void 0),d=ya(e,{method:"eth_newFilter"}),l=[];if(c){if(l=[c.flatMap((h)=>ui({abi:[h],eventName:h.name,args:r}))],n)l=l[0]}let p=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i==="bigint"?H(i):i,toBlock:typeof a==="bigint"?H(a):a,...l.length?{topics:l}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:p,request:d(p),strict:Boolean(s),toBlock:a,type:"event"}}async function Wy(e){let t=ya(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}xn();He();ri();Kn();function Ky(e){let t=St(`0x${e.substring(4)}`).substring(26);return Yi(`0x${t}`)}mn();lr();Fe();async function s9({hash:e,signature:t}){let r=Kt(e)?e:Jt(e);await Promise.resolve().then(() => hm());return`0x${(()=>{if(typeof t==="object"&&"r"in t&&"s"in t){let{r:d,s:l,v:p,yParity:m}=t,h=Number(m??p),y=i9(h);return new hs.Signature(er(d),er(l)).addRecoveryBit(y)}let s=Kt(t)?t:Jt(t);if(et(s)!==65)throw Error("invalid signature length");let a=Yt(`0x${s.slice(130)}`),c=i9(a);return hs.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function i9(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw Error("Invalid yParityOrV value")}async function gm({hash:e,signature:t}){return Ky(await s9({hash:e,signature:t}))}xr();Fe();He();cy();xr();Fe();function gs(e,t="hex"){let r=a9(e),n=sd(new Uint8Array(r.length));if(r.encode(n),t==="hex")return mt(n.bytes);return n.bytes}function a9(e){if(Array.isArray(e))return wce(e.map((t)=>a9(t)));return Sce(e)}function wce(e){let t=e.reduce((o,i)=>o+i.length,0),r=c9(t);return{length:(()=>{if(t<=55)return 1+t;return 1+r+t})(),encode(o){if(t<=55)o.pushByte(192+t);else if(o.pushByte(247+r),r===1)o.pushUint8(t);else if(r===2)o.pushUint16(t);else if(r===3)o.pushUint24(t);else o.pushUint32(t);for(let{encode:i}of e)i(o)}}}function Sce(e){let t=typeof e==="string"?pr(e):e,r=c9(t.length);return{length:(()=>{if(t.length===1&&t[0]<128)return 1;if(t.length<=55)return 1+t.length;return 1+r+t.length})(),encode(o){if(t.length===1&&t[0]<128)o.pushBytes(t);else if(t.length<=55)o.pushByte(128+t.length),o.pushBytes(t);else{if(o.pushByte(183+r),r===1)o.pushUint8(t.length);else if(r===2)o.pushUint16(t.length);else if(r===3)o.pushUint24(t.length);else o.pushUint32(t.length);o.pushBytes(t)}}}}function c9(e){if(e<256)return 1;if(e<65536)return 2;if(e<16777216)return 3;if(e<4294967296)return 4;throw new C("Length is too large.")}Kn();function Yy(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,i=St(Qt(["0x05",gs([t?H(t):"0x",o,r?H(r):"0x"])]));if(n==="bytes")return pr(i);return i}async function ba(e){let{authorization:t,signature:r}=e;return gm({hash:Yy(t),signature:r??t})}Fe();ky();gd();He();on();class fP extends C{constructor(e,{account:t,docsPath:r,chain:n,data:o,gas:i,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:d,to:l,value:p}){let m=Ic({from:t?.address,to:l,value:typeof p<"u"&&`${hd(p)} ${n?.nativeCurrency?.symbol||"ETH"}`,data:o,gas:i,gasPrice:typeof s<"u"&&`${mr(s)} gwei`,maxFeePerGas:typeof a<"u"&&`${mr(a)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${mr(c)} gwei`,nonce:d});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",m].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}ls();fm();function u9(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Oo)return e;return o})();return new fP(n,{docsPath:t,...r})}ps();qy();ci();gd();He();class ym extends C{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Uc extends C{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class mP extends C{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${mr(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}lr();He();class Fc extends C{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}Fe();lr();var hP={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Yd(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?Yt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Yt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?hP[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=vce(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function vce(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function Jd(e,t){let r=(e.transactions??[]).map((n)=>{if(typeof n==="string")return n;return Yd(n)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function ar(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let i=o??!1,s=r!==void 0?H(r):void 0,a=null;if(t)a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else a=await e.request({method:"eth_getBlockByNumber",params:[s||n,i]},{dedupe:Boolean(s)});if(!a)throw new Fc({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||Jd)(a,"getBlock")}async function Qd(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function d9(e,t){return gP(e,t)}async function gP(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let i=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof i==="function"){let a=r||await J(e,ar,"getBlock")({}),c=await i({block:a,client:e,request:o});if(c===null)throw Error();return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return er(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):J(e,ar,"getBlock")({}),J(e,Qd,"getGasPrice")({})]);if(typeof i.baseFeePerGas!=="bigint")throw new Uc;let a=s-i.baseFeePerGas;if(a<0n)return 0n;return a}}async function l9(e,t){return Jy(e,t)}async function Jy(e,t){let{block:r,chain:n=e.chain,request:o,type:i="eip1559"}=t||{},s=await(async()=>{if(typeof n?.fees?.baseFeeMultiplier==="function")return n.fees.baseFeeMultiplier({block:r,client:e,request:o});return n?.fees?.baseFeeMultiplier??1.2})();if(s<1)throw new ym;let c=10**(s.toString().split(".")[1]?.length??0),d=(m)=>m*BigInt(Math.round(s*c))/BigInt(c),l=r?r:await J(e,ar,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas==="function"){let m=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:d,request:o,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof l.baseFeePerGas!=="bigint")throw new Uc;let m=typeof o?.maxPriorityFeePerGas==="bigint"?o.maxPriorityFeePerGas:await gP(e,{block:l,chain:n,request:o}),h=d(l.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??h+m,maxPriorityFeePerGas:m}}return{gasPrice:o?.gasPrice??d(await J(e,Qd,"getGasPrice")({}))}}Lc();lr();async function Xd(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getTransactionCount",params:[t,s]},{dedupe:typeof n==="bigint"||r!==void 0});return Yt(a)}on();xr();Fe();function el(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),n=typeof e.blobs[0]==="string"?e.blobs.map((i)=>pr(i)):e.blobs,o=[];for(let i of n)o.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?o:o.map((i)=>mt(i))}xr();Fe();function tl(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),n=typeof e.blobs[0]==="string"?e.blobs.map((s)=>pr(s)):e.blobs,o=typeof e.commitments[0]==="string"?e.commitments.map((s)=>pr(s)):e.commitments,i=[];for(let s=0;s<n.length;s++){let a=n[s],c=o[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map((s)=>mt(s))}Fe();sy();function Tce(e,t,r,n){if(typeof e.setBigUint64==="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,d=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+d,a,n)}function p9(e,t,r){return e&t^~e&r}function f9(e,t,r){return e&t^e&r^t&r}class yP extends Ff{constructor(e,t,r,n){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=oy(this.buffer)}update(e){id(this),e=Uf(e),Tc(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){let a=oy(e);for(;n<=o-i;i+=n)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){id(this),ny(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,ca(this.buffer.subarray(i)),this.padOffset>n-i)this.process(r,0),i=0;for(let l=i;l<n;l++)t[l]=0;Tce(r,n-8,BigInt(this.length*8),o),this.process(r,0);let s=oy(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");let c=a/4,d=this.get();if(c>d.length)throw Error("_sha2: outputLen bigger than state");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=o,e.length=n,e.pos=s,n%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var ys=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);sy();var Ece=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]),xa=new Uint32Array(64);class bP extends yP{constructor(e=32){super(64,e,8,!1);this.A=ys[0]|0,this.B=ys[1]|0,this.C=ys[2]|0,this.D=ys[3]|0,this.E=ys[4]|0,this.F=ys[5]|0,this.G=ys[6]|0,this.H=ys[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}process(e,t){for(let l=0;l<16;l++,t+=4)xa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=xa[l-15],m=xa[l-2],h=Eo(p,7)^Eo(p,18)^p>>>3,y=Eo(m,17)^Eo(m,19)^m>>>10;xa[l]=y+xa[l-7]+h+xa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=Eo(s,6)^Eo(s,11)^Eo(s,25),m=d+p+p9(s,a,c)+Ece[l]+xa[l]|0,y=(Eo(r,2)^Eo(r,13)^Eo(r,22))+f9(r,n,o)|0;d=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,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){ca(xa)}destroy(){this.set(0,0,0,0,0,0,0,0),ca(this.buffer)}}var m9=iy(()=>new bP);var h9=m9;xr();Fe();function g9(e,t){let r=t||"hex",n=h9(Kt(e,{strict:!1})?Wn(e):e);if(r==="bytes")return n;return Jt(n)}function y9(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t==="string"?"hex":"bytes"),o=g9(t,"bytes");return o.set([r],0),n==="bytes"?o:mt(o)}function Qy(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]==="string"?"hex":"bytes"),o=[];for(let i of t)o.push(y9({commitment:i,to:n,version:r}));return o}var b9=32,x9=4096,_9=131072,xP=761855;var Xy=1;He();class _P extends C{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class bm extends C{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class wP extends C{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class SP extends C{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${Xy}`,`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}cy();mn();xr();Fe();function w9(e){let t=e.to??(typeof e.data==="string"?"hex":"bytes"),r=typeof e.data==="string"?pr(e.data):e.data,n=et(r);if(!n)throw new bm;if(n>xP)throw new _P({maxSize:xP,size:n});let o=[],i=!0,s=0;while(i){let a=sd(new Uint8Array(_9)),c=0;while(c<x9){let d=r.slice(s,s+(b9-1));if(a.pushByte(0),a.pushBytes(d),d.length<31){a.pushByte(128),i=!1;break}c++,s+=31}o.push(a)}return t==="bytes"?o.map((a)=>a.bytes):o.map((a)=>mt(a.bytes))}function eb(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??w9({data:t,to:n}),i=e.commitments??el({blobs:o,kzg:r,to:n}),s=e.proofs??tl({blobs:o,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<o.length;c++)a.push({blob:o[c],commitment:i[c],proof:s[c]});return a}Ec();ci();on();function tb(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u"){if(typeof e.accessList<"u")return"eip2930";return"legacy"}throw new vE({transaction:e})}on();ls();on();fm();function _a(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Oo)return e;return o})();return new EE(n,{docsPath:t,...r})}ps();ci();lr();async function qr(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return Yt(t)}async function rl(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:d,gasPrice:l,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:y,nonceManager:x,to:_,type:w,value:A,...S}=t,v=await(async()=>{if(!r)return y;if(!x)return y;if(typeof y<"u")return y;let N=ze(r),j=i?i.id:await J(e,qr,"getChainId")({});return await x.consume({address:N.address,chainId:j,client:e})})();Sr(t);let P=i?.formatters?.transactionRequest?.format,O=(P||jr)({...eo(S,{format:P}),account:r?ze(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:s,data:c,gas:d,gasPrice:l,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:v,to:_,type:w,value:A},"fillTransaction");try{let N=await e.request({method:"eth_fillTransaction",params:[O]}),R=(i?.formatters?.transaction?.format||Yd)(N.tx);delete R.blockHash,delete R.blockNumber,delete R.r,delete R.s,delete R.transactionIndex,delete R.v,delete R.yParity,R.data=R.input;let K=typeof R.feePayerSignature<"u"&&R.feePayerSignature!==null;if(K&&typeof v<"u"&&R.nonce!==v)throw new Xf({filledNonce:R.nonce,requestedNonce:v});if(!K){if(R.gas)R.gas=t.gas??R.gas;if(R.gasPrice)R.gasPrice=t.gasPrice??R.gasPrice;if(R.maxFeePerBlobGas)R.maxFeePerBlobGas=t.maxFeePerBlobGas??R.maxFeePerBlobGas;if(R.maxFeePerGas)R.maxFeePerGas=t.maxFeePerGas??R.maxFeePerGas;if(R.maxPriorityFeePerGas)R.maxPriorityFeePerGas=t.maxPriorityFeePerGas??R.maxPriorityFeePerGas;if(typeof R.nonce<"u")R.nonce=t.nonce??R.nonce;let Z=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let ee=await J(e,ar,"getBlock")({});return i.fees.baseFeeMultiplier({block:ee,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(Z<1)throw new ym;let pe=10**(Z.toString().split(".")[1]?.length??0),U=(ee)=>ee*BigInt(Math.round(Z*pe))/BigInt(pe);if(R.maxFeePerGas&&!t.maxFeePerGas)R.maxFeePerGas=U(R.maxFeePerGas);if(R.gasPrice&&!t.gasPrice)R.gasPrice=U(R.gasPrice)}return{raw:N.raw,transaction:{from:O.from,...R},...N.capabilities?{capabilities:N.capabilities}:{}}}catch(N){throw _a(N,{...t,chain:e.chain})}}var xm=["blobVersionedHashes","chainId","fees","gas","nonce","type"],S9=new Map,vP=new On(128);async function di(e,t){let r=t;r.account??=e.account,r.parameters??=xm;let{account:n,chain:o=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof o?.prepareTransactionRequest==="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt};return})(),c;async function d(){if(c)return c;if(typeof r.chainId<"u")return r.chainId;if(o)return o.id;return c=await J(e,qr,"getChainId")({}),c}let l=n?ze(n):n,p=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"}),p??=r.nonce;let v=r.account??r.from;l=v?ze(v):void 0}if(s.includes("nonce")&&typeof p>"u"&&l&&i){let v=await d();p=await i.consume({address:l.address,chainId:v,client:e})}let h=(()=>{if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs)return!1;if(s.length>0&&"feePayer"in r&&r.feePayer&&!(("feePayerSignature"in r)&&r.feePayerSignature))return!0;if(vP.get(e.uid)===!1)return!1;if(!["fees","gas"].some((P)=>s.includes(P)))return!1;if(s.includes("chainId")&&typeof r.chainId!=="number")return!0;if(s.includes("nonce")&&typeof p!=="number")return!0;if(s.includes("fees")&&typeof r.gasPrice!=="bigint"&&(typeof r.maxFeePerGas!=="bigint"||typeof r.maxPriorityFeePerGas!=="bigint"))return!0;if(s.includes("gas")&&typeof r.gas!=="bigint")return!0;return!1})()?await J(e,rl,"fillTransaction")({...r,nonce:p}).then((v)=>{let{chainId:P,from:k,gas:O,gasPrice:N,nonce:j,maxFeePerBlobGas:R,maxFeePerGas:K,maxPriorityFeePerGas:Z,type:re,...pe}=v.transaction,U="feeToken"in pe?pe.feeToken:void 0,ee="feePayerSignature"in pe&&pe.feePayerSignature!==null&&typeof pe.feePayerSignature<"u",me=typeof U<"u"&&U!==null&&(!("feeToken"in r)||ee);return vP.set(e.uid,!0),{...r,...k?{from:k}:{},...re&&!r.type?{type:re}:{},...typeof P<"u"?{chainId:P}:{},...typeof O<"u"?{gas:O}:{},...typeof N<"u"?{gasPrice:N}:{},...typeof j<"u"?{nonce:j}:{},...typeof R<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:R}:{},...typeof K<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:K}:{},...typeof Z<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:Z}:{},..."nonceKey"in pe&&typeof pe.nonceKey<"u"?{nonceKey:pe.nonceKey}:{},..."keyAuthorization"in pe&&typeof pe.keyAuthorization<"u"&&pe.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:pe.keyAuthorization}:{},..."feePayerSignature"in pe&&typeof pe.feePayerSignature<"u"&&pe.feePayerSignature!==null?{feePayerSignature:pe.feePayerSignature}:{},...me?{feeToken:U}:{},...v.capabilities?{_capabilities:v.capabilities}:{}}}).catch((v)=>{let P=v;if(P.name!=="TransactionExecutionError")return r;if(P.walk?.((j)=>j instanceof Xf))throw v;if(P.walk?.((j)=>j.name==="ExecutionRevertedError"))throw v;if(P.walk?.((j)=>{let R=j;return R.name==="MethodNotFoundRpcError"||R.name==="MethodNotSupportedRpcError"||R.message?.includes("eth_fillTransaction is not available")}))vP.set(e.uid,!1);return r}):r;p??=h.nonce,r={...h,...l?{from:l?.address}:{},...typeof p<"u"?{nonce:p}:{}};let{blobs:y,gas:x,kzg:_,type:w}=r;if(a?.fn&&a.runAt?.includes("beforeFillParameters"))r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"});let A;async function S(){if(A)return A;return A=await J(e,ar,"getBlock")({blockTag:"latest"}),A}if(s.includes("nonce")&&typeof p>"u"&&l&&!i)r.nonce=await J(e,Xd,"getTransactionCount")({address:l.address,blockTag:"pending"});if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&y&&_){let v=el({blobs:y,kzg:_});if(s.includes("blobVersionedHashes")){let P=Qy({commitments:v,to:"hex"});r.blobVersionedHashes=P}if(s.includes("sidecars")){let P=tl({blobs:y,commitments:v,kzg:_}),k=eb({blobs:y,commitments:v,proofs:P,to:"hex"});r.sidecars=k}}if(s.includes("chainId"))r.chainId=await d();if((s.includes("fees")||s.includes("type"))&&typeof w>"u")try{r.type=tb(r)}catch{let v=S9.get(e.uid);if(typeof v>"u")v=typeof(await S())?.baseFeePerGas==="bigint",S9.set(e.uid,v);r.type=v?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let v=await S(),{maxFeePerGas:P,maxPriorityFeePerGas:k}=await Jy(e,{block:v,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<k)throw new mP({maxPriorityFeePerGas:k});r.maxPriorityFeePerGas=k,r.maxFeePerGas=P}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Uc;if(typeof r.gasPrice>"u"){let v=await S(),{gasPrice:P}=await Jy(e,{block:v,chain:o,request:r,type:"legacy"});r.gasPrice=P}}if(s.includes("gas")&&typeof x>"u")r.gas=await J(e,nl,"estimateGas")({...r,account:l,prepare:l?.type==="local"?[]:["blobVersionedHashes"]});if(a?.fn&&a.runAt?.includes("afterFillParameters"))r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"});return Sr(r),delete r.parameters,r}async function nl(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ze(r):void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local")return["blobVersionedHashes"];return})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await ba({authorization:t.authorizationList[0]}).catch(()=>{throw new C("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:l,blockNumber:p,blockTag:m,data:h,gas:y,gasPrice:x,maxFeePerBlobGas:_,maxFeePerGas:w,maxPriorityFeePerGas:A,nonce:S,value:v,stateOverride:P,...k}=n?await di(e,{...t,parameters:i,to:s}):t;if(y&&t.gas!==y)return y;let N=(typeof p==="bigint"?H(p):void 0)||m,j=Wd(P);Sr(t);let R=e.chain?.formatters?.transactionRequest?.format,Z=(R||jr)({...eo(k,{format:R}),account:o,accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:l,data:h,gasPrice:x,maxFeePerBlobGas:_,maxFeePerGas:w,maxPriorityFeePerGas:A,nonce:S,to:s,value:v},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:j?[Z,N??e.experimental_blockTag??"latest",j]:N?[Z,N]:[Z]}))}catch(s){throw u9(s,{...t,account:o,chain:e.chain})}}async function ol(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=At({abi:r,args:o,functionName:i});try{return await J(e,nl,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:n,...a})}catch(d){let l=a.account?ze(a.account):void 0;throw $n(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:l?.address})}}Mr();rs();xn();Lc();ga();async function v9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o=e.experimental_blockTag??"latest",requireCanonical:i}){let s=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let c=e.chain.contracts.multicall3.address,d=At({abi:Zn,functionName:"getEthBalance",args:[t]}),{data:l}=await J(e,Sn,"call")({to:c,data:d,blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});return Dr({abi:Zn,functionName:"getEthBalance",args:[t],data:l||"0x"})}let a=await e.request({method:"eth_getBalance",params:[t,s]});return BigInt(a)}async function T9(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var Pce=new Map,Ace=new Map;function E9(e){let t=(o,i)=>({clear:()=>i.delete(o),get:()=>i.get(o),set:(s)=>i.set(o,s)}),r=t(e,Pce),n=t(e,Ace);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function P9(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=E9(t),o=n.response.get();if(o&&r>0){if(Date.now()-o.created.getTime()<r)return o.data}let i=n.promise.get();if(!i)i=e(),n.promise.set(i);try{let s=await i;return n.response.set({created:new Date,data:s}),s}finally{n.promise.clear()}}var Ice=(e)=>`blockNumber.${e}`;async function to(e,{cacheTime:t=e.cacheTime}={}){let r=await P9(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Ice(e.uid),cacheTime:t});return BigInt(r)}Fe();lr();function Tr(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var TP={"0x0":"reverted","0x1":"success"};function il(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map((n)=>Tr(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Yt(e.transactionIndex):null,status:e.status?TP[e.status]:null,type:e.type?hP[e.type]||e.type:null};if(e.blobGasPrice)r.blobGasPrice=BigInt(e.blobGasPrice);if(e.blobGasUsed)r.blobGasUsed=BigInt(e.blobGasUsed);return r}async function A9(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}={}){let o=r!==void 0?H(r):void 0,i=await e.request({method:"eth_getBlockReceipts",params:[t||o||n]},{dedupe:Boolean(t||o)});if(!i)throw new Fc({blockHash:t,blockNumber:r});let s=e.chain?.formatters?.transactionReceipt?.format||il;return i.map((a)=>s(a,"getBlockReceipts"))}lr();Fe();async function I9(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){let o=r!==void 0?H(r):void 0,i;if(t)i=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0});else i=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[o||n]},{dedupe:Boolean(o)});return Yt(i)}Lc();async function jc(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getCode",params:[t,s]},{dedupe:typeof n==="bigint"||r!==void 0});if(a==="0x")return;return a}la();us();xr();Kn();Yf();ir();DT();mn();Yf();Vf();Zi();var k9="/docs/contract/decodeEventLog";function qc(e){let{abi:t,data:r,strict:n,topics:o}=e,i=n??!0,[s,...a]=o;if(!s)throw new wT({docsPath:k9});let c=t.find((w)=>w.type==="event"&&s===da(dr(w)));if(!(c&&("name"in c))||c.type!=="event")throw new ST(s,{docsPath:k9});let{name:d,inputs:l}=c,p=l?.some((w)=>!(("name"in w)&&w.name)),m=p?[]:{},h=l.map((w,A)=>[w,A]).filter(([w])=>("indexed"in w)&&w.indexed),y=[];for(let w=0;w<h.length;w++){let[A,S]=h[w],v=a[w];if(!v){if(i)throw new Sc({abiItem:c,param:A});y.push([A,S]);continue}m[p?S:A.name||S]=kce({param:A,value:v})}let x=l.filter((w)=>!(("indexed"in w)&&w.indexed)),_=i?x:[...y.map(([w])=>w),...x];if(_.length>0){if(r&&r!=="0x")try{let w=Xi(_,r);if(w){let A=0;if(!i)for(let[S,v]of y)m[p?v:S.name||v]=w[A++];if(p){for(let S=0;S<l.length;S++)if(m[S]===void 0&&A<w.length)m[S]=w[A++]}else for(let S=0;S<x.length;S++)m[x[S].name]=w[A++]}}catch(w){if(i){if(w instanceof $f||w instanceof qf)throw new sa({abiItem:c,data:r,params:_,size:et(r)});throw w}}else if(i)throw new sa({abiItem:c,data:"0x",params:_,size:0})}return{eventName:d,args:Object.values(m).length>0?m:void 0}}function kce({param:e,value:t}){if(e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))return t;return(Xi([e],t)||[])[0]}function li(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,i=(()=>{if(!e.eventName)return;if(Array.isArray(e.eventName))return e.eventName;return[e.eventName]})(),s=t.filter((a)=>a.type==="event").map((a)=>({abi:a,selector:da(a)}));return n.map((a)=>{let c=typeof a.blockNumber==="string"?Tr(a):a,d=s.filter((m)=>c.topics[0]===m.selector);if(d.length===0)return null;let l,p;for(let m of d)try{l=qc({...c,abi:[m.abi],strict:!0}),p=m;break}catch{}if(!l&&!o){p=d[0];try{l=qc({data:c.data,topics:c.topics,abi:[p.abi],strict:!1})}catch{let m=p.abi.inputs?.some((h)=>!(("name"in h)&&h.name));return{...c,args:m?[]:{},eventName:p.abi.name}}}if(!l||!p)return null;if(i&&!i.includes(l.eventName))return null;if(!Rce({args:l.args,inputs:p.abi.inputs,matchArgs:r}))return null;return{...l,...c}}).filter(Boolean)}function Rce(e){let{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function o(i,s,a){try{if(i.type==="address")return wr(s,a);if(i.type==="string"||i.type==="bytes")return St(Wn(s))===a;return s===a}catch{return!1}}if(Array.isArray(t)&&Array.isArray(n))return n.every((i,s)=>{if(i===null||i===void 0)return!0;let a=r[s];if(!a)return!1;return(Array.isArray(i)?i:[i]).some((d)=>o(a,d,t[s]))});if(typeof t==="object"&&!Array.isArray(t)&&typeof n==="object"&&!Array.isArray(n))return Object.entries(n).every(([i,s])=>{if(s===null||s===void 0)return!0;let a=r.find((d)=>d.name===i);if(!a)return!1;return(Array.isArray(s)?s:[s]).some((d)=>o(a,d,t[i]))});return!1}Fe();async function sl(e,{address:t,blockHash:r,fromBlock:n,toBlock:o,event:i,events:s,args:a,strict:c}={}){let d=c??!1,l=s??(i?[i]:void 0),p=[];if(l){if(p=[l.flatMap((x)=>ui({abi:[x],eventName:x.name,args:s?void 0:a}))],i)p=p[0]}let m;if(r)m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]});else m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof n==="bigint"?H(n):n,toBlock:typeof o==="bigint"?H(o):o}]});let h=m.map((y)=>Tr(y));if(!l)return h;return li({abi:l,args:a,logs:h,strict:d})}async function rb(e,t){let{abi:r,address:n,args:o,blockHash:i,eventName:s,fromBlock:a,toBlock:c,strict:d}=t,l=s?bn({abi:r,name:s}):void 0,p=!l?r.filter((m)=>m.type==="event"):void 0;return J(e,sl,"getLogs")({address:n,args:o,blockHash:i,event:l,events:p,fromBlock:a,toBlock:c,strict:d})}ri();mn();Ji();async function R9(e,{address:t,blockNumber:r,blockTag:n="latest"}){let o=await jc(e,{address:t,...r!==void 0?{blockNumber:r}:{blockTag:n}});if(!o)return;if(et(o)!==23)return;if(!o.startsWith("0xef0100"))return;return Po(gn(o,3,23))}He();class EP extends C{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function O9(e,t){let{address:r,factory:n,factoryData:o}=t;try{let[i,s,a,c,d,l,p]=await J(e,gt,"readContract")({abi:Oce,address:r,functionName:"eip712Domain",factory:n,factoryData:o});return{domain:{name:s,version:a,chainId:Number(c),verifyingContract:d,salt:l},extensions:p,fields:i}}catch(i){let s=i;if(s.name==="ContractFunctionExecutionError"&&s.cause.name==="ContractFunctionZeroDataError")throw new EP({address:r});throw s}}var Oce=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];Fe();function C9(e){return{baseFeePerGas:e.baseFeePerGas.map((t)=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map((t)=>t.map((r)=>BigInt(r)))}}async function M9(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:o}){let i=typeof r==="bigint"?H(r):void 0,s=await e.request({method:"eth_feeHistory",params:[H(t),i||n,o]},{dedupe:Boolean(i)});return C9(s)}async function wa(e,{filter:t}){let r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]==="string")return n;let o=n.map((i)=>Tr(i));if(!("abi"in t)||!t.abi)return o;return li({abi:t.abi,logs:o,strict:r})}async function $9(e,{filter:t}){let r=t.strict??!1,o=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map((i)=>Tr(i));if(!t.abi)return o;return li({abi:t.abi,logs:o,strict:r})}Lc();xn();lr();function Cce(e){return e.map((t)=>({...t,value:BigInt(t.value)}))}function N9(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?Yt(e.nonce):void 0,storageProof:e.storageProof?Cce(e.storageProof):void 0}}async function z9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i,storageKeys:s}){let a=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),c=await e.request({method:"eth_getProof",params:[t,s,a]});return N9(c)}on();async function B9(e,{hash:t}){let r=await e.request({method:"eth_getRawTransactionByHash",params:[t]},{dedupe:!0});if(!r)throw new kc({hash:t});return r}Lc();async function L9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i,slot:s}){let a=zn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});return await e.request({method:"eth_getStorageAt",params:[t,s,a]})}on();Fe();async function al(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:i,sender:s,nonce:a}){let c=n||"latest",d=r!==void 0?H(r):void 0,l=null;if(o)l=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0});else if(t)l=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,H(i)]},{dedupe:!0});else if((d||c)&&typeof i==="number")l=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[d||c,H(i)]},{dedupe:Boolean(d)});else if(s&&typeof a==="number")l=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,H(a)]},{dedupe:!0});if(!l)throw new kc({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:i});return(e.chain?.formatters?.transaction?.format||Yd)(l,"getTransaction")}async function D9(e,{hash:t,transactionReceipt:r}){let[n,o]=await Promise.all([J(e,to,"getBlockNumber")({}),t?J(e,al,"getTransaction")({hash:t}):void 0]),i=r?.blockNumber||o?.blockNumber;if(!i)return 0n;return n-i+1n}on();async function cl(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new em({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||il)(r,"getTransactionReceipt")}Mr();ir();He();os();rs();xn();Ac();jy();async function U9(e,t){let{account:r,authorizationList:n,allowFailure:o=!0,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,requireCanonical:d,stateOverride:l}=t,p=t.contracts,m=typeof e.batch?.multicall==="object"?e.batch.multicall:{},h=t.batchSize??m.batchSize??1024,y=t.deployless??m.deployless??!1,x=(()=>{if(t.multicallAddress)return t.multicallAddress;if(y)return null;if(e.chain)return Yn({blockNumber:s,chain:e.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),_=[[]],w=0,A=0;for(let O=0;O<p.length;O++){let{abi:N,address:j,args:R,functionName:K}=p[O];try{let Z=At({abi:N,args:R,functionName:K});if(A+=(Z.length-2)/2,h>0&&A>h&&_[w].length>0)w++,A=(Z.length-2)/2,_[w]=[];_[w]=[..._[w],{allowFailure:!0,callData:Z,target:j}]}catch(Z){let re=$n(Z,{abi:N,address:j,args:R,docsPath:"/docs/contract/multicall",functionName:K,sender:r});if(!o)throw re;_[w]=[..._[w],{allowFailure:!0,callData:"0x",target:j}]}}let S=Boolean(e.batch?.multicall),v=S?_.flatMap((O)=>O.map((N)=>[N])):_,P=await Promise.allSettled(v.map((O)=>{if(S)return Mce(e,{account:r,authorizationList:n,batchSize:h,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,call:O[0],multicallAddress:x,requireCanonical:d,stateOverride:l}).then((N)=>[N]);return J(e,gt,"readContract")({...x===null?{code:zc}:{address:x},abi:Zn,account:r,args:[O],authorizationList:n,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,functionName:"aggregate3",requireCanonical:d,stateOverride:l})})),k=[];for(let O=0;O<P.length;O++){let N=P[O];if(N.status==="rejected"){if(!o)throw N.reason;for(let R=0;R<v[O].length;R++)k.push({status:"failure",error:N.reason,result:void 0});continue}let j=N.value;for(let R=0;R<j.length;R++){let{returnData:K,success:Z}=j[R],{callData:re}=v[O][R],{abi:pe,address:U,functionName:ee,args:me}=p[k.length];try{if(re==="0x")throw new vo;if(!Z)throw new ns({data:K});let z=Dr({abi:pe,args:me,data:K,functionName:ee});k.push(o?{result:z,status:"success"}:z)}catch(z){let F=$n(z,{abi:pe,address:U,args:me,docsPath:"/docs/contract/multicall",functionName:ee});if(!o)throw F;k.push({error:F,result:void 0,status:"failure"})}}}if(k.length!==p.length)throw new C("multicall results mismatch");return k}async function Mce(e,t){let{batchSize:r,call:n,multicallAddress:o,...i}=t,{wait:s=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{schedule:a}=Zd({id:Je(["multicall",e.uid,r,o,i]),wait:s,shouldSplitBatch(d){if(r===0)return!1;return d.reduce((p,{callData:m})=>p+(m.length-2)/2,0)>r},fn:(d)=>J(e,gt,"readContract")({...o===null?{code:zc}:{address:o},...i,abi:Zn,args:[d],functionName:"aggregate3"})}),[c]=await a(n);return c}WE();ir();os();ls();rs();xn();Fe();fm();ps();qy();ci();async function ul(e,t){let{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:o,returnFullTransactions:i,traceTransfers:s,validation:a}=t;try{let c=[];for(let m of o){let h=m.blockOverrides?Ly(m.blockOverrides):void 0,y=m.calls.map((_)=>{let w=_,A=w.account?ze(w.account):void 0,S=w.abi?At(w):w.data,v={...w,account:A,data:w.dataSuffix?fr([S||"0x",w.dataSuffix]):S,from:w.from??A?.address};return Sr(v),jr(v)}),x=m.stateOverrides?Wd(m.stateOverrides):void 0;c.push({blockOverrides:h,calls:y,stateOverrides:x})}let l=(typeof r==="bigint"?H(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:s,validation:a},l]})).map((m,h)=>({...Jd(m),calls:m.calls.map((y,x)=>{let{abi:_,args:w,functionName:A,to:S}=o[h].calls[x],v=y.error?.data??y.returnData,P=BigInt(y.gasUsed),k=y.logs?.map((R)=>Tr(R)),O=y.status==="0x1"?"success":"failure",N=_&&O==="success"&&v!=="0x"?Dr({abi:_,data:v,functionName:A}):null,j=(()=>{if(O==="success")return;let R;if(v==="0x")R=new vo;else if(v)R=new ns({data:v});if(!R)return;return $n(R,{abi:_??[],address:S??"0x",args:w,functionName:A??"<unknown>"})})();return{data:v,gasUsed:P,logs:k,status:O,...O==="success"?{result:N}:{error:j}}})}))}catch(c){let d=c,l=ha(d,{});if(l instanceof Oo)throw d;throw l}}Kf();Qn();/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function $ce(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function PP(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function _m(e,...t){if(!$ce(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function AP(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function F9(e,t){_m(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function j9(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function IP(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Nce=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function zce(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Bce(e){for(let t=0;t<e.length;t++)e[t]=zce(e[t]);return e}var kP=Nce?(e)=>e:Bce;function Lce(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function RP(e){if(typeof e==="string")e=Lce(e);return _m(e),e}class OP{}function q9(e){let t=(n)=>e().update(RP(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}var nb=BigInt(4294967295),H9=BigInt(32);function Dce(e,t=!1){if(t)return{h:Number(e&nb),l:Number(e>>H9&nb)};return{h:Number(e>>H9&nb)|0,l:Number(e&nb)|0}}function G9(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}=Dce(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var V9=(e,t,r)=>e<<r|t>>>32-r,Z9=(e,t,r)=>t<<r|e>>>32-r,W9=(e,t,r)=>t<<r-32|e>>>64-r,K9=(e,t,r)=>e<<r-32|t>>>64-r;var Uce=BigInt(0),wm=BigInt(1),Fce=BigInt(2),jce=BigInt(7),qce=BigInt(256),Hce=BigInt(113),Q9=[],X9=[],eD=[];for(let e=0,t=wm,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Q9.push(2*(5*n+r)),X9.push((e+1)*(e+2)/2%64);let o=Uce;for(let i=0;i<7;i++)if(t=(t<<wm^(t>>jce)*Hce)%qce,t&Fce)o^=wm<<(wm<<BigInt(i))-wm;eD.push(o)}var tD=G9(eD,!0),Gce=tD[0],Vce=tD[1],Y9=(e,t,r)=>r>32?W9(e,t,r):V9(e,t,r),J9=(e,t,r)=>r>32?K9(e,t,r):Z9(e,t,r);function Zce(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,d=r[c],l=r[c+1],p=Y9(d,l,1)^r[a],m=J9(d,l,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=p,e[s+h+1]^=m}let o=e[2],i=e[3];for(let s=0;s<24;s++){let a=X9[s],c=Y9(o,i,a),d=J9(o,i,a),l=Q9[s];o=e[l],i=e[l+1],e[l]=c,e[l+1]=d}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=Gce[n],e[1]^=Vce[n]}IP(r)}class CP extends OP{constructor(e,t,r,n=!1,o=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=o,PP(r),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=j9(this.state)}clone(){return this._cloneInto()}keccak(){kP(this.state32),Zce(this.state32,this.rounds),kP(this.state32),this.posOut=0,this.pos=0}update(e){AP(this),e=RP(e),_m(e);let{blockLen:t,state:r}=this,n=e.length;for(let o=0;o<n;){let i=Math.min(t-this.pos,n-o);for(let s=0;s<i;s++)r[this.pos++]^=e[o++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:n}=this;if(e[r]^=t,(t&128)!==0&&r===n-1)this.keccak();e[n-1]^=128,this.keccak()}writeInto(e){AP(this,!1),_m(e),this.finish();let t=this.state,{blockLen:r}=this;for(let n=0,o=e.length;n<o;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,o-n);e.set(t.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return PP(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(F9(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,IP(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new CP(t,r,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}var Wce=(e,t,r)=>q9(()=>new CP(t,e,r));var rD=(()=>Wce(1,136,32))();qd();wn();function ob(e,t={}){let{as:r=typeof e==="string"?"Hex":"Bytes"}=t,n=rD(mL(e));if(r==="Bytes")return n;return Ur(n)}wn();qd();class MP extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e)&&t!==void 0)this.delete(e),super.set(e,t);return t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=this.keys().next().value;if(r)this.delete(r)}return this}}var Kce={checksum:new MP(8192)},ib=Kce.checksum;Qn();var Jce=/^0x[a-fA-F0-9]{40}$/;function dl(e,t={}){let{strict:r=!0}=t;if(!Jce.test(e))throw new $P({address:e,cause:new oD});if(r){if(e.toLowerCase()===e)return;if(NP(e)!==e)throw new $P({address:e,cause:new iD})}}function NP(e){if(ib.has(e))return ib.get(e);dl(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=ob(hL(t),{as:"Bytes"}),n=t.split("");for(let i=0;i<40;i+=2){if(r[i>>1]>>4>=8&&n[i])n[i]=n[i].toUpperCase();if((r[i>>1]&15)>=8&&n[i+1])n[i+1]=n[i+1].toUpperCase()}let o=`0x${n.join("")}`;return ib.set(e,o),o}function sb(e,t={}){let{strict:r=!0}=t??{};try{return dl(e,{strict:r}),!0}catch{return!1}}class $P extends Pe{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class oD extends Pe{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class iD extends Pe{constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}Qn();function cb(e){let t=!0,r="",n=0,o="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a))t=!0;if(a==="(")n++;if(a===")")n--;if(!t)continue;if(n===0){if(a===" "&&["event","function","error",""].includes(o))o="";else if(o+=a,a===")"){i=!0;break}continue}if(a===" "){if(e[s-1]!==","&&r!==","&&r!==",(")r="",t=!1;continue}o+=a,r+=a}if(!i)throw new Pe("Unable to normalize signature.");return o}function ab(e,t){let r=typeof e,n=t.type;switch(n){case"address":return sb(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(n==="tuple"&&"components"in t)return Object.values(t.components).every((o,i)=>ab(Object.values(e)[i],o));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n))return r==="number"||r==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n))return r==="string"||e instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n))return Array.isArray(e)&&e.every((o)=>ab(o,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function BP(e,t,r){for(let n in e){let o=e[n],i=t[n];if(o.type==="tuple"&&i.type==="tuple"&&"components"in o&&"components"in i)return BP(o.components,i.components,r[n]);let s=[o.type,i.type];if((()=>{if(s.includes("address")&&s.includes("bytes20"))return!0;if(s.includes("address")&&s.includes("string"))return sb(r[n],{strict:!1});if(s.includes("address")&&s.includes("bytes"))return sb(r[n],{strict:!1});return!1})())return s}return}function ll(e,t={}){let{prepare:r=!0}=t,n=(()=>{if(Array.isArray(e))return xy(e);if(typeof e==="string")return xy(e);return e})();return{...n,...r?{hash:Sa(n)}:{}}}function pl(e,t,r){let{args:n=[],prepare:o=!0}=r??{},i=ZE(t,{strict:!1}),s=e.filter((d)=>{if(i){if(d.type==="function"||d.type==="error")return LP(d)===Fr(t,0,4);if(d.type==="event")return Sa(d)===t;return!1}return"name"in d&&d.name===t});if(s.length===0)throw new va({name:t});if(s.length===1)return{...s[0],...o?{hash:Sa(s[0])}:{}};let a;for(let d of s){if(!("inputs"in d))continue;if(!n||n.length===0){if(!d.inputs||d.inputs.length===0)return{...d,...o?{hash:Sa(d)}:{}};continue}if(!d.inputs)continue;if(d.inputs.length===0)continue;if(d.inputs.length!==n.length)continue;if(n.every((p,m)=>{let h="inputs"in d&&d.inputs[m];if(!h)return!1;return ab(p,h)})){if(a&&"inputs"in a&&a.inputs){let p=BP(d.inputs,a.inputs,n);if(p)throw new sD({abiItem:d,type:p[0]},{abiItem:a,type:p[1]})}a=d}}let c=(()=>{if(a)return a;let[d,...l]=s;return{...d,overloads:l}})();if(!c)throw new va({name:t});return{...c,...o?{hash:Sa(c)}:{}}}function LP(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return pl(r,n)}return e[0]})();return Fr(Sa(t),0,4)}function Xce(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,o]=e;return pl(n,o)}return e[0]})(),r=(()=>{if(typeof t==="string")return t;return Pc(t)})();return cb(r)}function Sa(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return pl(r,n)}return e[0]})();if(typeof t!=="string"&&"hash"in t&&t.hash)return t.hash;return ob(Gd(Xce(t)))}class sD extends Pe{constructor(e,t){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${cb(Pc(e.abiItem))}\`, and`,`\`${t.type}\` in \`${cb(Pc(t.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class va extends Pe{constructor({name:e,data:t,type:r="item"}){let n=(()=>{if(e)return` with name "${e}"`;if(t)return` with data "${t}"`;return""})();super(`ABI ${r}${n} not found.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}Kf();qd();Qn();wn();qd();Qn();wn();var aD=/^(.*)\[([0-9]*)\]$/,cD=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,ub=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,MBe=2n**(8n-1n)-1n,$Be=2n**(16n-1n)-1n,NBe=2n**(24n-1n)-1n,zBe=2n**(32n-1n)-1n,BBe=2n**(40n-1n)-1n,LBe=2n**(48n-1n)-1n,DBe=2n**(56n-1n)-1n,UBe=2n**(64n-1n)-1n,FBe=2n**(72n-1n)-1n,jBe=2n**(80n-1n)-1n,qBe=2n**(88n-1n)-1n,HBe=2n**(96n-1n)-1n,GBe=2n**(104n-1n)-1n,VBe=2n**(112n-1n)-1n,ZBe=2n**(120n-1n)-1n,WBe=2n**(128n-1n)-1n,KBe=2n**(136n-1n)-1n,YBe=2n**(144n-1n)-1n,JBe=2n**(152n-1n)-1n,QBe=2n**(160n-1n)-1n,XBe=2n**(168n-1n)-1n,e3e=2n**(176n-1n)-1n,t3e=2n**(184n-1n)-1n,r3e=2n**(192n-1n)-1n,n3e=2n**(200n-1n)-1n,o3e=2n**(208n-1n)-1n,i3e=2n**(216n-1n)-1n,s3e=2n**(224n-1n)-1n,a3e=2n**(232n-1n)-1n,c3e=2n**(240n-1n)-1n,u3e=2n**(248n-1n)-1n,d3e=2n**(256n-1n)-1n,l3e=-(2n**(8n-1n)),p3e=-(2n**(16n-1n)),f3e=-(2n**(24n-1n)),m3e=-(2n**(32n-1n)),h3e=-(2n**(40n-1n)),g3e=-(2n**(48n-1n)),y3e=-(2n**(56n-1n)),b3e=-(2n**(64n-1n)),x3e=-(2n**(72n-1n)),_3e=-(2n**(80n-1n)),w3e=-(2n**(88n-1n)),S3e=-(2n**(96n-1n)),v3e=-(2n**(104n-1n)),T3e=-(2n**(112n-1n)),E3e=-(2n**(120n-1n)),P3e=-(2n**(128n-1n)),A3e=-(2n**(136n-1n)),I3e=-(2n**(144n-1n)),k3e=-(2n**(152n-1n)),R3e=-(2n**(160n-1n)),O3e=-(2n**(168n-1n)),C3e=-(2n**(176n-1n)),M3e=-(2n**(184n-1n)),$3e=-(2n**(192n-1n)),N3e=-(2n**(200n-1n)),z3e=-(2n**(208n-1n)),B3e=-(2n**(216n-1n)),L3e=-(2n**(224n-1n)),D3e=-(2n**(232n-1n)),U3e=-(2n**(240n-1n)),F3e=-(2n**(248n-1n)),j3e=-(2n**(256n-1n)),q3e=2n**8n-1n,H3e=2n**16n-1n,G3e=2n**24n-1n,V3e=2n**32n-1n,Z3e=2n**40n-1n,W3e=2n**48n-1n,K3e=2n**56n-1n,Y3e=2n**64n-1n,J3e=2n**72n-1n,Q3e=2n**80n-1n,X3e=2n**88n-1n,eLe=2n**96n-1n,tLe=2n**104n-1n,rLe=2n**112n-1n,nLe=2n**120n-1n,oLe=2n**128n-1n,iLe=2n**136n-1n,sLe=2n**144n-1n,aLe=2n**152n-1n,cLe=2n**160n-1n,uLe=2n**168n-1n,dLe=2n**176n-1n,lLe=2n**184n-1n,pLe=2n**192n-1n,fLe=2n**200n-1n,mLe=2n**208n-1n,hLe=2n**216n-1n,gLe=2n**224n-1n,yLe=2n**232n-1n,bLe=2n**240n-1n,xLe=2n**248n-1n,UP=2n**256n-1n;function Hc(e,t,r){let{checksumAddress:n,staticPosition:o}=r,i=qP(t.type);if(i){let[s,a]=i;return tue(e,{...t,type:a},{checksumAddress:n,length:s,staticPosition:o})}if(t.type==="tuple")return iue(e,t,{checksumAddress:n,staticPosition:o});if(t.type==="address")return eue(e,{checksum:n});if(t.type==="bool")return rue(e);if(t.type.startsWith("bytes"))return nue(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return oue(e,t);if(t.type==="string")return sue(e,{staticPosition:o});throw new Sm(t.type)}var dD=32,FP=32;function eue(e,t={}){let{checksum:r=!1}=t,n=e.readBytes(32);return[((i)=>r?NP(i):i)(Ur(gL(n,-20))),32]}function tue(e,t,r){let{checksumAddress:n,length:o,staticPosition:i}=r;if(o===null){let c=ii(e.readBytes(FP)),d=i+c,l=d+dD;e.setPosition(d);let p=ii(e.readBytes(dD)),m=fl(t),h=0,y=[];for(let x=0;x<p;++x){e.setPosition(l+(m?x*32:h));let[_,w]=Hc(e,t,{checksumAddress:n,staticPosition:l});if(h+=w,y.push(_),w===0)e.assertReadLimit(),e._touch()}return e.setPosition(i+32),[y,32]}if(fl(t)){let c=ii(e.readBytes(FP)),d=i+c,l=[];for(let p=0;p<o;++p){e.setPosition(d+p*32);let[m]=Hc(e,t,{checksumAddress:n,staticPosition:d});l.push(m)}return e.setPosition(i+32),[l,32]}let s=0,a=[];for(let c=0;c<o;++c){let[d,l]=Hc(e,t,{checksumAddress:n,staticPosition:i+s});if(s+=l,a.push(d),l===0)e.assertReadLimit(),e._touch()}return[a,s]}function rue(e){return[bL(e.readBytes(32),{size:32}),32]}function nue(e,t,{staticPosition:r}){let[n,o]=t.type.split("bytes");if(!o){let s=ii(e.readBytes(32));e.setPosition(r+s);let a=ii(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[Ur(c),32]}return[Ur(e.readBytes(Number.parseInt(o,10),32)),32]}function oue(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?yL(o,{signed:r}):ii(o,{signed:r}),32]}function iue(e,t,r){let{checksumAddress:n,staticPosition:o}=r,i=t.components.length===0||t.components.some(({name:c})=>!c),s=i?[]:{},a=0;if(fl(t)){let c=ii(e.readBytes(FP)),d=o+c;for(let l=0;l<t.components.length;++l){let p=t.components[l];e.setPosition(d+a);let[m,h]=Hc(e,p,{checksumAddress:n,staticPosition:d});a+=h,s[i?l:p?.name]=m}return e.setPosition(o+32),[s,32]}for(let c=0;c<t.components.length;++c){let d=t.components[c],[l,p]=Hc(e,d,{checksumAddress:n,staticPosition:o});s[i?c:d?.name]=l,a+=p}return[s,a]}function sue(e,{staticPosition:t}){let r=ii(e.readBytes(32)),n=t+r;e.setPosition(n);let o=ii(e.readBytes(32));if(o===0)return e.setPosition(t+32),["",32];let i=e.readBytes(o,32),s=xL(qE(i));return e.setPosition(t+32),[s,32]}function lD({checksumAddress:e,parameters:t,values:r}){let n=[];for(let o=0;o<t.length;o++)n.push(jP({checksumAddress:e,parameter:t[o],value:r[o]}));return n}function jP({checksumAddress:e=!1,parameter:t,value:r}){let n=t,o=qP(n.type);if(o){let[i,s]=o;return cue(r,{checksumAddress:e,length:i,parameter:{...n,type:s}})}if(n.type==="tuple")return fue(r,{checksumAddress:e,parameter:n});if(n.type==="address")return aue(r,{checksum:e});if(n.type==="bool")return due(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){let i=n.type.startsWith("int"),[,,s="256"]=ub.exec(n.type)??[];return lue(r,{signed:i,size:Number(s)})}if(n.type.startsWith("bytes"))return uue(r,{type:n.type});if(n.type==="string")return pue(r);throw new Sm(n.type)}function db(e){let t=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)t+=32;else t+=sr(a)}let r=[],n=[],o=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)r.push(rr(t+o,{size:32})),n.push(a),o+=sr(a);else r.push(a)}return _r(...r,...n)}function aue(e,t){let{checksum:r=!1}=t;return dl(e,{strict:r}),{dynamic:!1,encoded:cs(e.toLowerCase())}}function cue(e,t){let{checksumAddress:r,length:n,parameter:o}=t,i=n===null;if(!Array.isArray(e))throw new GP(e);if(!i&&e.length!==n)throw new HP({expectedLength:n,givenLength:e.length,type:`${o.type}[${n}]`});let s=e.length===0&&fl(o),a=[];for(let c=0;c<e.length;c++){let d=jP({checksumAddress:r,parameter:o,value:e[c]});if(d.dynamic)s=!0;a.push(d)}if(i||s){let c=db(a);if(i){let d=rr(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?_r(d,c):d}}if(s)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:_r(...a.map(({encoded:c})=>c))}}function uue(e,{type:t}){let[,r]=t.split("bytes"),n=sr(e);if(!r){let o=e;if(n%32!==0)o=si(o,Math.ceil((e.length-2)/2/32)*32);return{dynamic:!0,encoded:_r(cs(rr(n,{size:32})),o)}}if(n!==Number.parseInt(r,10))throw new lb({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:si(e)}}function due(e){if(typeof e!=="boolean")throw new Pe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:cs(zy(e))}}function lue(e,{signed:t,size:r}){if(typeof r==="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||e<o)throw new By({max:n.toString(),min:o.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:rr(e,{size:32,signed:t})}}function pue(e){let t=Gd(e),r=Math.ceil(sr(t)/32),n=[];for(let o=0;o<r;o++)n.push(si(Fr(t,o*32,(o+1)*32)));return{dynamic:!0,encoded:_r(si(rr(sr(t),{size:32})),...n)}}function fue(e,t){let{checksumAddress:r,parameter:n}=t,o=!1,i=[];for(let s=0;s<n.components.length;s++){let a=n.components[s],c=Array.isArray(e)?s:a.name,d=jP({checksumAddress:r,parameter:a,value:e[c]});if(i.push(d),d.dynamic)o=!0}return{dynamic:o,encoded:o?db(i):_r(...i.map(({encoded:s})=>s))}}function qP(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function fl(e){let{type:t}=e;if(t==="string")return!0;if(t==="bytes")return!0;if(t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(fl);let r=qP(e.type);if(r&&fl({...e,type:r[1]}))return!0;return!1}Qn();var hue={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new mD({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new fD({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new VP({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new VP({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();if(this.positionReadCount.set(this.position,e+1),e>0)this.recursiveReadCount++}};function pD(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(hue);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}class VP extends Pe{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class fD extends Pe{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class mD extends Pe{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function ml(e,t,r={}){let{as:n="Array",checksumAddress:o=!1}=r,i=typeof t==="string"?jE(t):t,s=pD(i);if(Xn(i)===0&&e.length>0)throw new gD;if(Xn(i)&&Xn(i)<32)throw new hD({data:typeof t==="string"?t:Ur(t),parameters:e,size:Xn(i)});let a=0,c=n==="Array"?[]:{};for(let d=0;d<e.length;++d){let l=e[d];if(a<i.length)s.setPosition(a);let[p,m]=Hc(s,l,{checksumAddress:o,staticPosition:0});if(a+=m,n==="Array")c.push(p);else c[l.name??d]=p}return c}function Gc(e,t,r){let{checksumAddress:n=!1}=r??{};if(e.length!==t.length)throw new WP({expectedLength:e.length,givenLength:t.length});let o=lD({checksumAddress:n,parameters:e,values:t}),i=db(o);if(i.length===0)return"0x";return i}function ZP(e,t){if(e.length!==t.length)throw new WP({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n];r.push(ZP.encode(o,i))}return _r(...r)}(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return dl(c),cs(c.toLowerCase(),o?32:0)}if(r==="string")return Gd(n);if(r==="bytes")return n;if(r==="bool")return cs(zy(n),o?32:1);let i=r.match(ub);if(i){let[c,d,l="256"]=i,p=Number.parseInt(l,10)/8;return rr(n,{size:o?32:p,signed:d==="int"})}let s=r.match(cD);if(s){let[c,d]=s;if(Number.parseInt(d,10)!==(n.length-2)/2)throw new lb({expectedSize:Number.parseInt(d,10),value:n});return si(n,o?32:0)}let a=r.match(aD);if(a&&Array.isArray(n)){let[c,d]=a,l=[];for(let p=0;p<n.length;p++)l.push(t(d,n[p],!0));if(l.length===0)return"0x";return _r(...l)}throw new Sm(r)}e.encode=t})(ZP||(ZP={}));function pb(e){if(Array.isArray(e)&&typeof e[0]==="string")return _y(e);if(typeof e==="string")return _y(e);return e}class hD extends Pe{constructor({data:e,parameters:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${es(t)})`,`Data: ${e} (${r} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class gD extends Pe{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class HP extends Pe{constructor({expectedLength:e,givenLength:t,type:r}){super(`Array length mismatch for type \`${r}\`. Expected: \`${e}\`. Given: \`${t}\`.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class lb extends Pe{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${sr(t)}) does not match expected size (bytes${e}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class WP extends Pe{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join(`
|
|
142
|
+
`));Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class GP extends Pe{constructor(e){super(`Value \`${e}\` is not a valid array.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class Sm extends Pe{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}wn();function yD(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[i,s]=e;return[yue(i),s]}return e})(),{bytecode:n,args:o}=r;return _r(n,t.inputs?.length&&o?.length?Gc(t.inputs,o):"0x")}function bD(e){return ll(e)}function yue(e){let t=e.find((r)=>r.type==="constructor");if(!t)throw new va({name:"constructor"});return t}function xD(e,t={}){return ll(e,t)}function _D(e){return Sa(e)}wn();function wD(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[i,s,a,c]=e;return[KP(i,s),a,c]}return e})(),o=ml(t.outputs,r,n);if(o&&Object.keys(o).length===0)return;if(o&&Object.keys(o).length===1){if(Array.isArray(o))return o[0];return Object.values(o)[0]}return o}function Ta(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[d,l,p]=e;return[KP(d,l,{args:p}),p]}let[a,c]=e;return[a,c]})(),{overloads:n}=t,o=n?KP([t,...n],t.name,{args:r}):t,i=_ue(o),s=r.length>0?Gc(o.inputs,r):void 0;return s?_r(i,s):i}function Vc(e,t={}){return ll(e,t)}function KP(e,t,r){let n=pl(e,t,r);if(n.type!=="function")throw new va({name:t,type:"function"});return n}function _ue(e){return LP(e)}var fb="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",mb="0x0000000000000000000000000000000000000000";He();os();ls();Lf();lr();ga();var Sue="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033",ID="0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063fd00430c1461002d575b5f5ffd5b6100476004803603810190610042919061012b565b610049565b005b80825f375f5f825f865afa610060573d5f5f3e3d5ffd5b3d5f5f3e3d5ff35b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61009982610070565b9050919050565b6100a98161008f565b81146100b3575f5ffd5b50565b5f813590506100c4816100a0565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f8401126100eb576100ea6100ca565b5b8235905067ffffffffffffffff811115610108576101076100ce565b5b602083019150836001820283011115610124576101236100d2565b5b9250929050565b5f5f5f6040848603121561014257610141610068565b5b5f61014f868287016100b6565b935050602084013567ffffffffffffffff8111156101705761016f61006c565b5b61017c868287016100d6565b9250925050925092509256fea2646970667358221220635ed99185cacf3f2acba6921f23687c969cec2bbaf5f9ad599f507e6e105e6964736f6c63430008230033",vue=0x00000000000000000000000000000000deadbeefn,Tue=_D(xD("event Transfer(address indexed from, address indexed to, uint256 value)")),SD=Vc("function balanceOf(address) returns (uint256)"),vD=Vc("function decimals() returns (uint256)"),TD=Vc("function tokenURI(uint256) returns (string)"),ED=Vc("function symbol() returns (string)"),Eue=Vc("function query(address target, bytes data)");async function kD(e,t){let{blockNumber:r,blockTag:n,calls:o,stateOverrides:i,traceAssetChanges:s,traceTransfers:a,validation:c}=t,d=t.account?ze(t.account):void 0;if(s&&!d)throw new C("`account` is required when `traceAssetChanges` is true");let l=d?yD(bD("constructor(bytes, bytes)"),{bytecode:Dy,args:[Sue,Ta(Vc("function getBalance(address)"),[d.address])]}):void 0,p=n??e.experimental_blockTag??"latest",m=r;if(s&&typeof m!=="bigint"&&p!=="earliest"&&p!=="pending")if(p==="latest")m=await to(e,{cacheTime:0});else{let te=await ar(e,{blockTag:p});if(typeof te.number!=="bigint")throw new C(`Block tag \`${p}\` did not resolve to a number.`);m=te.number}let h=typeof m==="bigint"?{blockNumber:m}:{blockTag:p},y=s?await ul(e,{...h,blocks:[{calls:o.map((te)=>({...te,from:d.address})),stateOverrides:i}],traceTransfers:a,validation:c}):void 0,x=y?[...new Set([...Pue(y[0].calls.flatMap((te)=>te.logs??[]),d.address),...t.calls.map((te)=>te.to?.toLowerCase())])].filter((te)=>Boolean(te)&&te!==fb&&te!==mb):[],_=Aue([...d?[d.address]:[],...x,...i?.map(({address:te})=>te)??[]]),w=[{address:_,code:ID}],[A,S]=await Promise.all([s?Promise.all([AD(e,{account:d.address,...h,data:l,stateOverride:i}),...x.map((te)=>AD(e,{account:d.address,address:te,...h,data:Ta(SD,[d.address]),staticCallAddress:_,stateOverride:i}))]):[],ul(e,{...h,blocks:[{calls:[...o,{to:mb}].map((te)=>({...te,from:d?.address})),stateOverrides:i},...s?[{calls:[{data:l}]},{calls:x.map((te)=>({to:_,data:Tm(te,Ta(SD,[d.address]))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Tm(te,Ta(vD))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Tm(te,Ta(TD,[0n]))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Tm(te,Ta(ED))})),stateOverrides:w}]:[]],traceTransfers:a,validation:c})]),v=S[0],[P,k,O,N,j]=s?S.slice(1):[],{calls:R,...K}=v,Z=R.slice(0,-1),re=A.map((te)=>PD(te)?er(te.data):null),pe=P?.calls??[],U=k?.calls??[],me=[...pe,...U].map((te)=>PD(te)?er(te.data):null),z=(O?.calls??[]).map((te)=>YP(te,vD)),F=(j?.calls??[]).map((te)=>YP(te,ED)),Y=(N?.calls??[]).map((te)=>YP(te,TD)),we=[];for(let[te,$e]of me.entries()){let Ee=re[te],Ae=A[te],tt=typeof Ee==="bigint"?Ee:te>0&&Ae?.status==="success"&&Ae.data==="0x"?0n:null;if(typeof $e!=="bigint")continue;if(typeof tt!=="bigint")continue;let yt=z[te-1],ft=F[te-1],q=Y[te-1],ne=(()=>{if(te===0)return{address:fb,decimals:18,symbol:"ETH"};return{address:x[te-1],decimals:q||yt?Number(yt??1):void 0,symbol:ft??void 0}})();we.push({token:ne,value:{pre:tt,post:$e,diff:$e-tt}})}return{assetChanges:we,block:K,results:Z}}function Tm(e,t){return Ta(Eue,[e,t])}function Pue(e,t){let r=ti(t.toLowerCase(),{size:32});return e.filter((n)=>{if(n.topics[0]?.toLowerCase()!==Tue)return!1;if(n.address.toLowerCase()===fb)return!1;return n.topics[1]?.toLowerCase()===r||n.topics[2]?.toLowerCase()===r}).map((n)=>n.address.toLowerCase())}function PD(e){return e.status==="success"&&/^0x[\da-f]{64}$/i.test(e.data)}function YP(e,t){if(e.status==="failure"||e.data==="0x")return null;try{return wD(t,e.data)}catch{return null}}async function AD(e,t){let{account:r,address:n,blockNumber:o,blockTag:i,data:s,staticCallAddress:a,stateOverride:c}=t;try{return{data:(await Sn({...e,ccipRead:!1},{account:n?mb:r,data:n?Tm(n,s):s,stateOverride:n&&a?[...c??[],{address:a,code:ID}]:c,...n?{to:a}:{},...typeof o==="bigint"?{blockNumber:o}:{blockTag:i}})).data??"0x",status:"success"}}catch(d){if(!(d instanceof Oc)||!(d.cause instanceof ai))throw d;return{data:"0x",status:"failure"}}}function Aue(e){let t=new Set(e.map((n)=>n.toLowerCase())),r=vue;while(t.has(`0x${r.toString(16).padStart(40,"0")}`))r++;return`0x${r.toString(16).padStart(40,"0")}`}rs();xn();ga();async function hl(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account?ze(a.account):e.account,d=At({abi:r,args:o,functionName:i});try{let{data:l}=await J(e,Sn,"call")({batch:!1,data:`${d}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),p=Dr({abi:r,args:o,functionName:i,data:l||"0x"}),m=r.filter((h)=>("name"in h)&&h.name===t.functionName);return{result:p,request:{abi:m,address:n,args:o,dataSuffix:s,functionName:i,...a,account:c}}}catch(l){throw $n(l,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:i,sender:c?.address})}}async function Ea(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}Qn();wn();var RD="0x6492649264926492649264926492649264926492649264926492649264926492";function Iue(e){if(Fr(e,-32)!==RD)throw new OD(e)}function kue(e){let{data:t,signature:r,to:n}=e;return _r(Gc(pb("address, bytes, bytes"),[n,t,r]),RD)}function Rue(e){try{return Iue(e),!0}catch{return!1}}class OD extends Pe{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}Qn();wn();function JP(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new hb({signature:e});if(typeof e.s>"u")throw new hb({signature:e});if(r&&typeof e.yParity>"u")throw new hb({signature:e});if(e.r<0n||e.r>UP)throw new BD({value:e.r});if(e.s<0n||e.s>UP)throw new LD({value:e.s});if(typeof e.yParity==="number"&&e.yParity!==0&&e.yParity!==1)throw new gb({value:e.yParity})}function Oue(e){return MD(Ur(e))}function MD(e){if(e.length!==130&&e.length!==132)throw new zD({signature:e});let t=BigInt(Fr(e,0,32)),r=BigInt(Fr(e,32,64)),n=(()=>{let o=Number(`0x${e.slice(130)}`);if(Number.isNaN(o))return;try{return QP(o)}catch{throw new gb({value:o})}})();if(typeof n>"u")return{r:t,s:r};return{r:t,s:r,yParity:n}}function $D(e){if(typeof e.r>"u")return;if(typeof e.s>"u")return;return ND(e)}function ND(e){let t=(()=>{if(typeof e==="string")return MD(e);if(e instanceof Uint8Array)return Oue(e);if(typeof e.r==="string")return Mue(e);if(e.v)return Cue(e);return{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}}})();return JP(t),t}function Cue(e){return{r:e.r,s:e.s,yParity:QP(e.v)}}function Mue(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r==="number"&&typeof n!=="number")n=QP(r);if(typeof n!=="number")throw new gb({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function QP(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new DD({value:e})}class zD extends Pe{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${sr(wL(e))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class hb extends Pe{constructor({signature:e}){super(`Signature \`${$y(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class BD extends Pe{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class LD extends Pe{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class gb extends Pe{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class DD extends Pe{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function FD(e,t={}){if(typeof e.chainId==="string")return $ue(e);return{...e,...t.signature}}function $ue(e){let{address:t,chainId:r,nonce:n}=e,o=$D(e);return{address:t,chainId:Number(r),nonce:BigInt(n),...o}}Qn();wn();var zue="0x8010801080108010801080108010801080108010801080108010801080108010",Bue=pb("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function jD(e){if(typeof e==="string"){if(Fr(e,-32)!==zue)throw new qD(e)}else JP(e.authorization)}function Lue(e){jD(e);let t=Ny(Fr(e,-64,-32)),r=Fr(e,-t-64,-64),n=Fr(e,0,-t-64),[o,i,s]=ml(Bue,r);return{authorization:FD({address:o.delegation,chainId:Number(o.chainId),nonce:o.nonce,yParity:o.yParity,r:o.r,s:o.s}),signature:n,...s&&s!=="0x"?{data:s,to:i}:{}}}function Due(e){try{return jD(e),!0}catch{return!1}}class qD extends Pe{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}Mr();os();Uy();xn();ri();us();ri();us();async function GD({address:e,authorization:t,signature:r}){return wr(Po(e),await ba({authorization:t,signature:r}))}lr();Fe();hm();lr();xr();function yb({r:e,s:t,to:r="hex",v:n,yParity:o}){let i=(()=>{if(o===0||o===1)return o;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw Error("Invalid `v` or `yParity` value")})(),s=`0x${new hs.Signature(er(e),er(t)).toCompactHex()}${i===0?"1b":"1c"}`;if(r==="hex")return s;return pr(s)}ga();async function Aa(e,t){let{address:r,chain:n=e.chain,hash:o,erc6492VerifierAddress:i=t.universalSignatureVerifierAddress??n?.contracts?.erc6492Verifier?.address,multicallAddress:s=t.multicallAddress??n?.contracts?.multicall3?.address,mode:a="auto"}=t;if(n?.verifyHash)return await n.verifyHash(e,t);let c=(()=>{let d=t.signature;if(Kt(d))return d;if(typeof d==="object"&&"r"in d&&"s"in d)return yb(d);return mt(d)})();try{if(a==="eoa")try{if(wr(Po(r),await gm({hash:o,signature:c})))return!0}catch{}if(Due(c))return await Uue(e,{...t,multicallAddress:s,signature:c});return await Fue(e,{...t,verifierAddress:i,signature:c})}catch(d){if(a!=="eoa")try{if(wr(Po(r),await gm({hash:o,signature:c})))return!0}catch{}if(d instanceof Pa)return!1;throw d}}async function Uue(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:i,hash:s,multicallAddress:a,requireCanonical:c}=t,{authorization:d,data:l,signature:p,to:m}=Lue(t.signature);if(await jc(e,{address:r,blockHash:n,blockNumber:o,blockTag:i,requireCanonical:c})===Qt(["0xef0100",d.address]))return await jue(e,{...t,signature:p});let y={address:d.address,chainId:Number(d.chainId),nonce:Number(d.nonce),r:H(d.r,{size:32}),s:H(d.s,{size:32}),yParity:d.yParity};if(!await GD({address:r,authorization:y}))throw new Pa;let _=await J(e,gt,"readContract")({...a?{address:a}:{code:zc},authorizationList:[y],abi:Zn,blockHash:n,blockNumber:o,blockTag:"pending",functionName:"aggregate3",requireCanonical:c,args:[[...l?[{allowFailure:!0,target:m??r,callData:l}]:[],{allowFailure:!0,target:r,callData:At({abi:pT,functionName:"isValidSignature",args:[s,p]})}]]});if(_[_.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new Pa}async function Fue(e,t){let{address:r,factory:n,factoryData:o,hash:i,signature:s,verifierAddress:a,...c}=t,d=await(async()=>{if(!n&&!o)return s;if(Rue(s))return s;return kue({data:o,signature:s,to:n})})(),l=a?{to:a,data:At({abi:Cf,functionName:"isValidSig",args:[r,i,d]}),...c}:{data:Bc({abi:Cf,args:[r,i,d],bytecode:AL}),...c},{data:p}=await J(e,Sn,"call")(l).catch((m)=>{if(m instanceof Oc)throw new Pa;throw m});if(OT(p??"0x0"))return!0;throw new Pa}async function jue(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:i,hash:s,requireCanonical:a,signature:c}=t;if((await J(e,gt,"readContract")({address:r,abi:pT,args:[s,c],blockHash:n,blockNumber:o,blockTag:i,functionName:"isValidSignature",requireCanonical:a}).catch((l)=>{if(l instanceof tm)throw new Pa;throw l})).startsWith("0x1626ba7e"))return!0;throw new Pa}class Pa extends Error{}Kn();var VD=`\x19Ethereum Signed Message:
|
|
143
143
|
`;mn();Fe();function ZD(e){let t=(()=>{if(typeof e==="string")return aa(e);if(typeof e.raw==="string")return e.raw;return mt(e.raw)})(),r=aa(`${VD}${et(t)}`);return fr([r,t])}function gl(e,t){return St(ZD(e),t)}async function WD(e,{address:t,message:r,factory:n,factoryData:o,signature:i,...s}){let a=gl(r);return J(e,Aa,"verifyHash")({address:t,factory:n,factoryData:o,hash:a,signature:i,...s})}Qi();Fe();Kn();ir();ei();He();class XP extends C{constructor({domain:e}){super(`Invalid domain "${Je(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class eA extends C{constructor({primaryType:e,types:t}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(t))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class tA extends C{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}class rA extends C{constructor({type:e}){let t=e.replace(/^(u?int)/,"$&256");super(`Type "${e}" is not a valid EIP-712 type.`,{metaMessages:[`Use "${t}" instead.`],name:"InvalidTypedDataTypeError"})}}Cn();mn();Fe();FT();function KD(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(c,d)=>{let l={...d};for(let p of c){let{name:m,type:h}=p;if(h==="address")l[m]=l[m].toLowerCase()}return l},s=(()=>{if(!o.EIP712Domain)return{};if(!t)return{};return i(o.EIP712Domain,t)})(),a=(()=>{if(n==="EIP712Domain")return;return i(o[n],r)})();return Je({domain:s,message:a,primaryType:n,types:o})}function bb(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(s,a)=>{for(let c of s){let{name:d,type:l}=c,p=a[d],m=l.replace(/(\[[0-9]*\])+$/,"");if(m==="int"||m==="uint")throw new rA({type:l});let h=l.match(dy);if(h&&(typeof p==="number"||typeof p==="bigint")){let[_,w,A]=h;H(p,{signed:w==="int",size:Number.parseInt(A,10)/8})}if(l==="address"&&typeof p==="string"&&!ht(p))throw new Ft({address:p});let y=l.match(KB);if(y){let[_,w]=y;if(w&&et(p)!==Number.parseInt(w,10))throw new ET({expectedSize:Number.parseInt(w,10),givenSize:et(p)})}let x=o[l];if(x)que(l),i(x,p)}};if(o.EIP712Domain&&t){if(typeof t!=="object")throw new XP({domain:t});i(o.EIP712Domain,t)}if(n!=="EIP712Domain")if(o[n])i(o[n],r);else throw new eA({primaryType:n,types:o})}function xb({domain:e}){return[typeof e?.name==="string"&&{name:"name",type:"string"},e?.version&&{name:"version",type:"string"},(typeof e?.chainId==="number"||typeof e?.chainId==="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function que(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new tA({type:e})}function _b(e){let{domain:t={},message:r,primaryType:n}=e,o={EIP712Domain:xb({domain:t}),...e.types};bb({domain:t,message:r,primaryType:n,types:o});let i=["0x1901"];if(t)i.push(Hue({domain:t,types:o}));if(n!=="EIP712Domain")i.push(YD({data:r,primaryType:n,types:o}));return St(fr(i))}function Hue({domain:e,types:t}){return YD({data:e,primaryType:"EIP712Domain",types:t})}function YD({data:e,primaryType:t,types:r}){let n=JD({data:e,primaryType:t,types:r});return St(n)}function JD({data:e,primaryType:t,types:r}){let n=[{type:"bytes32"}],o=[Gue({primaryType:t,types:r})];for(let i of r[t]){let[s,a]=XD({types:r,name:i.name,type:i.type,value:e[i.name]});n.push(s),o.push(a)}return nn(n,o)}function Gue({primaryType:e,types:t}){let r=Jt(Vue({primaryType:e,types:t}));return St(r)}function Vue({primaryType:e,types:t}){let r="",n=QD({primaryType:e,types:t});n.delete(e);let o=[e,...Array.from(n).sort()];for(let i of o)r+=`${i}(${t[i].map(({name:s,type:a})=>`${a} ${s}`).join(",")})`;return r}function QD({primaryType:e,types:t},r=new Set){let o=e.match(/^\w*/u)?.[0];if(r.has(o)||t[o]===void 0)return r;r.add(o);for(let i of t[o])QD({primaryType:i.type,types:t},r);return r}function XD({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},St(JD({data:n,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},St(n)];if(r==="string")return[{type:"bytes32"},St(Jt(n))];if(r.lastIndexOf("]")===r.length-1){let o=r.slice(0,r.lastIndexOf("[")),i=n.map((s)=>XD({name:t,type:o,types:e,value:s}));return[{type:"bytes32"},St(nn(i.map(([s])=>s),i.map(([,s])=>s)))]}return[{type:r},n]}async function eU(e,t){let{address:r,factory:n,factoryData:o,signature:i,message:s,primaryType:a,types:c,domain:d,...l}=t,p=_b({message:s,primaryType:a,types:c,domain:d});return J(e,Aa,"verifyHash")({address:r,factory:n,factoryData:o,hash:p,signature:i,...l})}on();var wb=new Map,nA=new Map,Zue=0;function Er(e,t,r){let n=++Zue,o=()=>wb.get(e)||[],i=()=>{let p=o().filter((m)=>m.id!==n);if(p.length===0){wb.delete(e),nA.delete(e);return}wb.set(e,p)},s=()=>{let l=o();if(!l.some((m)=>m.id===n))return;let p=nA.get(e);if(l.length===1&&p){let m=p();if(m instanceof Promise)m.catch(()=>{})}i()},a=o();if(wb.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return s;let c={};for(let l in t)c[l]=(...p)=>{let m=o();if(m.length===0)return;for(let h of m)h.fns[l]?.(...p)};let d=r(c);if(typeof d==="function")nA.set(e,d);return s}async function Em(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n(Nr(t));return}let o=()=>t?.removeEventListener("abort",s),i=setTimeout(()=>{o(),r()},e),s=()=>{clearTimeout(i),o(),n(Nr(t))};t?.addEventListener("abort",s,{once:!0})})}function Zc(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:o}={}){return new Promise((i,s)=>{let a=async({count:c=0}={})=>{if(o?.aborted){s(Nr(o));return}let d=async({error:l})=>{let p=typeof t==="function"?t({count:c,error:l}):t;if(p)try{await Em(p,{signal:o})}catch(m){s(m);return}return a({count:c+1})};try{let l=await e();i(l)}catch(l){if(o?.aborted){s(Nr(o));return}if(_n(l)){s(l);return}if(c<r&&await n({count:c,error:l}))return d({error:l});s(l)}};a().catch(s)})}lr();function ro(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let o=!0,i=()=>o=!1;return(async()=>{let a;if(t)a=await e({unpoll:i});let c=await r?.(a)??n;await Em(c);let d=async()=>{if(!o)return;await e({unpoll:i}),await Em(n),d()};d()})(),i}function Sb(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:o,poll:i,pollingInterval:s=e.pollingInterval}){let a=(()=>{if(typeof i<"u")return i;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),c;return a?(()=>{let p=Je(["watchBlockNumber",e.uid,t,r,s]);return Er(p,{onBlockNumber:n,onError:o},(m)=>ro(async()=>{try{let h=await J(e,to,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(h===c)return;if(h-c>1&&r)for(let y=c+1n;y<h;y++)m.onBlockNumber(y,c),c=y}if(c===void 0||h>c)m.onBlockNumber(h,c),c=h}catch(h){m.onError?.(h)}},{emitOnBegin:t,interval:s}))})():(()=>{let p=Je(["watchBlockNumber",e.uid,t,r]);return Er(p,{onBlockNumber:n,onError:o},(m)=>{let h=!0,y=()=>h=!1;return(async()=>{try{let x=(()=>{if(e.transport.type==="fallback"){let w=e.transport.transports.find((A)=>A.config.type==="webSocket"||A.config.type==="ipc");if(!w)return e.transport;return w.value}return e.transport})(),{unsubscribe:_}=await x.subscribe({params:["newHeads"],onData(w){if(!h)return;let A=er(w.result?.number);m.onBlockNumber(A,c),c=A},onError(w){m.onError?.(w)}});if(y=_,!h)y()}catch(x){o?.(x)}})(),()=>y()})})()}async function vb(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:o,onReplaced:i,retryCount:s=6,retryDelay:a=({count:P})=>~~(1<<P)*200,timeout:c=180000}=t,d=Je(["waitForTransactionReceipt",e.uid,o]),l=(()=>{if(t.pollingInterval)return t.pollingInterval;if(e.chain?.experimental_preconfirmationTime)return e.chain.experimental_preconfirmationTime;return e.pollingInterval})(),p,m,h,y=!1,x,_,{promise:w,resolve:A,reject:S}=Vd(),v=c?setTimeout(()=>{_?.(),x?.(),S(new PE({hash:o}))},c):void 0;return x=Er(d,{onReplaced:i,resolve:A,reject:S},async(P)=>{if(h=await J(e,cl,"getTransactionReceipt")({hash:o}).catch(()=>{return}),h&&n<=1){clearTimeout(v),P.resolve(h),x?.();return}_=J(e,Sb,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:l,async onBlockNumber(k){let O=(j)=>{clearTimeout(v),_?.(),j(),x?.()},N=k;if(y)return;try{if(h){if(n>1&&(!h.blockNumber||N-h.blockNumber+1n<n))return;O(()=>P.resolve(h));return}if(r&&!p)y=!0,await Zc(async()=>{if(p=await J(e,al,"getTransaction")({hash:o}),p.blockNumber)N=p.blockNumber},{delay:a,retryCount:s}),y=!1;if(h=await J(e,cl,"getTransactionReceipt")({hash:o}),n>1&&(!h.blockNumber||N-h.blockNumber+1n<n))return;O(()=>P.resolve(h))}catch(j){if(j instanceof kc||j instanceof em){if(!p){y=!1;return}try{m=p,y=!0;let R=await Zc(()=>J(e,ar,"getBlock")({blockNumber:N,includeTransactions:!0}),{delay:a,retryCount:s,shouldRetry:({error:re})=>re instanceof Fc});y=!1;let K=R.transactions.find(({from:re,nonce:pe})=>re===m.from&&pe===m.nonce);if(!K)return;if(h=await J(e,cl,"getTransactionReceipt")({hash:K.hash}),n>1&&(!h.blockNumber||N-h.blockNumber+1n<n))return;let Z="replaced";if(K.to===m.to&&K.value===m.value&&K.input===m.input)Z="repriced";else if(K.from===K.to&&K.value===0n)Z="cancelled";O(()=>{P.onReplaced?.({reason:Z,replacedTransaction:m,transaction:K,transactionReceipt:h}),P.resolve(h)})}catch(R){O(()=>P.reject(R))}}else O(()=>P.reject(j))}}})}),w}var Wue=["size","totalDifficulty","transactions","uncles","withdrawals"];function tU(e,{onBlockHeader:t,onError:r}){let n,o=Je(["watchBlockHeaders",e.uid]);return Er(o,{onBlockHeader:t,onError:r},(i)=>{let s=!0,a=!1,c=()=>s=!1;return(async()=>{try{let d=(()=>{if(e.transport.type==="fallback"){let p=e.transport.transports.find((m)=>m.config.type==="webSocket"||m.config.type==="ipc");if(!p)return e.transport;return p.value}return e.transport})(),{unsubscribe:l}=await d.subscribe({params:["newHeads"],onData(p){if(!s)return;let m=(e.chain?.formatters?.block?.format||Jd)(p.result,"watchBlockHeaders");for(let h of Wue)delete m[h];i.onBlockHeader(m,n),n=m},onError(p){if(a)i.onError?.(p)}});if(a=!0,c=l,!s)c()}catch(d){i.onError?.(d)}})(),()=>c()})}function rU(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:o,onError:i,includeTransactions:s,poll:a,pollingInterval:c=e.pollingInterval}){let d=(()=>{if(typeof a<"u")return a;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),l=s??!1,p;return d?(()=>{let y=Je(["watchBlocks",e.uid,t,r,n,l,c]);return Er(y,{onBlock:o,onError:i},(x)=>ro(async()=>{try{let _=await J(e,ar,"getBlock")({blockTag:t,includeTransactions:l});if(_.number!==null&&p?.number!=null){if(_.number===p.number)return;if(_.number-p.number>1&&r)for(let w=p?.number+1n;w<_.number;w++){let A=await J(e,ar,"getBlock")({blockNumber:w,includeTransactions:l});x.onBlock(A,p),p=A}}if(p?.number==null||t==="pending"&&_?.number==null||_.number!==null&&_.number>p.number)x.onBlock(_,p),p=_}catch(_){x.onError?.(_)}},{emitOnBegin:n,interval:c}))})():(()=>{let y=!0,x=!0,_=()=>y=!1;return(async()=>{try{if(n)J(e,ar,"getBlock")({blockTag:t,includeTransactions:l}).then((S)=>{if(!y)return;if(!x)return;o(S,void 0),x=!1}).catch(i);let w=(()=>{if(e.transport.type==="fallback"){let S=e.transport.transports.find((v)=>v.config.type==="webSocket"||v.config.type==="ipc");if(!S)return e.transport;return S.value}return e.transport})(),{unsubscribe:A}=await w.subscribe({params:["newHeads"],async onData(S){if(!y)return;let v=await J(e,ar,"getBlock")({blockNumber:S.result?.number,includeTransactions:l}).catch(()=>{});if(!y)return;o(v,p),x=!1,p=v},onError(S){i?.(S)}});if(_=A,!y)_()}catch(w){i?.(w)}})(),()=>_()})()}ir();Fd();function nU(e,t){let{abi:r,address:n,args:o,batch:i=!0,eventName:s,fromBlock:a,onError:c,onLogs:d,poll:l,pollingInterval:p=e.pollingInterval,strict:m}=t;return(()=>{if(typeof l<"u")return l;if(typeof a==="bigint")return!0;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})()?(()=>{let _=m??!1,w=Je(["watchContractEvent",n,o,i,e.uid,s,p,_,a]);return Er(w,{onLogs:d,onError:c},(A)=>{let S;if(a!==void 0)S=a-1n;let v,P=!1,k=ro(async()=>{if(!P){try{v=await J(e,Vy,"createContractEventFilter")({abi:r,address:n,args:o,eventName:s,strict:_,fromBlock:a})}catch{}P=!0;return}try{let O;if(v)O=await J(e,wa,"getFilterChanges")({filter:v});else{let N=await J(e,to,"getBlockNumber")({});if(S&&S<N)O=await J(e,rb,"getContractEvents")({abi:r,address:n,args:o,eventName:s,fromBlock:S+1n,toBlock:N,strict:_});else O=[];S=N}if(O.length===0)return;if(i)A.onLogs(O);else for(let N of O)A.onLogs([N])}catch(O){if(v&&O instanceof Jn)P=!1;A.onError?.(O)}},{emitOnBegin:!0,interval:p});return async()=>{if(v)await J(e,Ea,"uninstallFilter")({filter:v});k()}})})():(()=>{let _=m??!1,w=Je(["watchContractEvent",n,o,i,e.uid,s,p,_]),A=!0,S=()=>A=!1;return Er(w,{onLogs:d,onError:c},(v)=>((async()=>{try{let P=(()=>{if(e.transport.type==="fallback"){let N=e.transport.transports.find((j)=>j.config.type==="webSocket"||j.config.type==="ipc");if(!N)return e.transport;return N.value}return e.transport})(),k=s?ui({abi:r,eventName:s,args:o}):[],{unsubscribe:O}=await P.subscribe({params:["logs",{address:n,topics:k}],onData(N){if(!A)return;let j=N.result;try{let{eventName:R,args:K}=qc({abi:r,data:j.data,topics:j.topics,strict:m}),Z=Tr(j,{args:K,eventName:R});v.onLogs([Z])}catch(R){let K,Z;if(R instanceof sa||R instanceof Sc){if(m)return;K=R.abiItem.name,Z=R.abiItem.inputs?.some((pe)=>!(("name"in pe)&&pe.name))}let re=Tr(j,{args:Z?[]:{},eventName:K});v.onLogs([re])}},onError(N){v.onError?.(N)}});if(S=O,!A)S()}catch(P){c?.(P)}})(),()=>S()))})()}ir();Fd();function oU(e,{address:t,args:r,batch:n=!0,event:o,events:i,fromBlock:s,onError:a,onLogs:c,poll:d,pollingInterval:l=e.pollingInterval,strict:p}){let m=(()=>{if(typeof d<"u")return d;if(typeof s==="bigint")return!0;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),h=p??!1;return m?(()=>{let _=Je(["watchEvent",t,r,n,e.uid,o,l,s]);return Er(_,{onLogs:c,onError:a},(w)=>{let A;if(s!==void 0)A=s-1n;let S,v=!1,P=ro(async()=>{if(!v){try{S=await J(e,Zy,"createEventFilter")({address:t,args:r,event:o,events:i,strict:h,fromBlock:s})}catch{}v=!0;return}try{let k;if(S)k=await J(e,wa,"getFilterChanges")({filter:S});else{let O=await J(e,to,"getBlockNumber")({});if(A&&A!==O)k=await J(e,sl,"getLogs")({address:t,args:r,event:o,events:i,fromBlock:A+1n,toBlock:O});else k=[];A=O}if(k.length===0)return;if(n)w.onLogs(k);else for(let O of k)w.onLogs([O])}catch(k){if(S&&k instanceof Jn)v=!1;w.onError?.(k)}},{emitOnBegin:!0,interval:l});return async()=>{if(S)await J(e,Ea,"uninstallFilter")({filter:S});P()}})})():(()=>{let _=!0,w=()=>_=!1;return(async()=>{try{let A=(()=>{if(e.transport.type==="fallback"){let k=e.transport.transports.find((O)=>O.config.type==="webSocket"||O.config.type==="ipc");if(!k)return e.transport;return k.value}return e.transport})(),S=i??(o?[o]:void 0),v=[];if(S){if(v=[S.flatMap((O)=>ui({abi:[O],eventName:O.name,args:r}))],o)v=v[0]}let{unsubscribe:P}=await A.subscribe({params:["logs",{address:t,topics:v}],onData(k){if(!_)return;let O=k.result;try{let{eventName:N,args:j}=qc({abi:S??[],data:O.data,topics:O.topics,strict:h}),R=Tr(O,{args:j,eventName:N});c([R])}catch(N){let j,R;if(N instanceof sa||N instanceof Sc){if(p)return;j=N.abiItem.name,R=N.abiItem.inputs?.some((Z)=>!(("name"in Z)&&Z.name))}let K=Tr(O,{args:R?[]:{},eventName:j});c([K])}},onError(k){a?.(k)}});if(w=P,!_)w()}catch(A){a?.(A)}})(),()=>w()})()}function iU(e,{batch:t=!0,onError:r,onTransactions:n,poll:o,pollingInterval:i=e.pollingInterval}){return(typeof o<"u"?o:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let d=Je(["watchPendingTransactions",e.uid,t,i]);return Er(d,{onTransactions:n,onError:r},(l)=>{let p,m=ro(async()=>{try{if(!p)try{p=await J(e,Wy,"createPendingTransactionFilter")({});return}catch(y){throw m(),y}let h=await J(e,wa,"getFilterChanges")({filter:p});if(h.length===0)return;if(t)l.onTransactions(h);else for(let y of h)l.onTransactions([y])}catch(h){l.onError?.(h)}},{emitOnBegin:!0,interval:i});return async()=>{if(p)await J(e,Ea,"uninstallFilter")({filter:p});m()}})})():(()=>{let d=!0,l=()=>d=!1;return(async()=>{try{let{unsubscribe:p}=await e.transport.subscribe({params:["newPendingTransactions"],onData(m){if(!d)return;let h=m.result;n([h])},onError(m){r?.(m)}});if(l=p,!d)l()}catch(p){r?.(p)}})(),()=>l()})()}var Kue=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function Yue(e){if(!Kue.test(e))return!1;return!Number.isNaN(new Date(e).getTime())}function oA(e){if(!Yue(e))return new Date(Number.NaN);return new Date(e)}function sU(e){let{scheme:t,statement:r,...n}=e.match(Jue)?.groups??{},{chainId:o,expirationTime:i,issuedAt:s,notBefore:a,requestId:c,...d}=e.match(Que)?.groups??{},l=e.split("Resources:")[1]?.split(`
|
|
144
144
|
- `).slice(1);return{...n,...d,...o?{chainId:Number(o)}:{},...i?{expirationTime:oA(i)}:{},...s?{issuedAt:oA(s)}:{},...a?{notBefore:oA(a)}:{},...c?{requestId:c}:{},...l?{resources:l}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var Jue=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,Que=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;Cn();us();function aU(e){let{address:t,domain:r,message:n,nonce:o,scheme:i,time:s=new Date}=e;if(r&&n.domain!==r)return!1;if(o&&n.nonce!==o)return!1;if(i&&n.scheme!==i)return!1;if(Number.isNaN(s.getTime()))return!1;if(n.expirationTime){if(Number.isNaN(n.expirationTime.getTime()))return!1;if(s>=n.expirationTime)return!1}if(n.notBefore){if(Number.isNaN(n.notBefore.getTime()))return!1;if(s<n.notBefore)return!1}try{if(!n.address)return!1;if(!ht(n.address,{strict:!1}))return!1;if(t&&!wr(n.address,t))return!1}catch{return!1}return!0}async function cU(e,t){let{address:r,domain:n,message:o,nonce:i,scheme:s,signature:a,time:c=new Date,...d}=t,l=sU(o);if(!l.address)return!1;if(!aU({address:r,domain:n,message:l,nonce:i,scheme:s,time:c}))return!1;let m=gl(o);return Aa(e,{address:l.address,hash:m,signature:a,...d})}Mr();He();class cr extends C{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
|
|
145
145
|
`),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class Co extends C{constructor({docsPath:e,metaMessages:t,type:r}){super(`Account type "${r}" is not supported.`,{docsPath:e,metaMessages:t,name:"AccountTypeNotSupportedError"})}}xn();He();Jf();function yl({chain:e,currentChainId:t}){if(!e)throw new hE;if(t!==e.id)throw new mE({chain:e,currentChainId:t})}ps();Ec();ci();async function bl(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var iA=new On(128);async function Ia(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:d=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:l,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,type:_,value:w,...A}=t;if(typeof r>"u")throw new cr({docsPath:"/docs/actions/wallet/sendTransaction"});let S=r?ze(r):null,v;try{Sr(t);let P=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(s&&s.length>0)return await ba({authorization:s[0]}).catch(()=>{throw new C("`to` is required. Could not infer from `authorizationList`.")});return})();if(S?.type==="json-rpc"||S===null){let k;if(o!==null){if(k=await J(e,qr,"getChainId")({}),n)yl({currentChainId:k,chain:o})}let O=e.chain?.formatters?.transactionRequest?.format,j=(O||jr)({...eo(A,{format:O}),accessList:i,account:S,authorizationList:s,blobs:a,chainId:k,data:d?fr([c??"0x",d]):c,gas:l,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,to:P,type:_,value:w},"sendTransaction"),R=iA.get(e.uid),K=R?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:K,params:[j]},{retryCount:0})}catch(Z){if(R===!1)throw Z;let re=Z;if(re.name==="InvalidInputRpcError"||re.name==="InvalidParamsRpcError"||re.name==="MethodNotFoundRpcError"||re.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[j]},{retryCount:0}).then((pe)=>(iA.set(e.uid,!0),pe)).catch((pe)=>{let U=pe;if(U.name==="MethodNotFoundRpcError"||U.name==="MethodNotSupportedRpcError")throw iA.set(e.uid,!1),re;throw U});throw re}}if(S?.type==="local"){let k=(()=>{if(!S.nonceManager||typeof x<"u")return S.nonceManager;let Z=S.nonceManager;return{consume(re){return v={address:re.address,chainId:re.chainId},Z.consume(re)},get(re){return Z.get(re)},increment(re){return Z.increment(re)},reset(re){return Z.reset(re)}}})(),O=await J(e,di,"prepareTransactionRequest")({account:S,accessList:i,authorizationList:s,blobs:a,chain:o,data:d?fr([c??"0x",d]):c,gas:l,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,nonceManager:k,parameters:[...xm,"sidecars"],type:_,value:w,...A,to:P}),N=o?.serializers?.transaction,j=await S.signTransaction(O,{serializer:N}),R=(o??e.chain)?.serializers?.transactionEnvelope,K=R?await R({serializedTransaction:j,transaction:O}):j;return await J(e,bl,"sendRawTransaction")({serializedTransaction:K})}if(S?.type==="smart")throw new Co({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new Co({docsPath:"/docs/actions/wallet/sendTransaction",type:S?.type})}catch(P){if(P instanceof Co)throw P;if(v)S?.nonceManager?.reset(v);throw _a(P,{...t,account:S,chain:t.chain||void 0})}}async function Mo(e,t){return Mo.internal(e,Ia,"sendTransaction",t)}(function(e){async function t(r,n,o,i){let{abi:s,account:a=r.account,address:c,args:d,functionName:l,...p}=i;if(typeof a>"u")throw new cr({docsPath:"/docs/contract/writeContract"});let m=a?ze(a):null,h=At({abi:s,args:d,functionName:l});try{return await J(r,n,o)({data:h,to:c,account:m,...p})}catch(y){throw $n(y,{abi:s,address:c,args:d,docsPath:"/docs/contract/writeContract",functionName:l,sender:m?.address})}}e.internal=t})(Mo||(Mo={}));Mr();Cn();us();Qf();function xl(e,t){return Ay(e,t)}Qf();function uU(e,t){return H3(e,t)}function _l(e,t){return{amount:e,decimals:t,formatted:xl(e,t)}}function Tb(e,t){if(typeof e==="bigint")return e;let r=e.decimals??t;return uU(e.formatted,Xue(r))}function Xue(e){if(e===void 0)throw Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function Eb(e,t){if(typeof e==="bigint")return t;return e.decimals??t}function zr(e,t){let{decimals:r,token:n}=t,o=aA(e,n);if(o)return{address:o.address,decimals:r??o.decimals};if(ht(n,{strict:!1}))return{address:n,decimals:r??tde(e,n)};throw Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function aA(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let o=ede(r,t);if(o)return sA(o,n);if(ht(t,{strict:!1}))for(let i of r){let s=sA(i,n);if(s&&wr(s.address,t))return s}return}function sA(e,t){let r=e.addresses[t];if(!r)return;return{address:r,currency:e.currency,decimals:e.decimals,name:e.name,popular:e.popular,symbol:e.symbol}}function ede(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n;return}function tde(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let o of r){let i=sA(o,n);if(i&&wr(i.address,t))return i.decimals}return}async function wl(e,t){let{address:r,decimals:n}=zr(e,t);if(n!==void 0)return{address:r,decimals:n};return{address:r,decimals:await gt(e,{abi:Wt,address:r,functionName:"decimals"})}}function Sl(e){let{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}=e;return{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}}function pi(e){return{...e,data:At(e),to:e.address}}async function bs(e,t){return bs.inner(Mo,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return pi(rde(s,a))}e.call=r;async function n(s,a){return ol(s,{...Sl(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return hl(s,{...Sl(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=li({abi:Wt,logs:s,eventName:"Approval",strict:!0});if(!a)throw Error("`Approval` event not found.");return a}e.extractEvent=i})(bs||(bs={}));function rde(e,t){let{amount:r,spender:n,token:o}=t,{address:i,decimals:s}=zr(e,{token:o});return{abi:Wt,address:i,args:[n,Tb(r,s)],functionName:"approve"}}He();on();ps();Ec();ci();on();async function vl(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let o=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),s=(e.chain?.formatters?.transactionReceipt?.format||il)(o);if(s.status==="reverted"&&r)throw new yd({receipt:s});return s}var cA=new On(128);async function Pb(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:d=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:l,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,pollingInterval:_,throwOnReceiptRevert:w,type:A,value:S,...v}=t,P=t.timeout??Math.max((o?.blockTime??0)*3,5000);if(typeof r>"u")throw new cr({docsPath:"/docs/actions/wallet/sendTransactionSync"});let k=r?ze(r):null,O;try{Sr(t);let N=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(s&&s.length>0)return await ba({authorization:s[0]}).catch(()=>{throw new C("`to` is required. Could not infer from `authorizationList`.")});return})();if(k?.type==="json-rpc"||k===null){let j;if(o!==null){if(j=await J(e,qr,"getChainId")({}),n)yl({currentChainId:j,chain:o})}let R=e.chain?.formatters?.transactionRequest?.format,Z=(R||jr)({...eo(v,{format:R}),accessList:i,account:k,authorizationList:s,blobs:a,chainId:j,data:d?fr([c??"0x",d]):c,gas:l,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,to:N,type:A,value:S},"sendTransaction"),re=cA.get(e.uid),pe=re?"wallet_sendTransaction":"eth_sendTransaction",U=await(async()=>{try{return await e.request({method:pe,params:[Z]},{retryCount:0})}catch(me){if(re===!1)throw me;let z=me;if(z.name==="InvalidInputRpcError"||z.name==="InvalidParamsRpcError"||z.name==="MethodNotFoundRpcError"||z.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[Z]},{retryCount:0}).then((F)=>(cA.set(e.uid,!0),F)).catch((F)=>{let Y=F;if(Y.name==="MethodNotFoundRpcError"||Y.name==="MethodNotSupportedRpcError")throw cA.set(e.uid,!1),z;throw Y});throw z}})(),ee=await J(e,vb,"waitForTransactionReceipt")({checkReplacement:!1,hash:U,pollingInterval:_,timeout:P});if(w&&ee.status==="reverted")throw new yd({receipt:ee});return ee}if(k?.type==="local"){let j=(()=>{if(!k.nonceManager||typeof x<"u")return k.nonceManager;let U=k.nonceManager;return{consume(ee){return O={address:ee.address,chainId:ee.chainId},U.consume(ee)},get(ee){return U.get(ee)},increment(ee){return U.increment(ee)},reset(ee){return U.reset(ee)}}})(),R=await J(e,di,"prepareTransactionRequest")({account:k,accessList:i,authorizationList:s,blobs:a,chain:o,data:d?fr([c??"0x",d]):c,gas:l,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,nonceManager:j,parameters:[...xm,"sidecars"],type:A,value:S,...v,to:N}),K=o?.serializers?.transaction,Z=await k.signTransaction(R,{serializer:K}),re=(o??e.chain)?.serializers?.transactionEnvelope,pe=re?await re({serializedTransaction:Z,transaction:R}):Z;return await J(e,vl,"sendRawTransactionSync")({serializedTransaction:pe,throwOnReceiptRevert:w,timeout:t.timeout})}if(k?.type==="smart")throw new Co({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new Co({docsPath:"/docs/actions/wallet/sendTransactionSync",type:k?.type})}catch(N){if(N instanceof Co)throw N;if(O&&!(N instanceof yd))k?.nonceManager?.reset(O);throw _a(N,{...t,account:k,chain:t.chain||void 0})}}async function Tl(e,t){return Mo.internal(e,Pb,"sendTransactionSync",t)}async function uA(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=zr(e,{token:n}),s=Eb(r,i),a=await bs.inner(Tl,e,{...t,throwOnReceiptRevert:o}),{args:c}=bs.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:xl(c.value,s)},receipt:a}}Mr();async function El(e,t){let{account:r,decimals:n,spender:o,token:i,...s}=t,[a,{decimals:c}]=await Promise.all([gt(e,{...s,...El.call(e,{account:r,spender:o,token:i})}),wl(e,{decimals:n,token:i})]);return _l(a,c)}(function(e){function t(r,n){return pi({address:zr(r,n).address,abi:Wt,functionName:"allowance",args:[n.account,n.spender]})}e.call=t})(El||(El={}));Mr();async function Pl(e,t){let{account:r=e.account,decimals:n,token:o,...i}=t;if(!r)throw new cr;let s=ze(r).address,[a,{decimals:c}]=await Promise.all([gt(e,{...i,...Pl.call(e,{account:s,token:o})}),wl(e,{decimals:n,token:o})]);return _l(a,c)}(function(e){function t(r,n){let o=n.account??r.account;if(!o)throw new cr;let i=ze(o).address;return pi({address:zr(r,n).address,abi:Wt,functionName:"balanceOf",args:[i]})}e.call=t})(Pl||(Pl={}));Mr();async function dA(e,t){let{token:r,...n}=t,{address:o}=zr(e,{token:r}),i=aA(e,r),[s,a,c]=await Promise.all([i?.decimals??gt(e,{...n,abi:Wt,address:o,functionName:"decimals"}),i?.name??gt(e,{...n,abi:Wt,address:o,functionName:"name"}),i?.symbol??gt(e,{...n,abi:Wt,address:o,functionName:"symbol"})]);return{decimals:s,name:a,symbol:c}}Mr();async function Al(e,t){let{decimals:r,token:n,...o}=t,[i,{decimals:s}]=await Promise.all([gt(e,{...o,...Al.call(e,{token:n})}),wl(e,{decimals:r,token:n})]);return _l(i,s)}(function(e){function t(r,n){return pi({address:zr(r,n).address,abi:Wt,args:[],functionName:"totalSupply"})}e.call=t})(Al||(Al={}));Mr();async function xs(e,t){return xs.inner(Mo,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return pi(nde(s,a))}e.call=r;async function n(s,a){return ol(s,{...Sl(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return hl(s,{...Sl(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=li({abi:Wt,logs:s,eventName:"Transfer",strict:!0});if(!a)throw Error("`Transfer` event not found.");return a}e.extractEvent=i})(xs||(xs={}));function nde(e,t){let{amount:r,from:n,to:o,token:i}=t,{address:s,decimals:a}=zr(e,{token:i}),c=Tb(r,a);if(n)return{abi:Wt,address:s,args:[n,o,c],functionName:"transferFrom"};return{abi:Wt,address:s,args:[o,c],functionName:"transfer"}}async function lA(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=zr(e,{token:n}),s=Eb(r,i),a=await xs.inner(Tl,e,{...t,throwOnReceiptRevert:o}),{args:c}=xs.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:xl(c.value,s)},receipt:a}}function dU(e){return{call:(t)=>Sn(e,t),createAccessList:(t)=>GL(e,t),createBlockFilter:()=>VL(e),createContractEventFilter:(t)=>Vy(e,t),createEventFilter:(t)=>Zy(e,t),createPendingTransactionFilter:()=>Wy(e),estimateContractGas:(t)=>ol(e,t),estimateGas:(t)=>nl(e,t),getBalance:(t)=>v9(e,t),getBlobBaseFee:()=>T9(e),getBlock:(t)=>ar(e,t),getBlockNumber:(t)=>to(e,t),getBlockReceipts:(t)=>A9(e,t),getBlockTransactionCount:(t)=>I9(e,t),getBytecode:(t)=>jc(e,t),getChainId:()=>qr(e),getCode:(t)=>jc(e,t),getContractEvents:(t)=>rb(e,t),getDelegation:(t)=>R9(e,t),getEip712Domain:(t)=>O9(e,t),getEnsAddress:(t)=>zL(e,t),getEnsAvatar:(t)=>jL(e,t),getEnsName:(t)=>qL(e,t),getEnsResolver:(t)=>HL(e,t),getEnsText:(t)=>Gy(e,t),getFeeHistory:(t)=>M9(e,t),estimateFeesPerGas:(t)=>l9(e,t),getFilterChanges:(t)=>wa(e,t),getFilterLogs:(t)=>$9(e,t),getGasPrice:()=>Qd(e),getLogs:(t)=>sl(e,t),getProof:(t)=>z9(e,t),estimateMaxPriorityFeePerGas:(t)=>d9(e,t),fillTransaction:(t)=>rl(e,t),getRawTransaction:(t)=>B9(e,t),getStorageAt:(t)=>L9(e,t),getTransaction:(t)=>al(e,t),getTransactionConfirmations:(t)=>D9(e,t),getTransactionCount:(t)=>Xd(e,t),getTransactionReceipt:(t)=>cl(e,t),multicall:(t)=>U9(e,t),prepareTransactionRequest:(t)=>di(e,t),readContract:(t)=>gt(e,t),sendRawTransaction:(t)=>bl(e,t),sendRawTransactionSync:(t)=>vl(e,t),simulate:(t)=>ul(e,t),simulateBlocks:(t)=>ul(e,t),simulateCalls:(t)=>kD(e,t),simulateContract:(t)=>hl(e,t),verifyHash:(t)=>Aa(e,t),verifyMessage:(t)=>WD(e,t),verifySiweMessage:(t)=>cU(e,t),verifyTypedData:(t)=>eU(e,t),uninstallFilter:(t)=>Ea(e,t),waitForTransactionReceipt:(t)=>vb(e,t),watchBlockHeaders:(t)=>tU(e,t),watchBlocks:(t)=>rU(e,t),watchBlockNumber:(t)=>Sb(e,t),watchContractEvent:(t)=>nU(e,t),watchEvent:(t)=>oU(e,t),watchPendingTransactions:(t)=>iU(e,t),token:ode(e)}}function ode(e){return{getAllowance:Qo(e,El),getBalance:Qo(e,Pl),getMetadata:Qo(e,dA),getTotalSupply:Qo(e,Al)}}function pA(e){let{key:t="public",name:r="Public Client"}=e;return V0({...e,key:t,name:r,type:"publicClient"}).extend(dU)}Fe();async function lU(e,{chain:t}){let{id:r,name:n,nativeCurrency:o,rpcUrls:i,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:H(r),chainName:n,nativeCurrency:o,rpcUrls:i.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}Uy();function pU(e,t){let{abi:r,args:n,bytecode:o,...i}=t,s=Bc({abi:r,args:n,bytecode:o});return Ia(e,{...i,...i.authorizationList?{to:null}:{},data:s})}ri();async function fU(e){if(e.account?.type==="local")return[e.account.address];return(await e.request({method:"eth_accounts"},{dedupe:!0})).map((r)=>Yi(r))}Ji();lr();He();Fd();xn();lr();Fe();var fA="0x5792579257925792579257925792579257925792579257925792579257925792",mA=H(0,{size:32});async function Ab(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:o,experimental_fallbackDelay:i=32,forceAtomic:s=!1,id:a,version:c="2.0.0"}=t,d=r?ze(r):null,l=t.capabilities;if(e.dataSuffix&&!t.capabilities?.dataSuffix)if(typeof e.dataSuffix==="string")l={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}};else l={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}};let p=t.calls.map((m)=>{let h=m,y=h.abi?At({abi:h.abi,functionName:h.functionName,args:h.args}):h.data;return{data:h.dataSuffix&&y?fr([y,h.dataSuffix]):y,to:h.to,value:h.value?H(h.value):void 0}});try{let m=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:s,calls:p,capabilities:l,chainId:H(n.id),from:d?.address,id:a,version:c}]},{retryCount:0});if(typeof m==="string")return{id:m};return m}catch(m){let h=m;if(o&&(h.name==="MethodNotFoundRpcError"||h.name==="MethodNotSupportedRpcError"||h.name==="UnknownRpcError"||h.details.toLowerCase().includes("does not exist / is not available")||h.details.toLowerCase().includes("missing or invalid. request()")||h.details.toLowerCase().includes("did not match any variant of untagged enum")||h.details.toLowerCase().includes("account upgraded to unsupported contract")||h.details.toLowerCase().includes("eip-7702 not supported")||h.details.toLowerCase().includes("unsupported wc_ method")||h.details.toLowerCase().includes("feature toggled misconfigured")||h.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(l){if(Object.values(l).some((w)=>!w.optional))throw new fa(new C("non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.",{details:"non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`."}))}if(s&&p.length>1)throw new ma(new C("`forceAtomic` is not supported on fallback to `eth_sendTransaction`.",{details:"`forceAtomic` is not supported on fallback to `eth_sendTransaction`."}));let y=[];for(let _ of p){try{let w=await Ia(e,{account:d,chain:n,data:_.data,to:_.to,value:_.value?er(_.value):void 0});y.push({status:"fulfilled",value:w})}catch(w){y.push({reason:w,status:"rejected"})}if(i>0)await new Promise((w)=>setTimeout(w,i))}if(y.every((_)=>_.status==="rejected"))throw y[0].reason;let x=y.map((_)=>{if(_.status==="fulfilled")return _.value;return mA});return{id:fr([...x,H(n.id,{size:32}),fA])}}throw _a(m,{...t,account:d,chain:t.chain})}}async function Ib(e,t){async function r(l){if(l.endsWith(fA.slice(2))){let m=$r(uy(l,-64,-32)),h=uy(l,0,-64).slice(2).match(/.{1,64}/g),y=await Promise.all(h.map((_)=>mA.slice(2)!==_?e.request({method:"eth_getTransactionReceipt",params:[`0x${_}`]},{dedupe:!0}):void 0)),x=(()=>{if(y.some((_)=>_===null))return 100;if(y.every((_)=>_?.status==="0x1"))return 200;if(y.every((_)=>_?.status==="0x0"))return 500;return 600})();return{atomic:!1,chainId:Yt(m),receipts:y.filter(Boolean),status:x,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[l]})}let{atomic:n=!1,chainId:o,receipts:i,version:s="2.0.0",...a}=await r(t.id),[c,d]=(()=>{let l=a.status;if(l>=100&&l<200)return["pending",l];if(l>=200&&l<300)return["success",l];if(l>=300&&l<700)return["failure",l];if(l==="CONFIRMED")return["success",200];if(l==="PENDING")return["pending",100];return[void 0,l]})();return{...a,atomic:n,chainId:o?Yt(o):void 0,receipts:i?.map((l)=>({...l,blockNumber:er(l.blockNumber),gasUsed:er(l.gasUsed),status:TP[l.status]}))??[],statusCode:d,status:c,version:s}}Fe();async function mU(e,t={}){let{account:r=e.account,chainId:n}=t,o=r?ze(r):void 0,i=n?[o?.address,[H(n)]]:[o?.address],s=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(let[c,d]of Object.entries(s)){a[Number(c)]={};for(let[l,p]of Object.entries(d)){if(l==="addSubAccount")l="unstable_addSubAccount";a[Number(c)][l]=p}}return typeof n==="number"?a[n]:a}async function hU(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}us();async function kb(e,t){let{account:r=e.account,chainId:n,nonce:o}=t;if(!r)throw new cr({docsPath:"/docs/eip7702/prepareAuthorization"});let i=ze(r),s=(()=>{if(!t.executor)return;if(t.executor==="self")return t.executor;return ze(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:o};if(typeof a.chainId>"u")a.chainId=e.chain?.id??await J(e,qr,"getChainId")({});if(typeof a.nonce>"u"){if(a.nonce=await J(e,Xd,"getTransactionCount")({address:i.address,blockTag:"pending"}),s==="self"||s?.address&&wr(s.address,i.address))a.nonce+=1}return a}ri();async function gU(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map((r)=>Po(r))}async function yU(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}He();He();class hA extends C{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"});Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}async function Rb(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:o=({statusCode:x})=>x===200||x>=300,retryCount:i=4,retryDelay:s=({count:x})=>~~(1<<x)*200,timeout:a=60000,throwOnFailure:c=!1}=t,d=Je(["waitForCallsStatus",e.uid,r]),{promise:l,resolve:p,reject:m}=Vd(),h,y=Er(d,{resolve:p,reject:m},(x)=>{let _=ro(async()=>{let w=(A)=>{clearTimeout(h),_(),A(),y()};try{let A=await Zc(async()=>{let S=await J(e,Ib,"getCallsStatus")({id:r});if(c&&S.status==="failure")throw new hA(S);return S},{retryCount:i,delay:s});if(!o(A))return;w(()=>x.resolve(A))}catch(A){w(()=>x.reject(A))}},{interval:n,emitOnBegin:!0});return _});return h=a?setTimeout(()=>{y(),clearTimeout(h),m(new bU({id:r}))},a):void 0,await l}class bU extends C{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}async function xU(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5000),o=await J(e,Ab,"sendCalls")(t);return await J(e,Rb,"waitForCallsStatus")({...t,id:o.id,timeout:n})}async function _U(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]});return}async function wU(e,t){let{account:r=e.account}=t;if(!r)throw new cr({docsPath:"/docs/eip7702/signAuthorization"});let n=ze(r);if(!n.signAuthorization)throw new Co({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let o=await kb(e,t);return n.signAuthorization(o)}Fe();async function SU(e,{account:t=e.account,message:r}){if(!t)throw new cr({docsPath:"/docs/actions/wallet/signMessage"});let n=ze(t);if(n.signMessage)return n.signMessage({message:r});let o=(()=>{if(typeof r==="string")return aa(r);if(r.raw instanceof Uint8Array)return Jt(r.raw);return r.raw})();return e.request({method:"personal_sign",params:[o,n.address]},{retryCount:0})}Fe();ps();ci();async function vU(e,t){let{account:r=e.account,chain:n=e.chain,...o}=t;if(!r)throw new cr({docsPath:"/docs/actions/wallet/signTransaction"});let i=ze(r);Sr({account:i,...t});let s=await J(e,qr,"getChainId")({});if(n!==null)yl({currentChainId:s,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||jr;if(i.signTransaction)return i.signTransaction({...o,account:i,chainId:s},{serializer:e.chain?.serializers?.transaction});return await e.request({method:"eth_signTransaction",params:[{...c({...o,account:i},"signTransaction"),chainId:H(s),from:i.address}]},{retryCount:0})}async function TU(e,t){let{account:r=e.account,domain:n,message:o,primaryType:i}=t;if(!r)throw new cr({docsPath:"/docs/actions/wallet/signTypedData"});let s=ze(r),a={EIP712Domain:xb({domain:n}),...t.types};if(bb({domain:n,message:o,primaryType:i,types:a}),s.signTypedData)return s.signTypedData({domain:n,message:o,primaryType:i,types:a});let c=KD({domain:n,message:o,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[s.address,c]},{retryCount:0})}Fe();async function EU(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:H(t)}]},{retryCount:0})}async function PU(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function AU(e){return{addChain:(t)=>lU(e,t),deployContract:(t)=>pU(e,t),fillTransaction:(t)=>rl(e,t),getAddresses:()=>fU(e),getCallsStatus:(t)=>Ib(e,t),getCapabilities:(t)=>mU(e,t),getChainId:()=>qr(e),getPermissions:()=>hU(e),prepareAuthorization:(t)=>kb(e,t),prepareTransactionRequest:(t)=>di(e,t),requestAddresses:()=>gU(e),requestPermissions:(t)=>yU(e,t),sendCalls:(t)=>Ab(e,t),sendCallsSync:(t)=>xU(e,t),sendRawTransaction:(t)=>bl(e,t),sendRawTransactionSync:(t)=>vl(e,t),sendTransaction:(t)=>Ia(e,t),sendTransactionSync:(t)=>Pb(e,t),showCallsStatus:(t)=>_U(e,t),signAuthorization:(t)=>wU(e,t),signMessage:(t)=>SU(e,t),signTransaction:(t)=>vU(e,t),signTypedData:(t)=>TU(e,t),switchChain:(t)=>EU(e,t),waitForCallsStatus:(t)=>Rb(e,t),watchAsset:(t)=>PU(e,t),writeContract:(t)=>Mo(e,t),writeContractSync:(t)=>Tl(e,t),token:{approve:Qo(e,bs),approveSync:Qo(e,uA),transfer:Qo(e,xs),transferSync:Qo(e,lA)}}}function gA(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return V0({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(AU)}Mc();He();class yA extends C{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}jy();Mc();function IU(e,{errorInstance:t=Error("timed out"),timeout:r,signal:n}){return new Promise((o,i)=>{(async()=>{let s,a=new AbortController;try{if(r>0)s=setTimeout(()=>{if(n)a.abort();else i(t)},r);o(await e({signal:a?.signal||null}))}catch(c){if(a?.signal.aborted&&_n(c)){i(t);return}i(c)}finally{clearTimeout(s)}})()})}function ide(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var bA=ide();var sde=10485760;function kU(e,t={}){let{url:r,headers:n}=cde(e);return{async request(o){let{body:i,fetchFn:s=t.fetchFn??fetch,maxResponseBodySize:a=t.maxResponseBodySize??sde,onRequest:c=t.onRequest,onResponse:d=t.onResponse,timeout:l=t.timeout??1e4}=o,p={...t.fetchOptions??{},...o.fetchOptions??{}},{headers:m,method:h,signal:y}=p;try{let x=await IU(async({signal:A})=>{let S={...p,body:Array.isArray(i)?Je(i.map((O)=>({jsonrpc:"2.0",id:O.id??bA.take(),...O}))):Je({jsonrpc:"2.0",id:i.id??bA.take(),...i}),headers:{...n,"Content-Type":"application/json",...m},method:h||"POST",signal:y||(l>0?A:null)},v=new Request(r,S),P=await c?.(v,S)??{...S,url:r};return await s(P.url??r,P)},{errorInstance:new Oy({body:i,url:r}),timeout:l,signal:!0});if(d)await d(x);let _,w=await ade(x,{maxResponseBodySize:a});if(x.headers.get("Content-Type")?.startsWith("application/json"))_=JSON.parse(w);else{_=w;try{_=JSON.parse(_||"{}")}catch(A){if(x.ok)throw A;_={error:_}}}if(!x.ok){if(typeof _.error?.code==="number"&&typeof _.error?.message==="string")return _;throw new Io({body:i,details:Je(_.error)||x.statusText,headers:x.headers,status:x.status,url:r})}return _}catch(x){if(y?.aborted)throw Nr(y);if(_n(x))throw x;if(x instanceof Io)throw x;if(x instanceof wd)throw x;if(x instanceof Oy)throw x;throw new Io({body:i,cause:x,url:r})}}}}async function ade(e,{maxResponseBodySize:t}){if(t===!1)return e.text();let r=e.headers.get("Content-Length");if(r){let a=Number(r);if(a>t)throw new wd({maxSize:t,size:a})}if(!e.body){let a=await e.text(),c=new TextEncoder().encode(a).length;if(c>t)throw new wd({maxSize:t,size:c});return a}let n=e.body.getReader(),o=new TextDecoder,i="",s=0;try{while(!0){let{done:a,value:c}=await n.read();if(a)break;if(s+=c.byteLength,s>t)throw await n.cancel(),new wd({maxSize:t,size:s});i+=o.decode(c,{stream:!0})}return i+=o.decode(),i}finally{n.releaseLock()}}function cde(e){try{let t=new URL(e),r=(()=>{if(t.username){let n=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}return})();return{url:t.toString(),...r}}catch{return{url:e}}}He();Mc();Fd();Ec();var Ob=new On(8192);function RU(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(Ob.get(r))return Ob.get(r);let n=e().finally(()=>Ob.delete(r));return Ob.set(r,n),n}function OU(e,t={}){return async(r,n={})=>{let{dedupe:o=!1,methods:i,retryDelay:s=150,retryCount:a=3,signal:c,uid:d}={...t,...n},{method:l}=r;if(i?.exclude?.includes(l))throw new pa(Error("method not supported"),{method:l});if(i?.include&&!i.include.includes(l))throw new pa(Error("method not supported"),{method:l});if(c?.aborted)throw Nr(c);let p=o?dde(`${d}.${Je(r)}`):void 0;return RU(()=>Zc(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(m){if(c?.aborted)throw Nr(c);if(_n(m))throw m;let h=m;switch(h.code){case Sd.code:throw new Sd(h);case vd.code:throw new vd(h);case Td.code:throw new Td(h,{method:r.method});case Ed.code:throw new Ed(h);case ss.code:throw new ss(h);case Jn.code:throw new Jn(h);case Pd.code:throw new Pd(h);case Ad.code:throw new Ad(h);case Id.code:throw new Id(h);case pa.code:throw new pa(h,{method:r.method});case $c.code:throw new $c(h);case kd.code:throw new kd(h);case Nc.code:throw new Nc(h);case Rd.code:throw new Rd(h);case Od.code:throw new Od(h);case Cd.code:throw new Cd(h);case Md.code:throw new Md(h);case $d.code:throw new $d(h);case fa.code:throw new fa(h);case Nd.code:throw new Nd(h);case zd.code:throw new zd(h);case Bd.code:throw new Bd(h);case Ld.code:throw new Ld(h);case Dd.code:throw new Dd(h);case ma.code:throw new ma(h);case 5000:throw new Nc(h);case Ud.code:throw new Ud(h);default:if(m instanceof C)throw m;throw new ME(h)}}},{delay:({count:m,error:h})=>{if(h&&h instanceof Io){let y=h?.headers?.get("Retry-After");if(y?.match(/\d/))return Number.parseInt(y,10)*1000}return~~(1<<m)*s},retryCount:a,signal:c,shouldRetry:({error:m})=>ude(m)}),{enabled:o,id:p})}}function ude(e){if(_n(e))return!1;if("code"in e&&typeof e.code==="number"){if(e.code===-1)return!0;if(e.code===$c.code)return!0;if(e.code===ss.code)return!0;if(e.code===429)return!0;return!1}if(e instanceof Io&&e.status){if(e.status===403)return!0;if(e.status===408)return!0;if(e.status===413)return!0;if(e.status===429)return!0;if(e.status===500)return!0;if(e.status===502)return!0;if(e.status===503)return!0;if(e.status===504)return!0;return!1}return!0}function dde(e,t=0){let r=3735928559^t,n=1103547991^t;for(let o=0;o<e.length;o++){let i=e.charCodeAt(o);r=Math.imul(r^i,2654435761),n=Math.imul(n^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}function CU({key:e,methods:t,name:r,request:n,retryCount:o=3,retryDelay:i=150,timeout:s,type:a},c){let d=G0();return{config:{key:e,methods:t,name:r,request:n,retryCount:o,retryDelay:i,timeout:s,type:a},request:OU(n,{methods:t,retryCount:o,retryDelay:i,uid:d}),value:c}}var lde=0,MU=new WeakMap;function pde(e){if(!e)return"default";let t=MU.get(e);if(t!==void 0)return t;let r=lde++;return MU.set(e,r),r}function Pm(e,t={}){let{batch:r,fetchFn:n,fetchOptions:o,key:i="http",maxResponseBodySize:s,methods:a,name:c="HTTP JSON-RPC",onFetchRequest:d,onFetchResponse:l,retryDelay:p,raw:m}=t;return({chain:h,retryCount:y,timeout:x})=>{let{batchSize:_=1000,wait:w=0}=typeof r==="object"?r:{},A=t.retryCount??y,S=x??t.timeout??1e4,v=e||h?.rpcUrls.default.http[0];if(!v)throw new yA;let P=kU(v,{fetchFn:n,fetchOptions:o,maxResponseBodySize:s,onRequest:d,onResponse:l,timeout:S});return CU({key:i,methods:a,name:c,async request({method:k,params:O},N){let j={method:k,params:O},R=N?.signal?{signal:N.signal}:void 0,{schedule:K}=Zd({id:`${v}.${pde(N?.signal)}`,wait:w,shouldSplitBatch(U){return U.length>_},fn:(U)=>P.request({body:U,fetchOptions:R}),sort:(U,ee)=>U.id-ee.id}),Z=async(U)=>r?K(U):[await P.request({body:U,fetchOptions:R})],[{error:re,result:pe}]=await Z(j);if(m)return{error:re,result:pe};if(re)throw new Cc({body:j,error:re,url:v});return pe},retryCount:A,retryDelay:p,timeout:S,type:"http"},{fetchOptions:o,url:v})}}Mr();function Cb(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return(o)=>{let i=typeof o==="function"?o(n):o,s={...n,...i};return Object.assign(s,{extend:r(s)})}}return Object.assign(t,{extend:r(t)})}var Am=Cb({id:1329,name:"Sei Network",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc.sei-apis.com/"],webSocket:["wss://evm-ws.sei-apis.com/"]}},blockExplorers:{default:{name:"Seiscan",url:"https://seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11"}}});var Im=Cb({id:1328,name:"Sei Testnet",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc-testnet.sei-apis.com"],webSocket:["wss://evm-ws-testnet.sei-apis.com"]}},blockExplorers:{default:{name:"Seiscan",url:"https://testnet.seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:98697651}},testnet:!0});var Mb=Vr(j0(),1);function $U(e){return btoa(String.fromCharCode(...e))}function NU(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=:${$U(N0(n))}:`,d=`("@method" "@path" "@query" "content-digest");created=${o};keyid="${Li(e.publicKey)}";alg="ed25519"`,l=`"@method": ${t}
|
|
@@ -148,5 +148,5 @@ ${t}`}function D0(e,t){return Li(rd.sign(pc(t),e))}var kf=[0.0001,0.001,0.01,0.1
|
|
|
148
148
|
"content-digest": ${c}
|
|
149
149
|
"@signature-params": ${d}`;return{"Signature-Input":`monaco=${d}`,Signature:`monaco=:${$U(rd.sign(pc(l),e.privateKey))}:`,"Content-Digest":c}}var fde="@0xmonaco/core",xA={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},_A="Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",mde=new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2}) (${_A}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`),hde=new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-(${_A})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`),gde=new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (${_A}) ([ \\d]\\d) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$`);function yde(e,t,r,n,o,i){let s=new Date(Date.now()),a=Math.floor(s.getUTCFullYear()/100)*100+e,c=Date.UTC(a,t,r,n,o,i),d=Date.UTC(s.getUTCFullYear()+50,s.getUTCMonth(),s.getUTCDate(),s.getUTCHours(),s.getUTCMinutes(),s.getUTCSeconds());return c>d?a-100:a}function bde(e){let t,r,n,o,i,s,a=mde.exec(e),c=hde.exec(e),d=gde.exec(e);if(a)t=Number(a[1]),r=xA[a[2]],n=Number(a[3]),o=Number(a[4]),i=Number(a[5]),s=Number(a[6]);else if(c){if(t=Number(c[1]),r=xA[c[2]],o=Number(c[4]),i=Number(c[5]),s=Number(c[6]),r===void 0)return;n=yde(Number(c[3]),r,t,o,i,s)}else if(d)r=xA[d[1]],t=Number((d[2]??"").trim()),o=Number(d[3]),i=Number(d[4]),s=Number(d[5]),n=Number(d[6]);else return;if(r===void 0)return;let l=Date.UTC(n,r,t,o,i,s),p=new Date(l);if(p.getUTCFullYear()!==n||p.getUTCMonth()!==r||p.getUTCDate()!==t||p.getUTCHours()!==o||p.getUTCMinutes()!==i||p.getUTCSeconds()!==s)return;return l}class Ve{apiUrl;sessionKeypair;serverKey;requestSigning="legacy";setRequestSigning(e){if(e!=="legacy"&&e!=="rfc9421")throw Error("Unsupported request signing protocol");this.requestSigning=e}retryOptions;constructor(e,t){this.apiUrl=e,this.retryOptions={maxRetries:t?.maxRetries??3,baseDelayMs:t?.baseDelayMs??1000}}setSessionKeypair(e){this.sessionKeypair=e?Z8(e.publicKey,e.privateKey):void 0}setServerKey(e){this.serverKey=e}parseRequestBody(e){if(!e)return;if(typeof e==="string")try{return JSON.parse(e)}catch{return e}if(e instanceof FormData){let t={};return e.forEach((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),t}if(e instanceof URLSearchParams){let t={};return e.forEach((r,n)=>{t[n]=r}),t}if(e instanceof Blob)return{type:"[Blob]",size:e.size,contentType:e.type};if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return{type:"[ArrayBuffer]",size:e instanceof ArrayBuffer?e.byteLength:e.byteLength};if(typeof ReadableStream<"u"&&e instanceof ReadableStream)return{type:"[ReadableStream]",note:"Stream body not captured for logging"};return{type:"[Unknown]",bodyType:typeof e}}extractResponseMetadata(e){if(!e)return{};let t=e.get("x-request-id")||e.get("request-id")||e.get("x-correlation-id")||void 0,r=e.get("retry-after"),n;if(r!==null){let o=r.trim();if(/^\d+$/.test(o))n=Number.parseInt(o,10);else{let i=bde(o);if(i!==void 0)n=Math.max(0,Math.ceil((i-Date.now())/1000))}}return{requestId:t,retryAfter:n}}async executeRequest(e,t,r,n){let o,i={"User-Agent":fde,...r.headers};try{o=await fetch(e,{...r,headers:i})}catch(d){throw new Zt(`Network request failed for ${t}`,{endpoint:e,cause:d instanceof Error?d:Error(String(d)),requestBody:n})}let s,a=o.headers?.get("content-type")||"unknown",c=o.clone?o.clone():o;try{s=await o.json()}catch(d){let l;try{l=await c.text()}catch{l="[Unable to read response body]"}if(!o.ok){let p=`API request failed: ${o.status}. Response is not JSON (Content-Type: ${a})`,{requestId:m,retryAfter:h}=this.extractResponseMetadata(o.headers);throw new Zt(p,{endpoint:e,statusCode:o.status,responseBody:{rawResponse:l.substring(0,500),contentType:a,parseError:d instanceof Error?d.message:String(d)},cause:d instanceof Error?d:void 0,requestBody:n,requestId:m,retryAfter:h})}if(l.trim()==="")return;throw new Zt(`Expected JSON response but received ${a}`,{endpoint:e,statusCode:o.status,responseBody:{rawResponse:l.substring(0,500),contentType:a},cause:d instanceof Error?d:void 0,requestBody:n})}if(!o.ok){let d=s!==null&&typeof s==="object"?s:void 0,l=(typeof d?.message==="string"?d.message:void 0)||(typeof d?.error==="string"?d.error:void 0)||`API request failed: ${o.status}`,{requestId:p,retryAfter:m}=this.extractResponseMetadata(o.headers);throw new Zt(l,{endpoint:e,statusCode:o.status,responseBody:s,requestBody:n,requestId:p,retryAfter:m})}return s}async makeAuthenticatedRequest(e,t={}){if(!this.sessionKeypair)throw new Zt("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:Mb.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body),o=this.buildSignatureHeaders(e,t),i=t.headers;if(this.requestSigning==="rfc9421"){let s={};new Headers(t.headers).forEach((a,c)=>{s[c]=a}),i=s}return this.executeRequest(r,e,{...t,...this.requestSigning==="rfc9421"?{redirect:"error"}:{},headers:{"Content-Type":"application/json",...i,...o}},n)}buildSignatureHeaders(e,t){if(!this.sessionKeypair)throw new Zt("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:Mb.StatusCodes.UNAUTHORIZED});let r=(t.method??"GET").toUpperCase();if(this.requestSigning==="rfc9421"){if(t.body!=null&&typeof t.body!=="string")throw Error("Signed requests require a string body");let c=new Headers(t.headers);for(let l of["signature","signature-input","content-digest","x-monaco-publickey","x-monaco-timestamp","x-monaco-signature"])if(c.has(l))throw Error("Signature headers are managed by the SDK");let d=new URL(`${this.apiUrl}${e}`);return NU(this.sessionKeypair,r,d.pathname+d.search,pc(t.body??""),Math.floor(Date.now()/1000))}let n=Date.now(),o=typeof t.body==="string"?pc(t.body):new Uint8Array(0),i=W8(o),s=K8(r,e,n,i),a=D0(this.sessionKeypair.privateKey,s);return{"X-Monaco-PublicKey":Li(this.sessionKeypair.publicKey),"X-Monaco-Timestamp":String(n),"X-Monaco-Signature":a}}async makeBackendRequest(e,t={}){if(!this.serverKey)throw new Zt("Server key not set. Call setServerKey(sk_...) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:Mb.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json","x-server-key":this.serverKey,...t.headers}},n)}async makePublicRequest(e,t={}){let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json",...t.headers}},n)}}function nt(e){return encodeURIComponent(e)}function Bt(e,t){if(!t)return e;let r=new URLSearchParams;for(let[o,i]of Object.entries(t))if(i!==void 0)r.set(o,String(i));let n=r.toString();return n?`${e}?${n}`:e}var ae={orders:{create:()=>"/api/v1/orders",list:(e)=>Bt("/api/v1/orders",e),get:(e)=>`/api/v1/orders/${nt(e)}`,replace:(e)=>`/api/v1/orders/${nt(e)}`,cancel:()=>"/api/v1/orders/cancel",batchCancel:()=>"/api/v1/orders/batch-cancel",batchCancelAll:()=>"/api/v1/orders/batch-cancel-all",batchCancelAllByPair:(e)=>`/api/v1/orders/batch-cancel-all/${nt(e)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:(e)=>Bt("/api/v1/orders/conditional",e),cancelConditional:(e)=>`/api/v1/orders/conditional/${nt(e)}`,getConditional:(e)=>`/api/v1/orders/conditional/${nt(e)}`,createTwap:()=>"/api/v1/orders/twap",listTwap:(e)=>Bt("/api/v1/orders/twap",e),getTwap:(e)=>`/api/v1/orders/twap/${nt(e)}`,getTwapTca:(e)=>`/api/v1/orders/twap/${nt(e)}/tca`,cancelTwap:(e)=>`/api/v1/orders/twap/${nt(e)}/cancel`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:(e)=>`/api/v1/delegated-agents/${nt(e)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:(e)=>`/api/v1/withdrawals/${nt(String(e))}`,list:(e)=>Bt("/api/v1/withdrawals",e)},market:{listTradingPairs:(e)=>Bt("/api/v1/market/pairs",e),getTradingPair:(e)=>`/api/v1/market/pairs/${nt(e)}`,getCandles:(e,t,r)=>Bt(`/api/v1/market/pairs/charts/candlestick/${nt(e)}/${nt(t)}`,r),getMarketMetadata:(e)=>`/api/v1/market/pairs/${nt(e)}/metadata`,getPerpMarketConfig:(e)=>`/api/v1/market/pairs/${nt(e)}/perp/config`,getPerpMarketSummary:(e)=>`/api/v1/market/pairs/${nt(e)}/perp/summary`,getMarkPrice:(e)=>`/api/v1/market/pairs/${nt(e)}/mark-price`,getIndexPrice:(e)=>`/api/v1/market/pairs/${nt(e)}/index-price`,getFundingState:(e)=>`/api/v1/market/pairs/${nt(e)}/funding`,listFundingHistory:(e,t)=>Bt(`/api/v1/market/pairs/${nt(e)}/funding/history`,t),listAllFundingHistory:(e)=>Bt("/api/v1/market/funding/history",e),getOpenInterest:(e)=>`/api/v1/market/pairs/${nt(e)}/open-interest`,getScreener:(e)=>Bt("/api/v1/market/screener",e),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:(e,t)=>Bt(`/api/v1/orderbook/${nt(e)}`,t)},trades:{publicByPair:(e,t)=>Bt(`/api/v1/trades/${nt(e)}`,t),byId:(e)=>`/api/v1/trades/by-id/${nt(e)}`,user:(e)=>Bt("/api/v1/accounts/trades",e)},applications:{orders:(e)=>Bt("/api/v1/applications/orders",e),users:(e)=>Bt("/api/v1/applications/users",e),movements:(e)=>Bt("/api/v1/applications/movements",e),balances:(e)=>Bt("/api/v1/applications/balances",e),stats:(e)=>Bt("/api/v1/applications/stats",e)},subAccounts:{list:()=>"/api/v1/accounts/sub-accounts",createLimit:()=>"/api/v1/accounts/sub-accounts/limits",getLimits:(e)=>`/api/v1/accounts/sub-accounts/${nt(e)}/limits`,limit:(e,t)=>`/api/v1/accounts/sub-accounts/${nt(e)}/limits/${nt(t)}`},faucet:{mint:()=>"/api/v1/faucet/mint",info:()=>"/api/v1/faucet/info"},sweeper:{register:()=>"/api/v1/sweeper/register",chains:()=>"/api/v1/sweeper/chains"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:(e)=>Bt("/api/v1/positions",e),get:(e)=>`/api/v1/positions/${nt(e)}`,close:(e)=>`/api/v1/positions/${nt(e)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:(e)=>`/api/v1/positions/${nt(e)}/risk`,attachTpSl:(e)=>`/api/v1/positions/${nt(e)}/tp-sl`,history:(e)=>Bt("/api/v1/positions/history",e),pnlHistory:(e,t)=>Bt(`/api/v1/positions/${nt(e)}/pnl/history`,t)},marginAccounts:{list:(e)=>Bt("/api/v1/margin/accounts",e),parentSummary:(e)=>Bt("/api/v1/margin/parent-margin-account",e),summary:(e,t)=>Bt(`/api/v1/margin/accounts/${nt(e)}`,t),availableCollateral:(e)=>Bt("/api/v1/margin/collateral/available",e),transferIn:(e)=>`/api/v1/margin/accounts/${nt(e)}/collateral/transfer-in`,transferInParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-in",transferInRiskBucket:()=>"/api/v1/margin/risk-buckets/collateral/transfer-in",transferOut:(e)=>`/api/v1/margin/accounts/${nt(e)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:(e,t)=>Bt(`/api/v1/margin/accounts/${nt(e)}/movements`,t),parentMovements:(e)=>Bt("/api/v1/margin/parent-margin-account/movements",e),simulateParentMarginOrderRisk:()=>"/api/v1/margin/parent-margin-account/simulate-order-risk",simulateOrderRisk:(e)=>`/api/v1/margin/accounts/${nt(e)}/simulate-order-risk`,simulateRiskBucketOrderRisk:()=>"/api/v1/margin/risk-buckets/simulate-order-risk"},streams:{orderbook:()=>"/api/v1/streaming/orderbook",trades:()=>"/api/v1/streaming/trades",perpMarketSummaries:()=>"/api/v1/streaming/perp-market-summaries",markPrices:()=>"/api/v1/streaming/mark-prices",privateTrades:()=>"/api/v1/streaming/private-trades",orders:()=>"/api/v1/streaming/orders",positions:()=>"/api/v1/streaming/positions",funding:()=>"/api/v1/streaming/funding",liquidationAlerts:()=>"/api/v1/streaming/liquidation-alerts"}};class $b extends Ve{async getApplicationConfig(){let e=await this.makeAuthenticatedRequest("/api/v1/applications/config",{method:"GET"});return{id:e.id,name:e.name,allowedOrigins:e.allowedOrigins,webhookUrl:e.webhookUrl,vaultContractAddress:e.vaultContractAddress,clientId:e.clientId}}async listApplicationOrders(e){return await this.makeBackendRequest(ae.applications.orders(e))}async listApplicationUsers(e){return await this.makeBackendRequest(ae.applications.users(e))}async listApplicationMovements(e){return await this.makeBackendRequest(ae.applications.movements(e))}async listApplicationBalances(e){return await this.makeBackendRequest(ae.applications.balances(e))}async getApplicationStats(e){return await this.makeBackendRequest(ae.applications.stats(e))}}var xde=T({applicationId:b().uuid(),enrolled:ue(),payoutAddress:b().nullable().optional(),buildercodesEnabled:ue(),buildercodesBudgetBps:M().int().min(0).max(1e4)}),wA=T({page:M().int().min(1).max(1e4).optional(),pageSize:M().int().min(1).max(100).optional()}),zU=T({tradeId:b().uuid(),payoutAddress:b(),token:b(),amount:b(),appliedBps:M().int(),createdAt:b()}),_de=T({payouts:Ce(zU),total:M().int().nonnegative(),page:M().int().positive(),pageSize:M().int().positive(),totalPages:M().int().nonnegative()}),BU=T({token:b(),totalAmount:b(),payoutCount:M().int().nonnegative(),lastCreditedAt:b()}),wde=T({totalPayouts:M().int().nonnegative(),lastCreditedAt:b().nullable().optional(),byToken:Ce(BU)}),LU=T({token:b(),available:b()}),Sde=T({balances:Ce(LU)}),SA=T({token:b().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:b().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),vde=T({payoutBalance:b(),tradingBalance:b()});var vA=T({tradingPairId:b().trim().min(1,"Trading pair ID is required and cannot be empty"),side:G(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:b().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:b().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:G(["LIMIT","MARKET"]).optional(),slippageToleranceBps:M().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:Go.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),Tde=T({applicationName:b().nullable().optional(),applicationTakerFee:b(),applicationTakerFeeBps:M(),buyOrderLockAmount:b().nullable().optional(),makerTotalReceipt:b(),monacoMakerRebate:b(),monacoMakerRebateBps:M(),monacoMakerRebateBpsExact:b(),monacoTakerFee:b(),monacoTakerFeeBps:M(),monacoTakerFeeBpsExact:b(),notional:b(),takerTotalPayment:b(),totalTakerFees:b(),maxQuantity:b().nullable(),maxQuantityRaw:b().nullable(),slippageToleranceBps:M().nullable()}),TA=T({tradingPairId:b().trim().min(1,"Trading pair ID is required and cannot be empty")}),DU=T({tierLevel:M().int(),minVolumeThreshold:b(),makerFeeBps:b(),takerFeeBps:b()}),Ede=T({currentTierLevel:M().int(),weightedVolume14d:b(),spotVolume14d:b(),perpVolume14d:b(),volumeToNextTier:b().nullable().optional(),nextTierLevel:M().int().nullable().optional(),feeSchedule:Ce(DU)});var UU=T({token:b(),available:b()}),Pde=T({balances:Ce(UU)}),Ade=T({code:b(),createdAt:b(),customCode:b(),isCustom:ue(),display:b()}),FU=G(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Ide=T({available:ue(),reason:Bp((e)=>e===""||e===null?void 0:e,FU.optional())}),EA=T({code:b().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")}),kde=T({code:b()}),PA=T({token:b().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:b().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Rde=T({rewardsBalance:b(),tradingBalance:b()});var Nb=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];class jU extends Error{issues;constructor(e){let t=e.issues.map((r)=>{let n=r.path.join(".");return`${n?`${n}: `:""}${r.message}`});super(`Validation failed:
|
|
150
150
|
- ${t.join(`
|
|
151
|
-
- `)}`);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 ye(e,t){let r=e.safeParse(t);if(!r.success)throw new jU(r.error);return r.data}var Il=G(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),km=G(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),Db=G(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Rm=G(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),qU=G(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),AA=G(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Wc=G(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),kl=G(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),ut=b().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"}),Ie=R5({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),ka=Ou.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),HU=M().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Om=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),Ode=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),zb=T({triggerPrice:ut,orderType:kl,limitPrice:ut.optional(),quantity:ut.optional(),closePosition:ue().optional(),timeInForce:AA.optional(),slippageToleranceBps:Om.optional(),expiresAt:ka.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"]}),Bb=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,IA=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),kA=b().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),GU=T({tradingPairId:Ie,side:Il,quantity:ut,price:ut,options:T({idempotencyKey:kA.optional(),tradingMode:km.optional(),useMasterBalance:ue().optional(),expirationDate:ka.optional(),timeInForce:qU.optional(),marginAccountId:Ie.optional(),marginMode:Db.optional(),riskBucketId:Ie.optional(),riskBucketCollateral:ut.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:Rm.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional(),takeProfit:zb.optional(),stopLoss:zb.optional()}).optional()}).refine((e)=>IA(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)=>!Bb(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!Bb(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),VU=T({tradingPairId:Ie,side:Il,quantity:ut,options:T({idempotencyKey:kA.optional(),tradingMode:km.optional(),slippageTolerance:HU,marginAccountId:Ie.optional(),marginMode:Db.optional(),riskBucketId:Ie.optional(),riskBucketCollateral:ut.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:Rm.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),selfTradePreventionMode:Wc.optional(),takeProfit:zb.optional(),stopLoss:zb.optional()}).optional()}).refine((e)=>IA(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)=>!Bb(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!Bb(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),ZU=T({orderId:Ie,remainingQuantityTarget:ut.optional()}),WU=T({orderId:Ie,newOrder:T({price:ut.optional(),quantity:ut.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()})}),KU=T({status:st([G(Nb),Ce(G(Nb)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Ie.optional(),tradingMode:km.optional(),marginAccountId:Ie.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:b().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Go.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),oIt=G(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),iIt=G(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),Cde=G(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),sIt=G(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),RA=T({conditionalOrderId:Ie}),YU=T({marginAccountId:Ie.optional(),tradingPairId:Ie.optional(),state:Cde.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Mde=G(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),$de=st([M().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),b().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Nde=2592000000,JU=T({tradingPairId:Ie,side:Il,quantity:ut,options:T({durationSeconds:$de.optional(),startTime:ka.optional(),endTime:ka.optional(),limitPrice:ut.optional(),slippageToleranceBps:Ode.optional(),randomize:ue().optional(),executionStyle:G(["TAKER","PASSIVE"]).optional(),reduceOnly:ue().optional(),tradingMode:km.optional(),marginAccountId:Ie.optional(),riskBucketId:Ie.optional(),marginMode:Db.optional(),leverage:ut.optional(),strategyKey:b().min(1).max(128).optional(),useMasterBalance:ue().optional(),clientTwapId:b().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:ut.optional(),triggerDirection:G(["ABOVE","BELOW"]).optional(),conditionalExpiry:ka.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).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()<=Nde},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),Ub=T({twapOrderId:Ie}),QU=T({state:Mde.optional(),tradingPairId:Ie.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),zde=T({tradingPairId:Ie,orderType:kl,side:Il,price:ut.optional(),quantity:ut,idempotencyKey:kA.optional(),tradingMode:km.optional(),slippageTolerance:HU,useMasterBalance:ue().optional(),expirationDate:ka.optional(),timeInForce:qU.optional(),marginAccountId:Ie.optional(),marginMode:Db.optional(),riskBucketId:Ie.optional(),riskBucketCollateral:ut.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:Rm.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>IA(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"]}),Lb=100,XU=T({orders:Ce(zde).min(1,"At least one order is required").max(Lb,`At most ${Lb} orders per batch request`)}),Bde=T({orderId:Ie,price:ut.optional(),quantity:ut.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),eF=T({orders:Ce(Bde).min(1,"At least one order is required").max(Lb,`At most ${Lb} orders per batch request`)});var OA=T({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),tF=OA.extend({state:b().trim().min(1,"State cannot be empty").optional(),tradingPairId:Ie.optional()}),rF=T({marginAccountId:Ie,tradingPairId:Ie.optional()}),nF=T({tradingPairId:Ie.optional()}).optional(),oF=T({asset:b().trim().min(1,"Asset cannot be empty").optional()}).optional(),Lde=T({asset:b().trim().min(1,"Asset cannot be empty"),amount:ut,tradingPairId:Ie.optional(),strategyKey:b().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:G(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),Fb=T({asset:b().trim().min(1,"Asset cannot be empty"),amount:ut}),Dde=T({tradingPairId:Ie,strategyKey:b().trim().min(1,"Strategy key cannot be empty").optional()}),Ude=Ce(Ie).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),iF=Dde.extend({marginMode:_e("ISOLATED").optional(),selectedTradingPairIds:uo().optional(),applyToPositionMargin:ue().optional()}),Fde=T({marginMode:_e("CROSS"),selectedTradingPairIds:Ude,strategyKey:uo().optional()}),jde=T({marginMode:_e("CROSS"),selectedTradingPairIds:uo().optional(),strategyKey:uo().optional(),tradingPairId:uo().optional()}),CA=T({marginAccountId:Ie,request:Lde}),sF=T({request:Fb}),qde=T({marginMode:G(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.marginMode==="CROSS"&&e.selectedTradingPairIds!==void 0)t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare"})}),aF=T({request:qde.pipe(st([Fb.merge(iF).strict(),Fb.merge(jde).strict()]))}),cF=T({request:Fb}),uF=OA.extend({marginAccountId:Ie,movementType:b().trim().min(1,"Movement type cannot be empty").optional()}),dF=OA.extend({movementType:b().trim().min(1,"Movement type cannot be empty").optional()}).optional(),MA=T({tradingPairId:Ie,side:Il,positionSide:Rm.optional(),orderType:kl,price:ut.optional(),quantity:ut,leverage:ut.optional(),reduceOnly:ue().optional()}),$A=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:Go.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:Go.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},lF=MA.strict().superRefine($A),Hde=MA.merge(iF).strict().superRefine($A),Gde=MA.merge(Fde).strict().superRefine($A).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),Vde=st([Hde,Gde]),pF=T({marginAccountId:Ie,request:lF}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),fF=T({request:lF}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),mF=T({request:Vde}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var hF=G(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),Zde=31536000000,Wde=946684800000,jb=M().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(Wde,{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()+Zde,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),fIt=T({tradingPairId:Ie,interval:hF,startTime:jb,endTime:jb}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),mIt=b().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")'}),Kde=M().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),gF=T({tradingPairId:Ie,interval:hF,startTime:jb.optional(),endTime:jb.optional(),limit:Kde,priceType:G(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var hIt=T({tradingPairId:Ie}),gIt=T({query:b().min(1,"Search query cannot be empty").optional(),pageSize:M().int().min(1).max(100).optional(),page:M().int().min(1).optional()}),fi=T({tradingPairId:Ie});var bF=T({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Yde=G(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),Jde=G(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),Cm=T({positionId:Ie}),xF=bF.extend({marginAccountId:Ie.optional(),tradingPairId:Ie.optional(),status:Yde.optional()}),_F=Cm,wF=Cm.extend({request:T({closeType:Jde,limitPrice:ut.optional(),slippageToleranceBps:Om.optional(),quantity:ut.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"]}),SF=T({tradingPairId:Ie.optional(),slippageToleranceBps:Om.optional()}),vF=Cm,yF=T({triggerPrice:ut,orderType:kl,limitPrice:ut.optional(),quantity:ut.optional(),closePosition:ue().optional(),timeInForce:AA.optional(),slippageToleranceBps:Om.optional(),expiresAt:ka.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"]}),TF=Cm.extend({request:T({takeProfit:yF.optional(),stopLoss:yF.optional(),oco:ue().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),EF=bF.extend({positionId:Ie.optional(),marginAccountId:Ie.optional(),tradingPairId:Ie.optional(),reductionOnly:ue().optional()}),Qde=G(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),PF=Cm.extend({params:T({interval:Qde,startTime:M().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:M().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 Xde=G(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),ele=G(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),AF=T({mode:Wc}),IF=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:Xde.optional(),transactionType:ele.optional(),assetId:Ie.optional()}),kF=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().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:Ie.optional(),pageToken:b().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Go.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),RF=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:Ie.optional(),positionId:Ie.optional(),marginAccountId:Ie.optional()});var PIt=b().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),NA=st([b().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),C5().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),OF=T({assetId:Ie,amount:NA,autoWait:ue().optional()}),CF=T({assetId:Ie,amount:NA,autoWait:ue().optional(),target:G(["spot","margin"]).optional(),options:T({asErc20:ue().optional()}).optional()}),MF=T({assetId:Ie,amount:NA,destination:b().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:ue().optional(),source:G(["spot","margin"]).optional()}),AIt=T({assetId:Ie});var tle="OPERATIONS_BLOCKED",rle="OVERLOADED";function nle(e){if(!(e instanceof Zt)||!e.retryable)return e;if(!(e.statusCode===void 0||e.statusCode>=500)||ole(e))return e;return e.retryable=!1,e.suggestion="The claim's outcome is unknown: it may have committed after this failure. Do not retry automatically, and do not rely on a balance read to decide — an admitted claim can still be queued, so an unchanged balance does not prove it will not commit. Treat the claim as pending and reconcile before issuing another; this endpoint has no idempotency key, so a retry can claim a second time.",e}function ole(e){let t=e.responseBody;if(t===null||typeof t!=="object")return!1;let{error:r,code:n}=t;return r===tle||n===rle}class qb extends Ve{async getConfig(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/config",{method:"GET"})}async listPayouts(e){if(e)ye(wA,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());let r=t.toString(),n=r?`/api/v1/buildercodes/payouts?${r}`:"/api/v1/buildercodes/payouts";return this.makeAuthenticatedRequest(n,{method:"GET"})}async getPayoutSummary(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/payouts/summary",{method:"GET"})}async getRewardsBalance(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/balance",{method:"GET"})}async claimBuildercodeRewards(e){let t=ye(SA,e);try{return await this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/claim",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}catch(r){throw nle(r)}}}class zA extends Ve{async upsertDelegatedAgent(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.list(),{method:"POST",body:JSON.stringify({agentAddress:e.agentAddress,name:e.name,expiresAt:e.expiresAt,allowedActions:e.allowedActions,allowedTradingPairIds:e.allowedTradingPairIds,allowedMarginAccountIds:e.allowedMarginAccountIds,allowedOrderTypes:e.allowedOrderTypes,allowedTimeInForce:e.allowedTimeInForce,maxLeverage:e.maxLeverage,maxOrderNotional:e.maxOrderNotional,maxOpenOrders:e.maxOpenOrders})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(ae.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(ae.delegatedAgents.owners())}async revokeDelegatedAgent(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.byId(e),{method:"DELETE"})}async createDelegatedSession(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:e.ownerUserId,sessionPublicKey:e.sessionPublicKey})})}}class Hb extends Ve{async mint(e){return await this.makeAuthenticatedRequest(ae.faucet.mint(),{method:"POST",body:JSON.stringify({turnstileToken:e.turnstileToken})})}async getInfo(){return await this.makeAuthenticatedRequest(ae.faucet.info(),{method:"GET"})}}class Gb extends Ve{async simulateFees(e){let t=ye(vA,e),r=new URLSearchParams;if(r.append("tradingPairId",t.tradingPairId),r.append("side",t.side),r.append("price",t.price),r.append("quantity",t.quantity),t.orderType!==void 0)r.append("orderType",t.orderType);if(t.slippageToleranceBps!==void 0)r.append("slippageToleranceBps",String(t.slippageToleranceBps));let n=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}async getMyFeeTier(e){let t=ye(TA,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let n=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}}class Vb extends Ve{async listMarginAccounts(e){if(e)ye(tF,e);return await this.makeAuthenticatedRequest(ae.marginAccounts.list(e?{page:e.page,pageSize:e.pageSize,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return ye(rF,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ae.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return ye(nF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return ye(oF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return ye(CA,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return ye(sF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return ye(aF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,applyToPositionMargin:e.applyToPositionMargin})})}async transferCollateralFromMarginAccount(e,t){return ye(CA,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferOut(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey,marginMode:t.marginMode})})}async transferCollateralFromParentMarginAccount(e){return ye(cF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return ye(uF,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ae.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return ye(dF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return ye(pF,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateOrderRisk(e),{method:"POST",body:JSON.stringify({tradingPairId:t.tradingPairId,side:t.side,positionSide:t.positionSide,orderType:t.orderType,price:t.price,quantity:t.quantity,leverage:t.leverage,reduceOnly:t.reduceOnly})})}async simulateParentMarginOrderRisk(e){return ye(fF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateParentMarginOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}async simulateRiskBucketOrderRisk(e){return ye(mF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}}class Zb extends Ve{async getPaginatedTradingPairs(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.marketType)t.append("marketType",e.marketType);if(e?.baseToken)t.append("baseToken",e.baseToken);if(e?.quoteToken)t.append("quoteToken",e.quoteToken);if(e?.isActive!==void 0)t.append("isActive",e.isActive.toString());if(e?.category)t.append("category",e.category);let r=t.toString(),n=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(n)}async getTradingPair(e){return ye(fi,{tradingPairId:e}),(await this.makePublicRequest(ae.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((n)=>n.symbol===e)}async getCandlesticks(e,t,r){ye(gF,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit,priceType:r?.priceType});let n=new URLSearchParams;if(r?.startTime!==void 0)n.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)n.append("endTime",r.endTime.toString());if(r?.limit!==void 0)n.append("limit",r.limit.toString());if(r?.priceType!==void 0)n.append("priceType",r.priceType);let o=n.toString(),i=o?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${o}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getPerpMarketSummary(e))}async getMarkPrice(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getMarkPrice(e))}async getIndexPrice(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getIndexPrice(e))}async getFundingState(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getFundingState(e))}async listFundingHistory(e,t){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return await this.makePublicRequest(ae.market.listAllFundingHistory(e))}async getOpenInterest(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(ae.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(ae.market.getMarketStats())}}class Wb extends Ve{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:n,magnitude:o,denomination:i}=t,s=new URLSearchParams;if(s.set("levels",String(r)),n)s.set("tradingMode",n);if(o!==void 0)s.set("magnitude",String(o));if(i)s.set("denomination",i.toLowerCase());let a=await this.makePublicRequest(`/api/v1/orderbook/${encodeURIComponent(e)}?${s.toString()}`);return{tradingPairId:a.tradingPairId,tradingMode:a.tradingMode,bids:a.data.bids.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),asks:a.data.asks.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),bestBid:a.data.bestBid,bestAsk:a.data.bestAsk,bidVolume:a.data.bidVolume,askVolume:a.data.askVolume,baseDecimals:a.baseDecimals,quoteDecimals:a.quoteDecimals,timestamp:a.timestamp,sequence:a.sequenceNumber}}}class Kb extends Ve{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me",{method:"GET"})}async setTraderCode(e){let t=ye(EA,{code:e});return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/pitpass/codes/available?${t}`,{method:"GET"});return{available:r.available,reason:r.reason?r.reason:void 0}}async getTraderCodeInfo(e){let t=encodeURIComponent(e.trim());return await this.makePublicRequest(`/api/v1/pitpass/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/balance",{method:"GET"})}async transferRewards(e){let t=ye(PA,e);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}}var Mm="/api/v1/accounts/me/portfolio";function Yb(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class Jb extends Ve{async getSummary(e){return await this.makeAuthenticatedRequest(Yb(`${Mm}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(Yb(`${Mm}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(Yb(`${Mm}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(Yb(`${Mm}/assets`,e))}async getMargin(){return await this.makeAuthenticatedRequest(`${Mm}/margin`)}}class Qb extends Ve{async listPositions(e){if(e)ye(xF,e);return await this.makeAuthenticatedRequest(ae.positions.list(e))}async getPosition(e){return ye(_F,{positionId:e}),await this.makeAuthenticatedRequest(ae.positions.get(e))}async closePosition(e,t){return ye(wF,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ae.positions.close(e),{method:"POST",body:JSON.stringify({closeType:t.closeType,limitPrice:t.limitPrice,slippageToleranceBps:t.slippageToleranceBps,quantity:t.quantity})})}async batchCloseAllPositions(e){if(e)ye(SF,e);return await this.makeAuthenticatedRequest(ae.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return ye(vF,{positionId:e}),await this.makeAuthenticatedRequest(ae.positions.risk(e))}async attachPositionTpSl(e,t){return ye(TF,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ae.positions.attachTpSl(e),{method:"POST",body:JSON.stringify({takeProfit:t.takeProfit?{triggerPrice:t.takeProfit.triggerPrice,orderType:t.takeProfit.orderType,limitPrice:t.takeProfit.limitPrice,quantity:t.takeProfit.quantity,closePosition:t.takeProfit.closePosition,timeInForce:t.takeProfit.timeInForce,slippageToleranceBps:t.takeProfit.slippageToleranceBps,expiresAt:t.takeProfit.expiresAt}:void 0,stopLoss:t.stopLoss?{triggerPrice:t.stopLoss.triggerPrice,orderType:t.stopLoss.orderType,limitPrice:t.stopLoss.limitPrice,quantity:t.stopLoss.quantity,closePosition:t.stopLoss.closePosition,timeInForce:t.stopLoss.timeInForce,slippageToleranceBps:t.stopLoss.slippageToleranceBps,expiresAt:t.stopLoss.expiresAt}:void 0,oco:t.oco})})}async listPositionHistory(e){if(e)ye(EF,e);return await this.makeAuthenticatedRequest(ae.positions.history(e))}async getPositionPnlHistory(e,t){return ye(PF,{positionId:e,params:t}),await this.makeAuthenticatedRequest(ae.positions.pnlHistory(e,t))}}class BA extends Ve{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)ye(IF,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.entryType!==void 0)t.append("entryType",e.entryType);if(e?.transactionType!==void 0)t.append("transactionType",e.transactionType);if(e?.assetId!==void 0)t.append("assetId",e.assetId);let r=t.toString(),n=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(n)}async getUserBalances(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());let r=t.toString(),n=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(n)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new Zt("assetId is required and cannot be empty",{endpoint:"/api/v1/accounts/balances/{assetId}"});let t=`/api/v1/accounts/balances/${e}`;return await this.makeAuthenticatedRequest(t)}async getPortfolioStats(e){let t=new URLSearchParams({period:e});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio?${t}`)}async getPortfolioChart(e,t){let r=new URLSearchParams({period:e,metric:t});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio/chart?${r}`)}async getUserTrades(e){if(e)ye(kF,e);let t=e?.page!==void 0&&e?.pageToken===void 0,r=new URLSearchParams;if(t&&e?.page!==void 0)r.append("page",e.page.toString());if(e?.pageSize!==void 0)r.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)r.append("tradingPairId",e.tradingPairId);if(!t)r.append("pageToken",e?.pageToken??"");let n=r.toString(),o=n?`/api/v1/accounts/trades?${n}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(o)}async*iterateUserTrades(e){let t="";for(;;){let r=await this.getUserTrades({...e,pageToken:t});if(yield*r.trades,!r.nextPageToken)return;t=r.nextPageToken}}async listFundingPayments(e){if(e)ye(RF,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);if(e?.positionId!==void 0)t.append("positionId",e.positionId);if(e?.marginAccountId!==void 0)t.append("marginAccountId",e.marginAccountId);let r=t.toString(),n=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(n)}async getSelfTradePreventionDefault(){return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention")}async setSelfTradePreventionDefault(e){let t=ye(AF,{mode:e});return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention",{method:"PUT",body:JSON.stringify(t)})}}class Xb extends Ve{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class ex extends Ve{async list(){return await this.makeAuthenticatedRequest(ae.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(ae.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(ae.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(ae.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(ae.subAccounts.limit(e,t),{method:"DELETE"})}}function ile(e){if(e==="spot")return"SPOT";if(e==="margin")return"MARGIN";throw new Pt(`Invalid deposit target: ${JSON.stringify(e)}. Expected "spot" or "margin".`)}class tx extends Ve{async register(e={}){let{depositTarget:t,...r}=e,n=t===void 0?r:{...r,depositTarget:ile(t)};return await this.makeAuthenticatedRequest(ae.sweeper.register(),{method:"POST",body:JSON.stringify(n)})}async getChains(){return await this.makePublicRequest(ae.sweeper.chains(),{method:"GET"})}}function $F(e){return{eventType:"trade",tradingPairId:e.tradingPairId,tradingMode:e.tradingMode.toUpperCase(),data:{tradeId:e.data.tradeId,price:e.data.price,quantity:e.data.quantity,makerSide:e.data.makerSide.toUpperCase(),executedAt:e.data.executedAt??""}}}class LA extends Ve{async getTrades(e,t={}){let{page:r=1}=t,n=t.pageSize!=null&&t.pageSize>0?Math.min(t.pageSize,100):25,o=new URLSearchParams;if(r>1)o.set("page",String(r));return o.set("pageSize",String(n)),(await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}?${o.toString()}`)).trades.map($F)}async getTradeById(e){let t=await this.makePublicRequest(ae.trades.byId(e));return $F(t)}}function rx(e){if(!e)return;return{triggerPrice:e.triggerPrice,orderType:e.orderType,limitPrice:e.limitPrice,timeInForce:e.timeInForce,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt,quantity:e.quantity,closePosition:e.closePosition}}class nx extends Ve{async placeLimitOrder(e,t,r,n,o){ye(GU,{tradingPairId:e,side:t,quantity:r,price:n,options:o});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:n,quantity:r,tradingMode:o?.tradingMode||"SPOT",useMasterBalance:o?.useMasterBalance,expirationDate:o?.expirationDate,timeInForce:o?.timeInForce,marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,postOnly:o?.postOnly,selfTradePreventionMode:o?.selfTradePreventionMode,clientOrderId:o?.clientOrderId,idempotencyKey:o?.idempotencyKey===void 0?crypto.randomUUID():o.idempotencyKey,takeProfit:rx(o?.takeProfit),stopLoss:rx(o?.stopLoss)};return await this.makeAuthenticatedRequest(ae.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,n){ye(VU,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:n?.slippageTolerance!==void 0?Math.round(n.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:n?.tradingMode||"SPOT",marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,selfTradePreventionMode:n?.selfTradePreventionMode,takeProfit:rx(n?.takeProfit),stopLoss:rx(n?.stopLoss),clientOrderId:n?.clientOrderId,idempotencyKey:n?.idempotencyKey===void 0?crypto.randomUUID():n.idempotencyKey};return await this.makeAuthenticatedRequest(ae.orders.create(),{method:"POST",body:JSON.stringify(o)})}async cancelOrder(e,t){ye(ZU,{orderId:e,remainingQuantityTarget:t?.remainingQuantityTarget});let r={orderId:e,...t?.remainingQuantityTarget!==void 0&&{remainingQuantityTarget:t.remainingQuantityTarget}};return await this.makeAuthenticatedRequest(ae.orders.cancel(),{method:"POST",body:JSON.stringify(r)})}async cancelConditionalOrder(e){return ye(RA,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return ye(RA,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)ye(YU,e);let{page:t=1,pageSize:r=20,marginAccountId:n,tradingPairId:o,state:i}=e||{};return await this.makeAuthenticatedRequest(ae.orders.listConditional({page:t,pageSize:Math.min(Math.max(r,1),100),marginAccountId:n,tradingPairId:o,state:i}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(ae.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?ae.orders.batchCancelAllByPair(e):ae.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){ye(WU,{orderId:e,newOrder:t});let r={useMasterBalance:t.useMasterBalance??!1};if(t.price!==void 0)r.price=t.price;if(t.quantity!==void 0)r.quantity=t.quantity;if(t.postOnly!==void 0)r.postOnly=t.postOnly;if(t.selfTradePreventionMode!==void 0)r.selfTradePreventionMode=t.selfTradePreventionMode;if(t.clientOrderId!==void 0)r.clientOrderId=t.clientOrderId;return await this.makeAuthenticatedRequest(ae.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){ye(XU,{orders:e});let t={orders:e.map((r)=>({tradingPairId:r.tradingPairId,orderType:r.orderType,side:r.side,price:r.price,quantity:r.quantity,tradingMode:r.tradingMode||"SPOT",slippageToleranceBps:r.slippageTolerance!==void 0?Math.round(r.slippageTolerance*1e4):void 0,useMasterBalance:r.useMasterBalance,expirationDate:r.expirationDate,timeInForce:r.timeInForce,marginAccountId:r.marginAccountId,marginMode:r.marginMode,riskBucketId:r.riskBucketId,riskBucketCollateral:r.riskBucketCollateral,strategyKey:r.strategyKey,positionSide:r.positionSide,leverage:r.leverage,reduceOnly:r.reduceOnly,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId,idempotencyKey:r.idempotencyKey===void 0?crypto.randomUUID():r.idempotencyKey}))};return this.makeAuthenticatedRequest(ae.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){ye(eF,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ae.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)ye(KU,e);let{page:t,pageSize:r=10,status:n,tradingPairId:o,tradingMode:i,marginAccountId:s,pageToken:a}=e||{},c=r>0?r:10,d=t!==void 0&&a===void 0,l=Math.min(c,d?100:1000),p=new URLSearchParams;if(d){let y=t>0?t:1;p.append("page",y.toString())}p.append("pageSize",l.toString());let m=typeof n==="string"?n:n?.join(",");if(m)p.append("status",m);if(o)p.append("tradingPairId",o);if(i)p.append("tradingMode",i);if(s)p.append("marginAccountId",s);if(!d)p.append("pageToken",a??"");let h=`/api/v1/orders?${p.toString()}`;return await this.makeAuthenticatedRequest(h,{method:"GET"})}async*iterateOrders(e){let t="";for(;;){let r=await this.getPaginatedOrders({...e,pageToken:t});if(yield*r.orders,!r.nextPageToken)return;t=r.nextPageToken}}async getOrder(e){return{order:await this.makeAuthenticatedRequest(ae.orders.get(e),{method:"GET"}),status:"SUCCESS"}}async createTwapOrder(e,t,r,n){ye(JU,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,side:t,quantity:r,durationSeconds:n.durationSeconds!==void 0?Number(n.durationSeconds):void 0,startTime:n.startTime,endTime:n.endTime,limitPrice:n.limitPrice,slippageToleranceBps:n.slippageToleranceBps,randomize:n.randomize,reduceOnly:n.reduceOnly,tradingMode:n.tradingMode||"SPOT",marginAccountId:n.marginAccountId,riskBucketId:n.riskBucketId,marginMode:n.marginMode,leverage:n.leverage,strategyKey:n.strategyKey,useMasterBalance:n.useMasterBalance,clientTwapId:n.clientTwapId,executionStyle:n.executionStyle,triggerPrice:n.triggerPrice,triggerDirection:n.triggerDirection,conditionalExpiry:n.conditionalExpiry};return await this.makeAuthenticatedRequest(ae.orders.createTwap(),{method:"POST",body:JSON.stringify(o)})}async cancelTwapOrder(e){return ye(Ub,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.cancelTwap(e),{method:"POST"})}async getTwapOrder(e){return ye(Ub,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getTwap(e),{method:"GET"})}async getTwapOrderTca(e){return ye(Ub,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getTwapTca(e),{method:"GET"})}async listTwapOrders(e){if(e)ye(QU,e);let{page:t=1,pageSize:r=20,state:n,tradingPairId:o}=e||{};return await this.makeAuthenticatedRequest(ae.orders.listTwap({page:t,pageSize:Math.min(Math.max(r,1),100),state:n,tradingPairId:o}),{method:"GET"})}}var DA=[{inputs:[{internalType:"address",name:"factory_",type:"address"},{internalType:"address",name:"unwrapHelper_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ChainNotConfigured",type:"error"},{inputs:[],name:"ComposeNotSupported",type:"error"},{inputs:[],name:"ComposeSourceMismatch",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeNotAccepted",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NoRoute",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotHub",type:"error"},{inputs:[],name:"NotRemote",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[],name:"QuoteNotBound",type:"error"},{inputs:[],name:"RoutedToken",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",type:"error"},{inputs:[],name:"StaleQuote",type:"error"},{inputs:[],name:"SweepParamsRequired",type:"error"},{inputs:[],name:"UnexpectedParams",type:"error"},{inputs:[],name:"UnexpectedValue",type:"error"},{inputs:[],name:"UnswapPathMissing",type:"error"},{inputs:[],name:"UntrustedComposeCaller",type:"error"},{inputs:[],name:"UntrustedComposeSource",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"address",name:"bridgeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"amountBridged",type:"uint256"},{indexed:!1,internalType:"address",name:"destination",type:"address"}],name:"Bridged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Refunded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"RefundedNative",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Swept",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"tokenIn",type:"address"},{indexed:!0,internalType:"address",name:"tokenOut",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountOut",type:"uint256"}],name:"Unswapped",type:"event"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"hubToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{internalType:"contract ISweeperFactory",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"bytes",name:"message",type:"bytes"},{internalType:"address",name:"",type:"address"},{internalType:"bytes",name:"",type:"bytes"}],name:"lzCompose",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{stateMutability:"payable",type:"receive"}];var UA=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[],name:"ImplementationNotSet",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousExecutor",type:"address"},{indexed:!0,internalType:"address",name:"newExecutor",type:"address"}],name:"ExecutorUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"rollup",type:"address"},{indexed:!1,internalType:"address",name:"bridgedStable",type:"address"},{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"address",name:"lzEndpoint",type:"address"}],name:"HubConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"uint32",name:"cctpDestinationDomain",type:"uint32"},{indexed:!1,internalType:"uint32",name:"stargateDestinationEid",type:"uint32"}],name:"RemoteConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],indexed:!1,internalType:"struct BridgeRoute",name:"route",type:"tuple"}],name:"RouteSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"sweeper",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"string",name:"applicationId",type:"string"},{indexed:!1,internalType:"address",name:"hubToken",type:"address"}],name:"SweeperDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousImplementation",type:"address"},{indexed:!0,internalType:"address",name:"newImplementation",type:"address"}],name:"SweeperImplementationUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"stargate",type:"address"},{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"TrustedStargateSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"hubToken",type:"address"},{indexed:!1,internalType:"bytes",name:"path",type:"bytes"}],name:"UnswapPathSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"bridgedStable",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"cctpDestinationDomain",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[],name:"chainMode",outputs:[{internalType:"enum ChainMode",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"rollup_",type:"address"},{internalType:"address",name:"bridgedStable_",type:"address"},{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"address",name:"lzEndpoint_",type:"address"}],name:"configureHub",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"uint32",name:"cctpDestinationDomain_",type:"uint32"},{internalType:"uint32",name:"stargateDestinationEid_",type:"uint32"}],name:"configureRemote",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"deploy",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"deployReceiver",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"executor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"forwarder",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner_",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"lzEndpoint",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"receiverFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"refundToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"route",outputs:[{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"executor_",type:"address"}],name:"setExecutor",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"route_",type:"tuple"}],name:"setRoute",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"setSweeperImplementation",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"setTrustedStargate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"path",type:"bytes"}],name:"setUnswapPath",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"stargateDestinationEid",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"}],name:"stargateToken",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"swapRouter",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweepWithParams",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"sweeperFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"sweeperImplementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"}],name:"unswapPath",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"}];var FA=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AccessControlBadConfirmation",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"bytes32",name:"neededRole",type:"bytes32"}],name:"AccessControlUnauthorizedAccount",type:"error"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"InvalidSeed",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[],name:"InvalidTimestamp",type:"error"},{inputs:[],name:"NonceAlreadyUsed",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[],name:"ReentrancyGuardReentrantCall",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newFeeCollector",type:"address"}],name:"FeeCollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newSettlementContract",type:"address"}],name:"SettlementContractChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"maker",type:"address"},{indexed:!0,internalType:"address",name:"taker",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"fee",type:"uint256"}],name:"SettlementTransfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdrawal",type:"event"},{inputs:[],name:"DEBUGGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"FEE_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PAUSER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"SETTLEMENT_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"seed",type:"bytes"}],name:"decodeSeed",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"depositERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],name:"depositNative",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"feeCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getChainID",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_admin",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"callerConfirmation",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newFeeCollector",type:"address"}],name:"setFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_settlementContract",type:"address"}],name:"setSettlementContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"settlementContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"maker",type:"address"},{internalType:"address",name:"taker",type:"address"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"fee",type:"uint256"}],name:"transferOnSettlement",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdrawNative",outputs:[],stateMutability:"nonpayable",type:"function"}];var l2t=new Uint8Array(32);function ox(e,t){return sle(t),t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}function sle(e){if(e!=="spot"&&e!=="margin")throw Error(`Invalid deposit target: ${JSON.stringify(e)}. `+'Expected "spot" or "margin" — lowercase, not the wire form "SPOT"/"MARGIN".')}var jA={vault:FA,sweeper:DA,sweeperFactory:UA};var ale=5000,cle=300000,ule=(e)=>new Promise((t)=>setTimeout(t,e));class ix extends Ve{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,n,o,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=n,this.profileAPI=o}setWalletClient(e){this.walletClient=e}async getVaultAddress(){return(await this.applicationsAPI.getApplicationConfig()).vaultContractAddress}async getClientId(){return(await this.applicationsAPI.getApplicationConfig()).clientId}async resolveAsset(e){let t,r;try{let n=await this.profileAPI.getUserBalanceByAssetId(e);t=n.token,r=n.wrappedNative===!0}catch(n){if(n instanceof Zt){if(n.statusCode===404)throw new Vi(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:n});throw new Vi(`Failed to resolve asset ID '${e}': ${n.retryable?"Network error occurred":"API request failed"}`,{revertReason:n.retryable?"NETWORK_ERROR":"API_ERROR",cause:n})}throw new Vi(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:n instanceof Error?n:void 0})}return{tokenAddress:t,isWrappedNative:r}}async approve(e,t,r=!0){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");ye(OF,{assetId:e,amount:t,autoWait:r});let n=await this.getVaultAddress(),{tokenAddress:o}=await this.resolveAsset(e),i=this.walletClient.account;if(!i)throw new Pt("No account available in wallet client","account");let s=i.getNonce?await i.getNonce():0n,a=await this.walletClient.writeContract({address:o,abi:Wt,functionName:"approve",args:[n,t],chain:this.chain,account:i}),c={nonce:s,hash:a,status:"pending"};return await this.waitForTransaction(c,r)}async deposit(e,t,r=!0,n="spot",o={}){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");ye(CF,{assetId:e,amount:t,autoWait:r,target:n,options:o});let i=await this.getVaultAddress(),s=await this.getClientId(),a=ox(s,n),{tokenAddress:c,isWrappedNative:d}=await this.resolveAsset(e),l=d&&o.asErc20!==!0;if(!l){if(await this.needsApproval(e,t,o))throw new Vi(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${c}).`,{revertReason:"APPROVAL_REQUIRED"})}let p=this.walletClient.account;if(!p)throw new Pt("No account available in wallet client","account");let m;if(l)m=await this.walletClient.writeContract({address:i,abi:jA.vault,functionName:"depositNative",args:[p.address,a],account:p,chain:this.chain,value:t});else m=await this.walletClient.writeContract({address:i,abi:jA.vault,functionName:"depositERC20",args:[p.address,a,c,t],account:p,chain:this.chain});let h=p.getNonce?await p.getNonce():0n,y={hash:m,status:"pending",nonce:h};return await this.waitForTransaction(y,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??ale,n=t?.timeoutMs??cle,o=Date.now()+n;for(;;){try{let{vaultAddress:i,calldata:s}=await this.makePublicRequest(`/api/v1/withdrawals/${e}`);if(s&&s!=="0x")return{vaultAddress:i,calldata:s}}catch(i){if(!(i instanceof Zt&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>o)return null;await ule(r)}}async withdraw(e,t,r=!0,n,o){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let i=this.walletClient.account;if(!i)throw new Pt("No account available in wallet client","account");let s=i.address.toLowerCase(),a=typeof n==="string"?n:"spot",c=typeof n==="string"?o:n;ye(MF,{assetId:e,amount:t,destination:s,autoWait:r,source:a});let{withdrawalIndex:d}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:s,source:a})});if(!r)return{withdrawalIndex:d,status:"awaiting_proof"};let l=await this.pollWithdrawalCalldata(d,c);if(!l)return{withdrawalIndex:d,status:"awaiting_proof"};let{vaultAddress:p,calldata:m}=l,h;try{h=await this.walletClient.sendTransaction({to:p,data:m,account:i,chain:this.chain})}catch(w){throw new Vi(`Failed to submit executeWithdrawal for withdrawal ${d}: ${w instanceof Error?w.message:"unknown error"}`,{cause:w instanceof Error?w:void 0})}let y=i.getNonce?await i.getNonce():0n,x={hash:h,status:"pending",nonce:y};return{...await this.waitForTransaction(x,r),withdrawalIndex:d}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let n=this.walletClient.account;if(!n)throw new Pt("No account available in wallet client","account");let o=await this.pollWithdrawalCalldata(e,r);if(!o)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:s}=o,a;try{a=await this.walletClient.sendTransaction({to:i,data:s,account:n,chain:this.chain})}catch(p){throw new Vi(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${p instanceof Error?p.message:"unknown error"}`,{cause:p instanceof Error?p:void 0})}let c=n.getNonce?await n.getNonce():0n,d={hash:a,status:"pending",nonce:c};return{...await this.waitForTransaction(d,t),withdrawalIndex:e}}async getBalance(e){throw new Zt("getBalance() is deprecated and no longer supported. Please use profileAPI.getUserBalances() or profileAPI.getUserBalanceByAssetId() instead for balance data.",{statusCode:410})}async getAllowance(e){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let t=await this.getVaultAddress(),n=(await this.walletClient.getAddresses())[0];if(!n)throw new Pt("No account found in wallet client.","walletClient");let{tokenAddress:o}=await this.resolveAsset(e);return await this.publicClient.readContract({address:o,abi:Wt,functionName:"allowance",args:[n,t]})}async needsApproval(e,t,r={}){let{isWrappedNative:n}=await this.resolveAsset(e);if(n&&r.asErc20!==!0)return!1;return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:n=1,timeout:o=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:n,timeout:o});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class sx extends Ve{async submit(e){return await this.makePublicRequest(ae.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class qA extends Ve{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(ae.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:e.assetId,amount:e.amount,destination:e.destination,source:e.source??"spot"})})}async getWithdrawal(e){return this.makePublicRequest(ae.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return this.makeAuthenticatedRequest(ae.withdrawals.list({page:e?.page,pageSize:e?.pageSize}))}}class ax extends Ve{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let r=this.walletClient.account;if(!r)throw new Pt("No account available in wallet client","account");let n=z0(),o={publicKey:B0(n),privateKey:L0(n)},i=await this.createChallenge(r.address,e,o.publicKey),s=await this.signChallenge(i.message);return await this.verifySignature(r.address,s,i.nonce,e,o,t)}async signChallenge(e){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let t=this.walletClient.account;if(!t)throw new Pt("No account available in wallet client","account");return await this.walletClient.signMessage({account:t,message:e})}async createChallenge(e,t,r){let n=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:n.nonce,message:n.message,expiresAt:n.expiresAt}}async verifySignature(e,t,r,n,o,i){let s=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:n,chainId:this.chain.id,sessionPublicKey:o.publicKey,...i?{referralCode:i}:{}})});return{sessionPublicKey:o.publicKey,sessionPrivateKey:o.privateKey,expiresAt:s.expiresAt,user:{id:s.user.id,address:s.user.address,username:s.user.username}}}async refreshSession(){return{expiresAt:(await this.makeAuthenticatedRequest("/api/v1/auth/refresh",{method:"POST"})).expiresAt}}async revokeSession(){await this.makeAuthenticatedRequest("/api/v1/auth/revoke",{method:"POST"})}}var dle=750;function NF(e,t){try{new URL(e)}catch(r){throw new Pt(`${t} must be a valid URL, got: ${e}`,t)}return e}class GA{auth;delegatedAgents;applications;fees;buildercodes;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;whitelist;profile;pulse;orderbook;trades;ws;walletClient;publicClient;authState;network;chain;propagateSession(e){this.auth.setSessionKeypair(e),this.delegatedAgents.setSessionKeypair(e),this.applications.setSessionKeypair(e),this.fees.setSessionKeypair(e),this.buildercodes.setSessionKeypair(e),this.pitpass.setSessionKeypair(e),this.vault.setSessionKeypair(e),this.withdrawals.setSessionKeypair(e),this.trading.setSessionKeypair(e),this.market.setSessionKeypair(e),this.marginAccounts.setSessionKeypair(e),this.positions.setSessionKeypair(e),this.portfolio.setSessionKeypair(e),this.subAccounts.setSessionKeypair(e),this.faucet.setSessionKeypair(e),this.sweeper.setSessionKeypair(e),this.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}setServerKey(e){this.auth.setServerKey(e),this.delegatedAgents.setServerKey(e),this.applications.setServerKey(e),this.fees.setServerKey(e),this.buildercodes.setServerKey(e),this.pitpass.setServerKey(e),this.vault.setServerKey(e),this.withdrawals.setServerKey(e),this.trading.setServerKey(e),this.market.setServerKey(e),this.marginAccounts.setServerKey(e),this.positions.setServerKey(e),this.portfolio.setServerKey(e),this.subAccounts.setServerKey(e),this.faucet.setServerKey(e),this.sweeper.setServerKey(e),this.whitelist.setServerKey(e),this.pulse.setServerKey(e),this.profile.setServerKey(e),this.orderbook.setServerKey(e),this.trades.setServerKey(e)}sessionFromAuthState(e){return{publicKey:e.sessionPublicKey,privateKey:e.sessionPrivateKey}}constructor(e){let t=["mainnet","development","staging","local"];if(!e.network||!t.includes(e.network))throw new Pt(`network must be one of: ${t.join(", ")}. Got: ${e.network}`,"network");if(this.network=e.network,!e.seiRpcUrl)throw new Pt("seiRpcUrl is required","seiRpcUrl");try{new URL(e.seiRpcUrl)}catch(a){throw new Pt(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?NF(e.wsUrl,"wsUrl"):uT(this.network),n=this.network==="mainnet"?Am:Im;if(this.chain=n,e.pollingInterval!==void 0&&(!Number.isFinite(e.pollingInterval)||e.pollingInterval<=0))throw new Pt(`pollingInterval must be a positive number of milliseconds, got: ${e.pollingInterval}`,"pollingInterval");let o=Pm(e.seiRpcUrl);this.publicClient=pA({chain:n,transport:o,pollingInterval:e.pollingInterval??dle});let i=e.apiUrl?NF(e.apiUrl,"apiUrl"):cT(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==n.id)throw new Pt(`Wallet client chain mismatch. Expected ${n.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}let s=(a)=>(a.setRequestSigning(e.requestSigning??"legacy"),a);this.applications=s(new $b(i)),this.market=s(new Zb(i)),this.marginAccounts=s(new Vb(i)),this.positions=s(new Qb(i)),this.portfolio=s(new Jb(i)),this.subAccounts=s(new ex(i)),this.faucet=s(new Hb(i)),this.sweeper=s(new tx(i)),this.whitelist=s(new sx(i)),this.pulse=s(new Xb(i)),this.auth=s(new ax(this.walletClient,this.chain,i)),this.delegatedAgents=s(new zA(i)),this.fees=s(new Gb(i)),this.buildercodes=s(new qb(i)),this.pitpass=s(new Kb(i)),this.profile=s(new BA(i)),this.vault=s(new ix(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i)),this.withdrawals=s(new qA(i)),this.trading=s(new nx(i)),this.orderbook=s(new Wb(i)),this.trades=s(new LA(i)),this.ws=tT(r,e.ws),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new Zt("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:HA.StatusCodes.UNAUTHORIZED});let t=z0(),r={publicKey:B0(t),privateKey:L0(t)},n=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:n.expiresAt,user:{id:n.ownerUserId,address:n.agentAddress}},this.propagateSession(this.sessionFromAuthState(this.authState)),this.authState}getAuthState(){return this.authState}setAuthState(e){this.authState=e,this.propagateSession(this.sessionFromAuthState(e))}async logout(){if(this.authState)try{await this.auth.revokeSession()}catch(e){console.warn("Failed to revoke session on logout:",e)}this.authState=void 0,this.propagateSession(void 0),this.ws.disconnect()}async refreshAuth(){if(!this.authState)throw new Zt("No active session to refresh",{endpoint:"auth/refresh",statusCode:HA.StatusCodes.UNAUTHORIZED});try{let e=await this.auth.refreshSession();return this.authState={...this.authState,expiresAt:e.expiresAt},this.authState}catch(e){throw this.authState=void 0,this.propagateSession(void 0),e}}isAuthenticated(){return!!this.authState}isConnected(){return!!this.walletClient&&!!this.publicClient}setWalletClient(e){if(e.chain?.id!==this.chain.id)throw new Pt(`Wallet client chain mismatch. Expected ${this.chain.id}, got ${e.chain?.id}`,"walletClient");this.walletClient=e,this.auth.setWalletClient(e),this.vault.setWalletClient(e)}getAccountAddress(){if(!this.walletClient)throw new Of("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new Of("No account available","account")}getNetwork(){return this.network}getChainId(){return this.chain.id}async waitForTransaction(e,t,r){return this.publicClient.waitForTransactionReceipt({hash:e,confirmations:t,timeout:r})}}function VA(e){return new GA(e)}hm();Fe();ei();Cn();function zF(e){if(typeof e==="string"){if(!ht(e,{strict:!1}))throw new Ft({address:e});return{address:e,type:"json-rpc"}}if(!ht(e.address,{strict:!1}))throw new Ft({address:e.address});return{address:e.address,nonceManager:e.nonceManager,sign:e.sign,signAuthorization:e.signAuthorization,signMessage:e.signMessage,signTransaction:e.signTransaction,signTypedData:e.signTypedData,source:"custom",type:"local"}}hm();xr();Fe();var ZA=!1;async function mi({hash:e,privateKey:t,to:r="object"}){let{r:n,s:o,recovery:i}=hs.sign(e.slice(2),t.slice(2),{lowS:!0,extraEntropy:Kt(ZA,{strict:!1})?pr(ZA):ZA}),s={r:H(n,{size:32}),s:H(o,{size:32}),v:i?28n:27n,yParity:i};return(()=>{if(r==="bytes"||r==="hex")return yb({...s,to:r});return s})()}async function BF(e){let{chainId:t,nonce:r,privateKey:n,to:o="object"}=e,i=e.contractAddress??e.address,s=await mi({hash:Yy({address:i,chainId:t,nonce:r}),privateKey:n,to:o});if(o==="object")return{address:i,chainId:t,nonce:r,...s};return s}async function LF({message:e,privateKey:t}){return await mi({hash:gl(e),privateKey:t,to:"hex"})}Kn();on();Fe();function DF(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...i}=r,s=r.address;t.push([n?Jt(n):"0x",s,o?Jt(o):"0x",...Rl({},i)])}return t}Fe();QE();ei();He();Jf();ls();Cn();mn();Ji();lr();function UF(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!ht(o))throw new Ft({address:o});if(n<0)throw new md({chainId:n})}cx(e)}function FF(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new bm;for(let r of t){let n=et(r),o=Yt(gn(r,0,1));if(n!==32)throw new wP({hash:r,size:n});if(o!==Xy)throw new SP({hash:r,version:o})}}cx(e)}function cx(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new md({chainId:t});if(o&&!ht(o))throw new Ft({address:o});if(n&&n>Kd)throw new Ro({maxFeePerGas:n});if(r&&n&&r>n)throw new ds({maxFeePerGas:n,maxPriorityFeePerGas:r})}function jF(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(t<=0)throw new md({chainId:t});if(i&&!ht(i))throw new Ft({address:i});if(r||o)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Kd)throw new Ro({maxFeePerGas:n})}function qF(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(i&&!ht(i))throw new Ft({address:i});if(typeof t<"u"&&t<=0)throw new md({chainId:t});if(r||o)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Kd)throw new Ro({maxFeePerGas:n})}ei();on();Cn();function $m(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:o}=e[r];for(let i=0;i<o.length;i++)if(o[i].length-2!==64)throw new TE({storageKey:o[i]});if(!ht(n,{strict:!1}))throw new Ft({address:n});t.push([n,o])}return t}function HF(e,t){let r=tb(e);if(r==="eip1559")return fle(e,t);if(r==="eip2930")return mle(e,t);if(r==="eip4844")return ple(e,t);if(r==="eip7702")return lle(e,t);return hle(e,t)}function lle(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:i,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:l,data:p}=e;UF(e);let m=$m(l),h=DF(r);return Qt(["0x04",gs([H(n),i?H(i):"0x",d?H(d):"0x",c?H(c):"0x",o?H(o):"0x",s??"0x",a?H(a):"0x",p??"0x",m,h,...Rl(e,t)])])}function ple(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:l,data:p}=e;FF(e);let{blobVersionedHashes:m,sidecars:h}=e;if(e.blobs&&(typeof m>"u"||typeof h>"u")){let S=typeof e.blobs[0]==="string"?e.blobs:e.blobs.map((k)=>mt(k)),v=e.kzg,P=el({blobs:S,kzg:v});if(typeof m>"u")m=Qy({commitments:P});if(typeof h>"u"){let k=tl({blobs:S,commitments:P,kzg:v});h=eb({blobs:S,commitments:P,proofs:k})}}let y=$m(l),x=[H(r),o?H(o):"0x",d?H(d):"0x",c?H(c):"0x",n?H(n):"0x",i??"0x",s?H(s):"0x",p??"0x",y,a?H(a):"0x",m??[],...Rl(e,t)],_=[],w=[],A=[];if(h)for(let S=0;S<h.length;S++){let{blob:v,commitment:P,proof:k}=h[S];_.push(v),w.push(P),A.push(k)}return Qt(["0x03",h?gs([x,_,w,A]):gs(x)])}function fle(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:d,data:l}=e;cx(e);let p=$m(d),m=[H(r),o?H(o):"0x",c?H(c):"0x",a?H(a):"0x",n?H(n):"0x",i??"0x",s?H(s):"0x",l??"0x",p,...Rl(e,t)];return Qt(["0x02",gs(m)])}function mle(e,t){let{chainId:r,gas:n,data:o,nonce:i,to:s,value:a,accessList:c,gasPrice:d}=e;jF(e);let l=$m(c),p=[H(r),i?H(i):"0x",d?H(d):"0x",n?H(n):"0x",s??"0x",a?H(a):"0x",o??"0x",l,...Rl(e,t)];return Qt(["0x01",gs(p)])}function hle(e,t){let{chainId:r=0,gas:n,data:o,nonce:i,to:s,value:a,gasPrice:c}=e;qF(e);let d=[i?H(i):"0x",c?H(c):"0x",n?H(n):"0x",s??"0x",a?H(a):"0x",o??"0x"];if(t){let l=(()=>{if(t.v>=35n){if((t.v-35n)/2n>0)return t.v;return 27n+(t.v===35n?0n:1n)}if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let h=27n+(t.v===27n?0n:1n);if(t.v!==h)throw new SE({v:t.v});return h})(),p=$r(t.r),m=$r(t.s);d=[...d,H(l),p==="0x00"?"0x":p,m==="0x00"?"0x":m]}else if(r>0)d=[...d,H(r),"0x","0x"];return gs(d)}function Rl(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let i=$r(r.r),s=$r(r.s);return[(()=>{if(typeof o==="number")return o?H(1):"0x";if(n===0n)return"0x";if(n===1n)return H(1);return n===27n?"0x":H(1)})(),i==="0x00"?"0x":i,s==="0x00"?"0x":s]}async function GF(e){let{privateKey:t,transaction:r,serializer:n=HF}=e,o=(()=>{if(r.type==="eip4844")return{...r,sidecars:!1};return r})(),i=await mi({hash:St(await n(o)),privateKey:t});return await n(r,i)}async function VF(e){let{privateKey:t,...r}=e;return await mi({hash:_b(r),privateKey:t,to:"hex"})}function WA(e,t={}){let{nonceManager:r}=t,n=Jt(hs.getPublicKey(e.slice(2),!1)),o=Ky(n);return{...zF({address:o,nonceManager:r,async sign({hash:s}){return mi({hash:s,privateKey:e,to:"hex"})},async signAuthorization(s){return BF({...s,privateKey:e})},async signMessage({message:s}){return LF({message:s,privateKey:e})},async signTransaction(s,{serializer:a}={}){return GF({privateKey:e,transaction:s,serializer:a})},async signTypedData(s){return VF({...s,privateKey:e})}}),publicKey:n,source:"privateKey"}}var KA=null;var gle={privateKeyToAccount:WA,createWalletClient:gA,http:Pm,createMonacoSDK:VA,sei:Am,seiTestnet:Im};function yle(e,t=gle){let r=e.network==="mainnet"?t.sei:t.seiTestnet,n;if(e.privateKey){let o=t.privateKeyToAccount(e.privateKey);n=t.createWalletClient({account:o,chain:r,transport:t.http(e.seiRpcUrl)})}return t.createMonacoSDK({walletClient:n,network:e.network,seiRpcUrl:e.seiRpcUrl})}function Ze(e){if(!KA){let t=e??lc();KA=yle(t)}return KA}var ble=60,ux=null;function xle(){return Math.floor(Date.now()/1000)}function ZF(e){return e-ble<=xle()}function _le(e){for(let t=e,r=0;t instanceof Error&&r<5;r++){if(t instanceof Zt&&t.statusCode===401)return!0;t=t.cause}return!1}function YA(e){if(!ux)ux=e().finally(()=>{ux=null});return ux}async function WF(e,t){if(await e.login(t.clientId),t.delegatedOwnerUserId){try{let r=await e.loginAsDelegatedOwner(t.delegatedOwnerUserId);console.error(`Adopted delegated owner ${r.user.id} (session expires at ${new Date(r.expiresAt*1000).toISOString()})`)}catch(r){throw await e.logout().catch(()=>{}),r}return}console.error(`Authenticated as ${e.getAccountAddress()}`)}async function KF(e,t){try{await e.refreshAuth()}catch{await WF(e,t)}}async function X(e){let t=Ze(e),r=e??lc(),n=t.getAuthState(),o=r.delegatedOwnerUserId!=null&&n?.user?.id!==r.delegatedOwnerUserId;if(!n||o)return await YA(()=>WF(t,r)),t;if(ZF(n.expiresAt))await YA(()=>KF(t,r));return t}async function wle(e){let t=e??lc();if(!t.privateKey)return!1;let r=Ze(e);return await YA(()=>KF(r,t)),!0}function YF(e,t){async function r(...n){let o=Ze(t).getAuthState(),i=o!==void 0&&!ZF(o.expiresAt);try{return await e(...n)}catch(s){if(!_le(s))throw s;if(!(i&&Ze(t).getAuthState()!==o)){if(!await wle(t))throw s}return await e(...n)}}return r}function L(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function dx(e){return{content:[{type:"text",text:e}]}}function JF(e,t){if(t.network==="mainnet")return;e.registerTool("get_faucet_info",{description:"Get the authenticated wallet's faucet quota: remaining requests in the rolling 24h window, when the next request becomes available, and the 5 most recent faucet requests. Check this before request_faucet to avoid rate-limit errors. Only available on non-mainnet networks (development, staging, local).",inputSchema:{}},async()=>{let n=await(await X()).faucet.getInfo();return L(n)})}function QF(e,t){if(t.network==="mainnet")return;e.registerTool("request_faucet",{description:"Request test funds from the faucet for all active trading pairs. Requires a Cloudflare Turnstile token (the faucet rejects requests without one). Only available on non-mainnet networks (development, staging, local).",inputSchema:T({turnstileToken:b().describe("Cloudflare Turnstile token proving the request came from a real client (required by the faucet).")})},async({turnstileToken:r})=>{let o=await(await X()).faucet.mint({turnstileToken:r});return L(o)})}function XF(e,t){QF(e,t),JF(e,t)}function ej(e){e.registerTool("get_my_fee_tier",{description:"Get the authenticated user's current fee tier, rolling 14-day volumes (with spot/perp breakdown), the volume needed to reach the next tier, and the requested pair's six-row fee schedule.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:t})=>{let n=await(await X()).fees.getMyFeeTier({tradingPairId:t});return L(n)})}function tj(e){e.registerTool("simulate_fees",{description:"Simulate the fees for an order before placing it. Returns Monaco protocol fees, application fees, and total amounts.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side"),price:b().describe("Price per unit as a decimal string"),quantity:b().describe("Quantity to trade as a decimal string")})},async({tradingPairId:t,side:r,price:n,quantity:o})=>{let s=await(await X()).fees.simulateFees({tradingPairId:t,side:r,price:n,quantity:o});return L(s)})}function rj(e){tj(e),ej(e)}function nj(e){e.registerTool("get_available_collateral",{description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",inputSchema:T({asset:b().optional().describe("Optional collateral asset symbol or ID to scope the query")})},async({asset:t})=>{let n=await(await X()).marginAccounts.getAvailableCollateral({asset:t});return L(n)})}function oj(e){e.registerTool("get_margin_accounts",{description:"List your margin accounts with optional filters (state, trading pair).",inputSchema:T({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),state:b().optional().describe("Filter by margin account state"),tradingPairId:b().optional().describe("Filter by trading pair UUID")})},async({page:t,pageSize:r,state:n,tradingPairId:o})=>{let s=await(await X()).marginAccounts.listMarginAccounts({page:t,pageSize:r,state:n,tradingPairId:o});return L(s)})}function ij(e){e.registerTool("get_parent_margin_account_movements",{description:"List collateral movements for your parent (cross) margin account.",inputSchema:T({movementType:b().optional().describe("Filter by movement type"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({movementType:t,page:r,pageSize:n})=>{let i=await(await X()).marginAccounts.getParentMarginAccountMovements({movementType:t,page:r,pageSize:n});return L(i)})}function sj(e){e.registerTool("get_parent_margin_account_summary",{description:"Get your parent (cross) margin account summary.",inputSchema:T({tradingPairId:b().optional().describe("Optional trading pair UUID to scope the summary")})},async({tradingPairId:t})=>{let n=await(await X()).marginAccounts.getParentMarginAccountSummary({tradingPairId:t});return L(n)})}function aj(e){e.registerTool("simulate_parent_margin_order_risk",{description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:G(["LIMIT","MARKET"]).describe("Order type"),quantity:b().describe("Order quantity as a decimal string"),price:b().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:b().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:ue().optional().describe("Whether the order can only reduce exposure")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]})},async({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a})=>{let d=await(await X()).marginAccounts.simulateParentMarginOrderRisk({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a});return L(d)})}function cj(e){e.registerTool("simulate_risk_bucket_order_risk",{description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:G(["LIMIT","MARKET"]).describe("Order type"),quantity:b().describe("Order quantity as a decimal string"),price:b().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:b().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:ue().optional().describe("Whether the order can only reduce exposure"),marginMode:G(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),strategyKey:b().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),selectedTradingPairIds:Ce(b()).optional().describe("Cross risk bucket trading pair UUIDs (CROSS only; must include tradingPairId)")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.marginMode!=="CROSS"||t.selectedTradingPairIds!==void 0&&t.selectedTradingPairIds.length>0,{message:"selectedTradingPairIds is required for CROSS risk buckets",path:["selectedTradingPairIds"]}).refine((t)=>t.marginMode!=="CROSS"||t.selectedTradingPairIds?.includes(t.tradingPairId),{message:"selectedTradingPairIds must include tradingPairId for CROSS risk buckets",path:["selectedTradingPairIds"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode==="CROSS"||t.selectedTradingPairIds===void 0,{message:"selectedTradingPairIds is only allowed for CROSS risk buckets",path:["selectedTradingPairIds"]})},async({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a,marginMode:c,strategyKey:d,selectedTradingPairIds:l})=>{let p=await X(),m={tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a},h=c==="CROSS"?await p.marginAccounts.simulateRiskBucketOrderRisk({...m,marginMode:c,selectedTradingPairIds:l??[]}):await p.marginAccounts.simulateRiskBucketOrderRisk({...m,marginMode:c,strategyKey:d});return L(h)})}function uj(e){e.registerTool("transfer_collateral_from_parent_margin_account",{description:"Move collateral out of your parent (cross) margin account back to spot.",inputSchema:T({asset:b().describe("Collateral asset symbol or ID"),amount:b().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await X()).marginAccounts.transferCollateralFromParentMarginAccount({asset:t,amount:r});return L(o)})}function dj(e){e.registerTool("transfer_collateral_to_parent_margin_account",{description:"Move collateral from spot into your parent (cross) margin account.",inputSchema:T({asset:b().describe("Collateral asset symbol or ID"),amount:b().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await X()).marginAccounts.transferCollateralToParentMarginAccount({asset:t,amount:r});return L(o)})}function lj(e){e.registerTool("transfer_collateral_to_risk_bucket",{description:"Allocate collateral into an isolated or cross risk bucket. A cross transfer names no pairs: cross scope is derived from trading (a pair joins the cross bucket when a cross order on it succeeds and leaves when its positions close).",inputSchema:T({asset:b().describe("Collateral asset symbol or ID"),amount:b().describe("Amount to transfer as a decimal string"),marginMode:G(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),tradingPairId:b().optional().describe("Trading pair UUID (required for ISOLATED; not allowed for CROSS)"),strategyKey:b().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),applyToPositionMargin:ue().optional().describe("ISOLATED only. Omitted/true (Adjust Margin, the default): commit the amount to the sole open position's stored margin — leverage drops and stays down, initial margin required rises, free collateral is unchanged. false: plain allocation — free collateral rises and the next order can spend it; funding loops targeting free collateral MUST pass false.")}).strict().refine((t)=>t.marginMode==="CROSS"||t.tradingPairId!==void 0,{message:"tradingPairId is required for ISOLATED risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.tradingPairId===void 0,{message:"tradingPairId is not allowed for CROSS risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode!=="CROSS"||t.applyToPositionMargin===void 0,{message:"applyToPositionMargin is only allowed for ISOLATED risk buckets",path:["applyToPositionMargin"]})},async({asset:t,amount:r,marginMode:n,tradingPairId:o,strategyKey:i,applyToPositionMargin:s})=>{let a=await X(),c=n==="CROSS"?await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n}):await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n,tradingPairId:o??"",strategyKey:i,applyToPositionMargin:s});return L(c)})}function pj(e){oj(e),sj(e),nj(e),ij(e),aj(e),cj(e),dj(e),uj(e),lj(e)}function fj(e){e.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),interval:G(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:M().optional().describe("Start time as Unix timestamp (seconds)"),endTime:M().optional().describe("End time as Unix timestamp (seconds)"),limit:M().optional().describe("Max number of candlesticks to return")})},async({tradingPairId:t,interval:r,startTime:n,endTime:o,limit:i})=>{let a=await Ze().market.getCandlesticks(t,r,{startTime:n,endTime:o,limit:i});return L(a)})}function mj(e){e.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getMarketMetadata(t);return L(n)})}function hj(e){e.registerTool("get_market_stats",{description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets."},async()=>{let r=await Ze().market.getMarketStats();return L(r)})}function gj(e){e.registerTool("get_screener",{description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",inputSchema:T({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),marketType:G(["SPOT","MARGIN"]).optional().describe("Filter by market type"),isActive:ue().optional().describe("Filter by active status"),category:b().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async({page:t,pageSize:r,marketType:n,isActive:o,category:i})=>{let a=await Ze().market.getScreener({page:t,pageSize:r,marketType:n,isActive:o,category:i});return L(a)})}function yj(e){e.registerTool("get_trading_pair_by_symbol",{description:"Look up a specific trading pair by its symbol (e.g. 'BTC/USDC'). Returns the pair's full details including its UUID.",inputSchema:T({symbol:b().describe("Trading pair symbol (e.g. 'BTC/USDC')")})},async({symbol:t})=>{let n=await Ze().market.getTradingPairBySymbol(t);if(!n)return dx(`Trading pair '${t}' not found.`);return L(n)})}function bj(e){e.registerTool("get_trading_pairs",{description:"Get a paginated list of trading pairs available on Monaco. Returns pair IDs, symbols, base/quote tokens, and status.",inputSchema:T({page:M().optional().describe("Page number (starts from 1)"),pageSize:M().optional().describe("Number of items per page (max 100)"),marketType:G(["SPOT","MARGIN"]).optional().describe("Filter by market type"),baseToken:b().optional().describe("Filter by base token"),quoteToken:b().optional().describe("Filter by quote token"),isActive:ue().optional().describe("Filter by active status"),category:b().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async(t)=>{let n=await Ze().market.getPaginatedTradingPairs(t);return L(n)})}function xj(e){bj(e),yj(e),fj(e),mj(e),gj(e),hj(e)}function _j(e){e.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),depth:M().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:G(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:M().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:G(["BASE","QUOTE"]).optional().describe("Quantity denomination: BASE or QUOTE")})},async({tradingPairId:t,depth:r,tradingMode:n,magnitude:o,denomination:i})=>{let a=await Ze().orderbook.getOrderbook(t,{depth:r,tradingMode:n,magnitude:o,denomination:i});return L(a)})}function wj(e){_j(e)}function Sj(e){e.registerTool("get_all_funding_history",{description:"List historical funding-rate records across all perpetual markets.",inputSchema:T({startTime:b().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:b().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),orderBy:G(["ASC","DESC"]).optional().describe("Sort order by time")})},async({startTime:t,endTime:r,page:n,pageSize:o,orderBy:i})=>{let a=await Ze().market.listAllFundingHistory({startTime:t,endTime:r,page:n,pageSize:o,orderBy:i});return L(a)})}function vj(e){e.registerTool("get_funding_history",{description:"List historical funding-rate records for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),startTime:b().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:b().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),orderBy:G(["ASC","DESC"]).optional().describe("Sort order by time")})},async({tradingPairId:t,startTime:r,endTime:n,page:o,pageSize:i,orderBy:s})=>{let c=await Ze().market.listFundingHistory(t,{startTime:r,endTime:n,page:o,pageSize:i,orderBy:s});return L(c)})}function Tj(e){e.registerTool("get_funding_state",{description:"Get the current funding rate and next funding time for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getFundingState(t);return L(n)})}function Ej(e){e.registerTool("get_index_price",{description:"Get the current index (oracle) price for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getIndexPrice(t);return L(n)})}function Pj(e){e.registerTool("get_mark_price",{description:"Get the current mark price for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getMarkPrice(t);return L(n)})}function Aj(e){e.registerTool("get_open_interest",{description:"Get the current open interest for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getOpenInterest(t);return L(n)})}function Ij(e){e.registerTool("get_perp_market_config",{description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getPerpMarketConfig(t);return L(n)})}function kj(e){e.registerTool("get_perp_market_summary",{description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getPerpMarketSummary(t);return L(n)})}function Rj(e){Ij(e),kj(e),Pj(e),Ej(e),Tj(e),Aj(e),vj(e),Sj(e)}function Oj(e){e.registerTool("check_trader_code_availability",{description:"Public advisory check of whether a custom PitPass TraderCode handle is available. Returns `available` and, when unavailable, a `reason` (one of taken, too_short, too_long, reserved, invalid_char, looks_like_address). Advisory only — the authoritative gate is the atomic claim in set_trader_code, so a positive result is not a reservation.",inputSchema:T({code:b().describe("The custom handle to check for availability.")})},async({code:t})=>{let n=await Ze().pitpass.checkTraderCodeAvailability(t);return L(n)})}function Cj(e){e.registerTool("clear_trader_code",{description:"Clear the authenticated caller's custom PitPass TraderCode handle, reverting to the wallet-derived default. The freed handle enters a cooldown before anyone else can claim it. Returns the caller's TraderCode identity after the revert.",inputSchema:T({})},async()=>{let r=await(await X()).pitpass.clearTraderCode();return L(r)})}function Mj(e){e.registerTool("get_my_trader_code",{description:"Return the authenticated caller's PitPass TraderCode — their normalized wallet address. Clients render it as `Monaco - <address>`. Never 404s; ensures the backing row so referrals attributed to this wallet link correctly.",inputSchema:T({})},async()=>{let r=await(await X()).pitpass.getMyTraderCode();return L(r)})}function $j(e){e.registerTool("get_rewards_balance",{description:"Return the authenticated caller's current PitPass rewards-bucket balances across all reward tokens. Returns an empty list when no rewards have been earned yet. Use transfer_rewards to move earned rewards into a tradeable balance.",inputSchema:T({})},async()=>{let r=await(await X()).pitpass.getRewardsBalance();return L(r)})}function Nj(e){e.registerTool("get_trader_code_info",{description:"Public lookup of a PitPass TraderCode (wallet address or 'Monaco - <address>' form). Returns the resolved normalized code when it belongs to a known wallet, or a 404 error if not found. Use this to validate a referral code before sign-up.",inputSchema:T({code:b().describe("The TraderCode to look up — a wallet address (0x-prefixed) or the 'Monaco - <address>' display form.")})},async({code:t})=>{let n=await Ze().pitpass.getTraderCodeInfo(t);return L(n)})}function zj(e){e.registerTool("set_trader_code",{description:"Claim or edit the authenticated caller's custom (vanity) PitPass TraderCode handle. Stored exactly as entered (case preserved); uniqueness is case-insensitive. Must start with a letter and be 5–20 characters of letters, digits, or underscores. The server is the authoritative gate: 409 if the handle is taken, 422 on validation failure, 429 when the per-hour edit limit is hit, 403 when the feature is disabled.",inputSchema:T({code:b().describe("The custom handle to claim or edit to — letter-first [A-Za-z0-9_], 5–20 characters. Case is preserved.")})},async({code:t})=>{let n=await(await X()).pitpass.setTraderCode(t);return L(n)})}function Bj(e){e.registerTool("transfer_rewards",{description:"Transfer earned PitPass rewards from your rewards bucket into your trading balance, making them immediately tradeable. Ledger-only — no on-chain transaction. Fails if the rewards balance is insufficient.",inputSchema:T({token:b().describe("Reward token contract address (0x-prefixed EVM address) to transfer."),amount:b().describe("Amount to transfer in RAW atomic units of the token (positive integer string).")})},async({token:t,amount:r})=>{let o=await(await X()).pitpass.transferRewards({token:t,amount:r});return L(o)})}function Lj(e){Nj(e),Oj(e)}function Dj(e){Mj(e),$j(e),Bj(e),zj(e),Cj(e)}function Uj(e){e.registerTool("get_portfolio_assets",{description:"Get your per-asset portfolio allocation and balances over a period.",inputSchema:T({period:G(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getAssets({period:t});return L(n)})}function Fj(e){e.registerTool("get_portfolio_margin",{description:"Get your portfolio margin overview (collateral, maintenance margin, health)."},async()=>{let r=await(await X()).portfolio.getMargin();return L(r)})}function jj(e){e.registerTool("get_portfolio_performance",{description:"Get your portfolio performance time series over a period.",inputSchema:T({period:G(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getPerformance({period:t});return L(n)})}function qj(e){e.registerTool("get_portfolio_realized_pnl",{description:"Get your realized PnL breakdown over a period.",inputSchema:T({period:G(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getRealizedPnl({period:t});return L(n)})}function Hj(e){e.registerTool("get_portfolio_summary",{description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",inputSchema:T({period:G(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getSummary({period:t});return L(n)})}function Gj(e){Hj(e),jj(e),qj(e),Uj(e),Fj(e)}function Vj(e){e.registerTool("close_position",{description:"Close a perpetual position with a market, limit, or IOC reduce order.",inputSchema:T({positionId:b().describe("Position UUID"),closeType:G(["MARKET","LIMIT","IOC"]).describe("Close order type"),limitPrice:b().optional().describe("Limit price as a decimal string — required for LIMIT and IOC, not allowed for MARKET"),slippageToleranceBps:M().optional().describe("Slippage tolerance in basis points (MARKET/IOC)"),quantity:b().optional().describe("Quantity to close as a decimal string (defaults to full position)")}).refine((t)=>t.closeType==="MARKET"||t.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["limitPrice"]}).refine((t)=>t.closeType!=="MARKET"||t.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["limitPrice"]})},async({positionId:t,closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i})=>{let a=await(await X()).positions.closePosition(t,{closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i});return L(a)})}function Zj(e){e.registerTool("get_position",{description:"Get details for a specific perpetual position by ID.",inputSchema:T({positionId:b().describe("Position UUID")})},async({positionId:t})=>{let n=await(await X()).positions.getPosition(t);return L(n)})}function Wj(e){e.registerTool("get_position_history",{description:"List historical (closed/reduced) perpetual position records with optional filters.",inputSchema:T({positionId:b().optional().describe("Filter by position UUID"),marginAccountId:b().optional().describe("Filter by margin account UUID"),tradingPairId:b().optional().describe("Filter by trading pair UUID"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),reductionOnly:ue().optional().describe("Only include reduction events")})},async({positionId:t,marginAccountId:r,tradingPairId:n,page:o,pageSize:i,reductionOnly:s})=>{let c=await(await X()).positions.listPositionHistory({positionId:t,marginAccountId:r,tradingPairId:n,page:o,pageSize:i,reductionOnly:s});return L(c)})}function Kj(e){e.registerTool("get_position_pnl_history",{description:"Get the PnL history time series for a perpetual position over an interval.",inputSchema:T({positionId:b().describe("Position UUID"),interval:G(["1m","5m","15m","1h","4h","1d"]).describe("Sampling interval"),startTime:M().int().min(0).optional().describe("Start time as a Unix timestamp in milliseconds"),endTime:M().int().min(0).optional().describe("End time as a Unix timestamp in milliseconds")}).refine((t)=>t.startTime===void 0||t.endTime===void 0||t.startTime<t.endTime,{message:"startTime must be less than endTime",path:["startTime"]})},async({positionId:t,interval:r,startTime:n,endTime:o})=>{let s=await(await X()).positions.getPositionPnlHistory(t,{interval:r,startTime:n,endTime:o});return L(s)})}function Yj(e){e.registerTool("get_position_risk",{description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",inputSchema:T({positionId:b().describe("Position UUID")})},async({positionId:t})=>{let n=await(await X()).positions.getPositionRisk(t);return L(n)})}function Jj(e){e.registerTool("get_positions",{description:"List your perpetual positions with optional filters (margin account, trading pair, status).",inputSchema:T({marginAccountId:b().optional().describe("Filter by margin account UUID"),tradingPairId:b().optional().describe("Filter by trading pair UUID"),status:G(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"]).optional().describe("Filter by position status"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({marginAccountId:t,tradingPairId:r,status:n,page:o,pageSize:i})=>{let a=await(await X()).positions.listPositions({marginAccountId:t,tradingPairId:r,status:n,page:o,pageSize:i});return L(a)})}function Qj(e){Jj(e),Zj(e),Yj(e),Wj(e),Kj(e),Vj(e)}function Xj(e){e.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:T({assetId:b().describe("The asset UUID")})},async({assetId:t})=>{let n=await(await X()).profile.getUserBalanceByAssetId(t);return L(n)})}function eq(e){e.registerTool("get_balances",{description:"Get the authenticated user's token balances with pagination.",inputSchema:T({page:M().optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().optional().describe("Number of items per page (default: 20, max: 100)")})},async({page:t,pageSize:r})=>{let o=await(await X()).profile.getUserBalances({page:t,pageSize:r});return L(o)})}function tq(e){e.registerTool("get_funding_payments",{description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",inputSchema:T({tradingPairId:b().optional().describe("Filter by trading pair UUID"),positionId:b().optional().describe("Filter by position UUID"),marginAccountId:b().optional().describe("Filter by margin account UUID"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({tradingPairId:t,positionId:r,marginAccountId:n,page:o,pageSize:i})=>{let a=await(await X()).profile.listFundingPayments({tradingPairId:t,positionId:r,marginAccountId:n,page:o,pageSize:i});return L(a)})}function rq(e){e.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history) with pagination.",inputSchema:T({page:M().int().min(1).optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().int().min(1).max(100).optional().describe("Items per page (default: 20, max: 100)"),entryType:G(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:G(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"]).optional().describe("Filter by transaction type (e.g. DEPOSIT, WITHDRAWAL, TRADE, FEE, FUNDING, LIQUIDATION, INTEREST, REWARD)"),assetId:b().uuid().optional().describe("Filter by asset ID (UUID)")})},async({page:t,pageSize:r,entryType:n,transactionType:o,assetId:i})=>{let a=await(await X()).profile.getPaginatedUserMovements({page:t,pageSize:r,entryType:n,transactionType:o,assetId:i});return L(a)})}function nq(e){e.registerTool("get_profile",{description:"Get the authenticated user's profile including address, username, account type, and withdrawal status. Use get_balances, get_movements, and get_orders for detailed account data."},async()=>{let r=await(await X()).profile.getProfile();return L(r)})}function oq(e){e.registerTool("get_user_trades",{description:"List your own trade fills with optional filters and cursor pagination.",inputSchema:T({tradingPairId:b().optional().describe("Filter by trading pair UUID"),pageSize:M().optional().describe("Items per page"),pageToken:b().optional().describe("Cursor for the next page"),page:M().optional().describe("Page number (legacy offset mode; prefer pageToken)")})},async({tradingPairId:t,pageSize:r,pageToken:n,page:o})=>{let s=await(await X()).profile.getUserTrades({tradingPairId:t,pageSize:r,pageToken:n,page:o});return L(s)})}function iq(e){nq(e),eq(e),Xj(e),rq(e),oq(e),tq(e)}function sq(e){e.registerTool("get_pulse",{description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags."},async()=>{let r=await Ze().pulse.getPulse();return L(r)})}function aq(e){sq(e)}var Sle="https://docs.0xmonaco.com/mcp",vle="SearchMonacoDocs",lx=null;async function cq(e,t,r){let n=await fetch(Sle,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...lx?{"Mcp-Session-Id":lx}:{}},body:JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t})});if(!n.ok)throw Error(`Mintlify MCP error: ${n.status}`);let o=n.headers.get("mcp-session-id");if(o)lx=o;let s=(await n.text()).split(`
|
|
152
|
-
`).find((a)=>a.startsWith("data: "));if(!s)throw Error("No data in Mintlify MCP response");return JSON.parse(s.slice(6))}async function Tle(){if(lx)return;await cq("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:w0.version}},0)}async function Ele(e){return await Tle(),(await cq("tools/call",{name:vle,arguments:{query:e}},1))?.result}function uq(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:T({query:b().describe("The search query")})},async({query:t})=>{try{let r=await Ele(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return L(r)}catch(r){return dx(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function dq(e){uq(e)}function lq(e){e.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),page:M().optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:t,page:r,pageSize:n})=>{let i=await Ze().trades.getTrades(t,{page:r,pageSize:n});return L(i)})}function pq(e){lq(e)}function fq(e){e.registerTool("batch_cancel_all_orders",{description:"Cancel EVERY one of your open orders in one call. Destructive and unfiltered by default — with no tradingPairId it cancels your entire open-order book across all pairs; pass a tradingPairId to limit it to that pair.",inputSchema:T({tradingPairId:b().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let n=await(await X()).trading.batchCancelAll(t);return L(n)})}function mq(e){e.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request. Non-atomic and best-effort: each order is cancelled independently, so a failed leg does not stop the others. Inspect the per-order results and reconcile (retry or re-check) any that did not cancel.",inputSchema:T({orderIds:Ce(b()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let n=await(await X()).trading.batchCancel(t);return L(n)})}function hq(e){e.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to a specific trading pair. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:T({tradingPairId:b().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:M().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:t,slippageToleranceBps:r})=>{let o=await(await X()).positions.batchCloseAllPositions({tradingPairId:t,slippageToleranceBps:r});return L(o)})}function gq(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:T({orderId:b().describe("The order ID to cancel")})},async({orderId:t})=>{let n=await(await X()).trading.cancelOrder(t);return L(n)})}function yq(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:T({orderId:b().describe("The order ID to look up")})},async({orderId:t})=>{let n=await(await X()).trading.getOrder(t);return L(n)})}var Ple=T({applicationId:b().uuid(),enrolled:ue(),payoutAddress:b().nullable().optional(),buildercodesEnabled:ue(),buildercodesBudgetBps:M().int().min(0).max(1e4)}),Ale=T({page:M().int().min(1).max(1e4).optional(),pageSize:M().int().min(1).max(100).optional()}),bq=T({tradeId:b().uuid(),payoutAddress:b(),token:b(),amount:b(),appliedBps:M().int(),createdAt:b()}),Ile=T({payouts:Ce(bq),total:M().int().nonnegative(),page:M().int().positive(),pageSize:M().int().positive(),totalPages:M().int().nonnegative()}),xq=T({token:b(),totalAmount:b(),payoutCount:M().int().nonnegative(),lastCreditedAt:b()}),kle=T({totalPayouts:M().int().nonnegative(),lastCreditedAt:b().nullable().optional(),byToken:Ce(xq)}),_q=T({token:b(),available:b()}),Rle=T({balances:Ce(_q)}),Ole=T({token:b().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:b().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Cle=T({payoutBalance:b(),tradingBalance:b()});var Mle=T({tradingPairId:b().trim().min(1,"Trading pair ID is required and cannot be empty"),side:G(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:b().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:b().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:G(["LIMIT","MARKET"]).optional(),slippageToleranceBps:M().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:Go.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),$le=T({applicationName:b().nullable().optional(),applicationTakerFee:b(),applicationTakerFeeBps:M(),buyOrderLockAmount:b().nullable().optional(),makerTotalReceipt:b(),monacoMakerRebate:b(),monacoMakerRebateBps:M(),monacoMakerRebateBpsExact:b(),monacoTakerFee:b(),monacoTakerFeeBps:M(),monacoTakerFeeBpsExact:b(),notional:b(),takerTotalPayment:b(),totalTakerFees:b(),maxQuantity:b().nullable(),maxQuantityRaw:b().nullable(),slippageToleranceBps:M().nullable()}),Nle=T({tradingPairId:b().trim().min(1,"Trading pair ID is required and cannot be empty")}),wq=T({tierLevel:M().int(),minVolumeThreshold:b(),makerFeeBps:b(),takerFeeBps:b()}),zle=T({currentTierLevel:M().int(),weightedVolume14d:b(),spotVolume14d:b(),perpVolume14d:b(),volumeToNextTier:b().nullable().optional(),nextTierLevel:M().int().nullable().optional(),feeSchedule:Ce(wq)});var Sq=T({token:b(),available:b()}),Ble=T({balances:Ce(Sq)}),Lle=T({code:b(),createdAt:b(),customCode:b(),isCustom:ue(),display:b()}),vq=G(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Dle=T({available:ue(),reason:Bp((e)=>e===""||e===null?void 0:e,vq.optional())}),Ule=T({code:b().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")}),Fle=T({code:b()}),jle=T({token:b().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:b().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),qle=T({rewardsBalance:b(),tradingBalance:b()});var Ol=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Cl=G(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),Nm=G(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),hx=G(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),zm=G(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),Tq=G(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),JA=G(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Kc=G(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Ml=G(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),dt=b().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"}),ke=R5({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Ra=Ou.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),Eq=M().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Bm=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),Hle=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),px=T({triggerPrice:dt,orderType:Ml,limitPrice:dt.optional(),quantity:dt.optional(),closePosition:ue().optional(),timeInForce:JA.optional(),slippageToleranceBps:Bm.optional(),expiresAt:Ra.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"]}),fx=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,QA=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),XA=b().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),gzt=T({tradingPairId:ke,side:Cl,quantity:dt,price:dt,options:T({idempotencyKey:XA.optional(),tradingMode:Nm.optional(),useMasterBalance:ue().optional(),expirationDate:Ra.optional(),timeInForce:Tq.optional(),marginAccountId:ke.optional(),marginMode:hx.optional(),riskBucketId:ke.optional(),riskBucketCollateral:dt.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:zm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional(),takeProfit:px.optional(),stopLoss:px.optional()}).optional()}).refine((e)=>QA(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)=>!fx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!fx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),yzt=T({tradingPairId:ke,side:Cl,quantity:dt,options:T({idempotencyKey:XA.optional(),tradingMode:Nm.optional(),slippageTolerance:Eq,marginAccountId:ke.optional(),marginMode:hx.optional(),riskBucketId:ke.optional(),riskBucketCollateral:dt.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:zm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),selfTradePreventionMode:Kc.optional(),takeProfit:px.optional(),stopLoss:px.optional()}).optional()}).refine((e)=>QA(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)=>!fx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!fx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),bzt=T({orderId:ke,remainingQuantityTarget:dt.optional()}),xzt=T({orderId:ke,newOrder:T({price:dt.optional(),quantity:dt.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()})}),_zt=T({status:st([G(Ol),Ce(G(Ol)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:ke.optional(),tradingMode:Nm.optional(),marginAccountId:ke.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:b().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Go.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),wzt=G(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),Szt=G(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),Gle=G(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),vzt=G(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),Tzt=T({conditionalOrderId:ke}),Ezt=T({marginAccountId:ke.optional(),tradingPairId:ke.optional(),state:Gle.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Vle=G(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),Zle=st([M().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),b().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Wle=2592000000,Pzt=T({tradingPairId:ke,side:Cl,quantity:dt,options:T({durationSeconds:Zle.optional(),startTime:Ra.optional(),endTime:Ra.optional(),limitPrice:dt.optional(),slippageToleranceBps:Hle.optional(),randomize:ue().optional(),executionStyle:G(["TAKER","PASSIVE"]).optional(),reduceOnly:ue().optional(),tradingMode:Nm.optional(),marginAccountId:ke.optional(),riskBucketId:ke.optional(),marginMode:hx.optional(),leverage:dt.optional(),strategyKey:b().min(1).max(128).optional(),useMasterBalance:ue().optional(),clientTwapId:b().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:dt.optional(),triggerDirection:G(["ABOVE","BELOW"]).optional(),conditionalExpiry:Ra.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).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()<=Wle},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),Azt=T({twapOrderId:ke}),Izt=T({state:Vle.optional(),tradingPairId:ke.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Kle=T({tradingPairId:ke,orderType:Ml,side:Cl,price:dt.optional(),quantity:dt,idempotencyKey:XA.optional(),tradingMode:Nm.optional(),slippageTolerance:Eq,useMasterBalance:ue().optional(),expirationDate:Ra.optional(),timeInForce:Tq.optional(),marginAccountId:ke.optional(),marginMode:hx.optional(),riskBucketId:ke.optional(),riskBucketCollateral:dt.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:zm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>QA(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"]}),mx=100,kzt=T({orders:Ce(Kle).min(1,"At least one order is required").max(mx,`At most ${mx} orders per batch request`)}),Yle=T({orderId:ke,price:dt.optional(),quantity:dt.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),Rzt=T({orders:Ce(Yle).min(1,"At least one order is required").max(mx,`At most ${mx} orders per batch request`)});var eI=T({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),$zt=eI.extend({state:b().trim().min(1,"State cannot be empty").optional(),tradingPairId:ke.optional()}),Nzt=T({marginAccountId:ke,tradingPairId:ke.optional()}),zzt=T({tradingPairId:ke.optional()}).optional(),Bzt=T({asset:b().trim().min(1,"Asset cannot be empty").optional()}).optional(),Jle=T({asset:b().trim().min(1,"Asset cannot be empty"),amount:dt,tradingPairId:ke.optional(),strategyKey:b().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:G(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),gx=T({asset:b().trim().min(1,"Asset cannot be empty"),amount:dt}),Qle=T({tradingPairId:ke,strategyKey:b().trim().min(1,"Strategy key cannot be empty").optional()}),Xle=Ce(ke).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),Pq=Qle.extend({marginMode:_e("ISOLATED").optional(),selectedTradingPairIds:uo().optional(),applyToPositionMargin:ue().optional()}),epe=T({marginMode:_e("CROSS"),selectedTradingPairIds:Xle,strategyKey:uo().optional()}),tpe=T({marginMode:_e("CROSS"),selectedTradingPairIds:uo().optional(),strategyKey:uo().optional(),tradingPairId:uo().optional()}),Lzt=T({marginAccountId:ke,request:Jle}),Dzt=T({request:gx}),rpe=T({marginMode:G(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.marginMode==="CROSS"&&e.selectedTradingPairIds!==void 0)t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare"})}),Uzt=T({request:rpe.pipe(st([gx.merge(Pq).strict(),gx.merge(tpe).strict()]))}),Fzt=T({request:gx}),jzt=eI.extend({marginAccountId:ke,movementType:b().trim().min(1,"Movement type cannot be empty").optional()}),qzt=eI.extend({movementType:b().trim().min(1,"Movement type cannot be empty").optional()}).optional(),tI=T({tradingPairId:ke,side:Cl,positionSide:zm.optional(),orderType:Ml,price:dt.optional(),quantity:dt,leverage:dt.optional(),reduceOnly:ue().optional()}),rI=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:Go.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:Go.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},Aq=tI.strict().superRefine(rI),npe=tI.merge(Pq).strict().superRefine(rI),ope=tI.merge(epe).strict().superRefine(rI).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),ipe=st([npe,ope]),Hzt=T({marginAccountId:ke,request:Aq}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Gzt=T({request:Aq}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Vzt=T({request:ipe}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var Iq=G(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),spe=31536000000,ape=946684800000,yx=M().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(ape,{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()+spe,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),Yzt=T({tradingPairId:ke,interval:Iq,startTime:yx,endTime:yx}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),Jzt=b().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")'}),cpe=M().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),Qzt=T({tradingPairId:ke,interval:Iq,startTime:yx.optional(),endTime:yx.optional(),limit:cpe,priceType:G(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var Xzt=T({tradingPairId:ke}),eBt=T({query:b().min(1,"Search query cannot be empty").optional(),pageSize:M().int().min(1).max(100).optional(),page:M().int().min(1).optional()}),tBt=T({tradingPairId:ke});var Rq=T({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),upe=G(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),dpe=G(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),nI=T({positionId:ke}),iBt=Rq.extend({marginAccountId:ke.optional(),tradingPairId:ke.optional(),status:upe.optional()});var sBt=nI.extend({request:T({closeType:dpe,limitPrice:dt.optional(),slippageToleranceBps:Bm.optional(),quantity:dt.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"]}),aBt=T({tradingPairId:ke.optional(),slippageToleranceBps:Bm.optional()});var kq=T({triggerPrice:dt,orderType:Ml,limitPrice:dt.optional(),quantity:dt.optional(),closePosition:ue().optional(),timeInForce:JA.optional(),slippageToleranceBps:Bm.optional(),expiresAt:Ra.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"]}),cBt=nI.extend({request:T({takeProfit:kq.optional(),stopLoss:kq.optional(),oco:ue().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),uBt=Rq.extend({positionId:ke.optional(),marginAccountId:ke.optional(),tradingPairId:ke.optional(),reductionOnly:ue().optional()}),lpe=G(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),dBt=nI.extend({params:T({interval:lpe,startTime:M().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:M().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 ppe=G(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),fpe=G(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),mBt=T({mode:Kc}),hBt=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:ppe.optional(),transactionType:fpe.optional(),assetId:ke.optional()}),gBt=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().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:ke.optional(),pageToken:b().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Go.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),yBt=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:ke.optional(),positionId:ke.optional(),marginAccountId:ke.optional()});var wBt=b().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),oI=st([b().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),C5().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),SBt=T({assetId:ke,amount:oI,autoWait:ue().optional()}),vBt=T({assetId:ke,amount:oI,autoWait:ue().optional(),target:G(["spot","margin"]).optional(),options:T({asErc20:ue().optional()}).optional()}),TBt=T({assetId:ke,amount:oI,destination:b().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:ue().optional(),source:G(["spot","margin"]).optional()}),EBt=T({assetId:ke});function Oq(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit both page and pageToken for the newest orders; pass the previous response's nextPageToken to fetch the next page. A response with zero orders and an empty nextPageToken means the walk is exhausted. Cursor responses have no exact totals (total/totalPages are 0).",inputSchema:T({status:G(Ol).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:b().optional().describe("Filter by trading pair UUID"),page:M().optional().describe("Deprecated: page number for legacy offset pagination, which only sees recent history. Use pageToken instead."),pageSize:M().optional().describe("Orders per page (default: 10; max 100 in legacy page mode, up to 1000 with pageToken)"),pageToken:b().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it (and page) to start from the newest orders.")})},async({status:t,tradingPairId:r,page:n,pageSize:o,pageToken:i})=>{let a=await(await X()).trading.getPaginatedOrders({status:t,tradingPairId:r,page:n,pageSize:o,pageToken:i});return L(a)})}function Cq(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. Limit orders execute only when the market reaches the specified price. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side"),quantity:b().describe("Order quantity as a decimal string"),price:b().describe("Limit price as a decimal string"),tradingMode:G(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:G(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:b().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:b().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:G(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:b().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:b().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:b().optional().describe("Optional client strategy key"),positionSide:G(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:b().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:ue().optional().describe("Whether the order can only reduce existing exposure"),postOnly:ue().optional().describe("Maker-only: rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if this order would cross the book. GTC time in force only; rejected with IOC/FOK."),selfTradePreventionMode:G(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Per-order self-trade-prevention override for matches against your own resting orders. CANCEL_MAKER cancels your resting orders and keeps matching; CANCEL_TAKER cancels this order's remainder at the first self-touch; CANCEL_BOTH does both; SKIP trades around your orders and cancels a remainder that would cross them. Omitted, your wallet default applies, else the platform default CANCEL_MAKER. Echoed back as selfTradePreventionMode on order reads."),idempotencyKey:b().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:b().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests, and is released on fill/cancel/expiry/rejection, so a marketable order that fills on arrival never takes it. Never resubmit on a lost response without the original idempotencyKey — a resubmission can execute a second time. Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,price:o,tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:d,riskBucketId:l,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:_,selfTradePreventionMode:w,clientOrderId:A,idempotencyKey:S})=>{let P=await(await X()).trading.placeLimitOrder(t,r,n,o,{tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:d,riskBucketId:l,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:_,selfTradePreventionMode:w,clientOrderId:A,idempotencyKey:S});return L(P)})}function Mq(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. It executes immediately against resting liquidity, but only inside a mandatory 1,000 bps (10%) server-side protective price band anchored to the mark/last-trade reference price. Fills stop at the edge of the band, so a market order may partially fill and cancel the remainder, be rejected when no liquidity sits inside the band, or be rejected when the market has no trustworthy price anchor. Optional slippageTolerance is merged tighter-wins with this band: it can only TIGHTEN execution, never widen past the mandatory band; omitting it applies the full 1,000 bps band. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side"),quantity:b().describe("Order quantity as a decimal string"),tradingMode:G(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:M().optional().describe("Tightens the mandatory 1,000 bps band, as a decimal (e.g. 0.01 for 1%; 0 for best price only). Can only tighten, never widen; omit to apply the full band."),marginAccountId:b().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:G(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:b().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:b().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:b().optional().describe("Optional client strategy key"),positionSide:G(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:b().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:ue().optional().describe("Whether the order can only reduce existing exposure"),idempotencyKey:b().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:b().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key. A market order never rests, so it never claims the handle and no duplicate-submission guard can fire for it: Without idempotencyKey, NEVER resubmit a market order on a lost response — it can execute again and increase your exposure (or reject, or fill at a different price; you cannot tell which in advance). Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:d,strategyKey:l,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y,idempotencyKey:x})=>{let w=await(await X()).trading.placeMarketOrder(t,r,n,{tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:d,strategyKey:l,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y,idempotencyKey:x});return L(w)})}function $q(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent, and MCP has no order-stream tool, so an ambiguous outcome (timeout, network error, or a 5xx with no order returned) CANNOT be resolved from inside MCP: do NOT retry. get_orders/get_order are replica-backed and an order rejected before acceptance is never written to them, so a missing row is not evidence the order failed. Check whether the position or balance moved, and otherwise report the ambiguity to the user rather than resubmitting. A retry here cannot double your exposure — replace names the original order id and a second attempt returns ORDER_NOT_FOUND once the first succeeded — but that code does not distinguish a landed replacement from an original that filled or was cancelled, so retrying still reports the wrong state.",inputSchema:T({orderId:b().describe("The order ID to replace"),price:b().optional().describe("New price as a decimal string"),quantity:b().optional().describe("New quantity as a decimal string"),postOnly:ue().optional().describe("Re-states maker-only intent for the replacement (nothing is inherited from the original order): rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if it would cross the book."),selfTradePreventionMode:G(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Re-states the per-order self-trade-prevention override for the replacement (nothing is inherited from the original order). Omitted, your wallet default applies, else the platform default CANCEL_MAKER."),clientOrderId:b().optional().describe("Client-assigned correlation handle for the replacement order, echoed back on order reads and order WebSocket events. Nothing is inherited from the original order — re-state it here to keep the handle across a requote. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests and is released on fill/cancel/expiry/rejection, so it cannot make a lost-response retry safe. Reconciling a lost response needs the order WebSocket stream, which is outside MCP — this server exposes no stream tool.")})},async({orderId:t,price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s})=>{let c=await(await X()).trading.replaceOrder(t,{price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s});return L(c)})}function Nq(e){Cq(e),Mq(e),gq(e),mq(e),fq(e),hq(e),$q(e),Oq(e),yq(e)}function zq(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:T({assetId:b().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let n=await(await X()).vault.getAllowance(t);return L({assetId:t,allowance:n.toString()})})}function Bq(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:T({assetId:b().describe("The asset UUID to approve"),amount:b().regex(/^\d+$/,"Must be a non-negative integer string").describe("Max amount to approve as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.approve(t,BigInt(r));return L({hash:o.hash,status:o.status})})}function Lq(e){e.registerTool("vault_deposit",{description:"Deposit tokens into the Monaco vault. Requires prior approval for ERC20 tokens (use vault_approve first). Set target to 'margin' to route the deposit straight into margin collateral instead of the spot wallet.",inputSchema:T({assetId:b().describe("The asset UUID to deposit"),amount:b().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to deposit as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)"),target:G(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:n})=>{let i=await(await X()).vault.deposit(t,BigInt(r),void 0,n);return L({hash:i.hash,status:i.status})})}function Dq(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:T({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({page:t,pageSize:r})=>{let o=await(await X()).withdrawals.listPendingWithdrawals({page:t,pageSize:r});return L(o)})}function Uq(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:T({assetId:b().describe("The asset UUID to check"),amount:b().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.needsApproval(t,BigInt(r));return L({assetId:t,amount:r,needs_approval:o})})}function Fq(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:T({assetId:b().describe("The asset UUID to withdraw"),amount:b().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to withdraw as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.withdraw(t,BigInt(r));return L({withdrawalIndex:o.withdrawalIndex,status:o.status,hash:o.hash})})}function jq(e){Bq(e),Lq(e),Fq(e),zq(e),Uq(e),Dq(e)}function mpe(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let n=YF(r);return[...e.slice(0,t),n]}function hpe(e,t){let[r,...n]=t;if(!r||typeof r!=="object")return t;let o=B4(e);if(!o)return t;let i=r.annotations;return[{...r,annotations:{...o,...i}},...n]}function qq(e,t,r){return new Proxy(e,{get(n,o,i){if(o==="registerTool")return(a,...c)=>{if(!j4(a,t))return;let d=hpe(a,c);if(r&&F4(a))d=mpe(d);return n.registerTool(a,...d)};let s=Reflect.get(n,o,i);return typeof s==="function"?s.bind(n):s}})}function Hq(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},n=qq(e,r,!1);if(dq(n),xj(n),Rj(n),wj(n),pq(n),Lj(n),aq(n),t.authenticated){let o=qq(e,r,!0);Nq(o),Qj(o),iq(o),Gj(o),pj(o),rj(o),jq(o),XF(o,{network:t.network}),Dj(o)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=gpe;if(!globalThis.fetch)globalThis.fetch=xh,globalThis.Headers=Zr,globalThis.Request=Ti,globalThis.Response=Ar;if(!globalThis.WebSocket)globalThis.WebSocket=x1.default;async function ype(){let e=lc(),t=e.privateKey!==null,r=new Pv({name:"monaco-mcp-server",version:w0.version});Hq(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let n=new Iv;await r.connect(n),console.error(t?`Monaco MCP server running on stdio (network=${e.network}, capability=${e.capability}). Fund-movement and privilege tools require MONACO_CAPABILITY=full or an explicit MONACO_TOOL_ALLOWLIST entry.`:"Monaco MCP server running on stdio (public read-only mode — set MONACO_PRIVATE_KEY, MONACO_CLIENT_ID and MONACO_NETWORK to enable authenticated tools).")}ype().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});
|
|
151
|
+
- `)}`);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 ye(e,t){let r=e.safeParse(t);if(!r.success)throw new jU(r.error);return r.data}var Il=G(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),km=G(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),Db=G(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Rm=G(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),qU=G(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),AA=G(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Wc=G(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),kl=G(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),ut=b().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"}),ke=R5({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),ka=Ou.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),HU=M().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Om=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),Ode=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),zb=T({triggerPrice:ut,orderType:kl,limitPrice:ut.optional(),quantity:ut.optional(),closePosition:ue().optional(),timeInForce:AA.optional(),slippageToleranceBps:Om.optional(),expiresAt:ka.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"]}),Bb=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,IA=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),kA=b().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),GU=T({tradingPairId:ke,side:Il,quantity:ut,price:ut,options:T({idempotencyKey:kA.optional(),tradingMode:km.optional(),useMasterBalance:ue().optional(),expirationDate:ka.optional(),timeInForce:qU.optional(),marginAccountId:ke.optional(),marginMode:Db.optional(),riskBucketId:ke.optional(),riskBucketCollateral:ut.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:Rm.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional(),takeProfit:zb.optional(),stopLoss:zb.optional()}).optional()}).refine((e)=>IA(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)=>!Bb(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!Bb(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),VU=T({tradingPairId:ke,side:Il,quantity:ut,options:T({idempotencyKey:kA.optional(),tradingMode:km.optional(),slippageTolerance:HU,marginAccountId:ke.optional(),marginMode:Db.optional(),riskBucketId:ke.optional(),riskBucketCollateral:ut.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:Rm.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),selfTradePreventionMode:Wc.optional(),takeProfit:zb.optional(),stopLoss:zb.optional()}).optional()}).refine((e)=>IA(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)=>!Bb(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!Bb(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),ZU=T({orderId:ke,remainingQuantityTarget:ut.optional()}),WU=T({orderId:ke,newOrder:T({price:ut.optional(),quantity:ut.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()})}),KU=T({status:st([G(Nb),Ce(G(Nb)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:ke.optional(),tradingMode:km.optional(),marginAccountId:ke.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:b().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Go.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),oIt=G(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),iIt=G(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),Cde=G(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),sIt=G(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),RA=T({conditionalOrderId:ke}),YU=T({marginAccountId:ke.optional(),tradingPairId:ke.optional(),state:Cde.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Mde=G(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),$de=st([M().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),b().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Nde=2592000000,JU=T({tradingPairId:ke,side:Il,quantity:ut,options:T({durationSeconds:$de.optional(),startTime:ka.optional(),endTime:ka.optional(),limitPrice:ut.optional(),slippageToleranceBps:Ode.optional(),randomize:ue().optional(),executionStyle:G(["TAKER","PASSIVE"]).optional(),reduceOnly:ue().optional(),tradingMode:km.optional(),marginAccountId:ke.optional(),riskBucketId:ke.optional(),marginMode:Db.optional(),leverage:ut.optional(),strategyKey:b().min(1).max(128).optional(),useMasterBalance:ue().optional(),clientTwapId:b().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:ut.optional(),triggerDirection:G(["ABOVE","BELOW"]).optional(),conditionalExpiry:ka.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).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()<=Nde},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),Ub=T({twapOrderId:ke}),QU=T({state:Mde.optional(),tradingPairId:ke.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),zde=T({tradingPairId:ke,orderType:kl,side:Il,price:ut.optional(),quantity:ut,idempotencyKey:kA.optional(),tradingMode:km.optional(),slippageTolerance:HU,useMasterBalance:ue().optional(),expirationDate:ka.optional(),timeInForce:qU.optional(),marginAccountId:ke.optional(),marginMode:Db.optional(),riskBucketId:ke.optional(),riskBucketCollateral:ut.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:Rm.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>IA(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"]}),Lb=100,XU=T({orders:Ce(zde).min(1,"At least one order is required").max(Lb,`At most ${Lb} orders per batch request`)}),Bde=T({orderId:ke,price:ut.optional(),quantity:ut.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),eF=T({orders:Ce(Bde).min(1,"At least one order is required").max(Lb,`At most ${Lb} orders per batch request`)});var OA=T({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),tF=OA.extend({state:b().trim().min(1,"State cannot be empty").optional(),tradingPairId:ke.optional()}),rF=T({marginAccountId:ke,tradingPairId:ke.optional()}),nF=T({tradingPairId:ke.optional()}).optional(),oF=T({asset:b().trim().min(1,"Asset cannot be empty").optional()}).optional(),Lde=T({asset:b().trim().min(1,"Asset cannot be empty"),amount:ut,tradingPairId:ke.optional(),strategyKey:b().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:G(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),Fb=T({asset:b().trim().min(1,"Asset cannot be empty"),amount:ut}),Dde=T({tradingPairId:ke,strategyKey:b().trim().min(1,"Strategy key cannot be empty").optional()}),Ude=Ce(ke).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),iF=Dde.extend({marginMode:_e("ISOLATED").optional(),selectedTradingPairIds:uo().optional(),applyToPositionMargin:ue().optional()}),Fde=T({marginMode:_e("CROSS"),selectedTradingPairIds:Ude,strategyKey:uo().optional()}),jde=T({marginMode:_e("CROSS"),selectedTradingPairIds:uo().optional(),strategyKey:uo().optional(),tradingPairId:uo().optional()}),CA=T({marginAccountId:ke,request:Lde}),sF=T({request:Fb}),qde=T({marginMode:G(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.marginMode==="CROSS"&&e.selectedTradingPairIds!==void 0)t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare"})}),aF=T({request:qde.pipe(st([Fb.merge(iF).strict(),Fb.merge(jde).strict()]))}),cF=T({request:Fb}),uF=OA.extend({marginAccountId:ke,movementType:b().trim().min(1,"Movement type cannot be empty").optional()}),dF=OA.extend({movementType:b().trim().min(1,"Movement type cannot be empty").optional()}).optional(),MA=T({tradingPairId:ke,side:Il,positionSide:Rm.optional(),orderType:kl,price:ut.optional(),quantity:ut,leverage:ut.optional(),reduceOnly:ue().optional()}),$A=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:Go.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:Go.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},lF=MA.strict().superRefine($A),Hde=MA.merge(iF).strict().superRefine($A),Gde=MA.merge(Fde).strict().superRefine($A).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),Vde=st([Hde,Gde]),pF=T({marginAccountId:ke,request:lF}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),fF=T({request:lF}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),mF=T({request:Vde}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var hF=G(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),Zde=31536000000,Wde=946684800000,jb=M().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(Wde,{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()+Zde,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),fIt=T({tradingPairId:ke,interval:hF,startTime:jb,endTime:jb}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),mIt=b().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")'}),Kde=M().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),gF=T({tradingPairId:ke,interval:hF,startTime:jb.optional(),endTime:jb.optional(),limit:Kde,priceType:G(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var hIt=T({tradingPairId:ke}),gIt=T({query:b().min(1,"Search query cannot be empty").optional(),pageSize:M().int().min(1).max(100).optional(),page:M().int().min(1).optional()}),fi=T({tradingPairId:ke});var bF=T({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Yde=G(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),Jde=G(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),Cm=T({positionId:ke}),xF=bF.extend({marginAccountId:ke.optional(),tradingPairId:ke.optional(),status:Yde.optional()}),_F=Cm,wF=Cm.extend({request:T({closeType:Jde,limitPrice:ut.optional(),slippageToleranceBps:Om.optional(),quantity:ut.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"]}),SF=T({tradingPairId:ke.optional(),slippageToleranceBps:Om.optional()}),vF=Cm,yF=T({triggerPrice:ut,orderType:kl,limitPrice:ut.optional(),quantity:ut.optional(),closePosition:ue().optional(),timeInForce:AA.optional(),slippageToleranceBps:Om.optional(),expiresAt:ka.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"]}),TF=Cm.extend({request:T({takeProfit:yF.optional(),stopLoss:yF.optional(),oco:ue().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),EF=bF.extend({positionId:ke.optional(),marginAccountId:ke.optional(),tradingPairId:ke.optional(),reductionOnly:ue().optional()}),Qde=G(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),PF=Cm.extend({params:T({interval:Qde,startTime:M().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:M().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 Xde=G(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),ele=G(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),AF=T({mode:Wc}),IF=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:Xde.optional(),transactionType:ele.optional(),assetId:ke.optional()}),kF=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().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:ke.optional(),pageToken:b().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Go.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),RF=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:ke.optional(),positionId:ke.optional(),marginAccountId:ke.optional()});var PIt=b().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),NA=st([b().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),C5().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),OF=T({assetId:ke,amount:NA,autoWait:ue().optional()}),CF=T({assetId:ke,amount:NA,autoWait:ue().optional(),target:G(["spot","margin"]).optional(),options:T({asErc20:ue().optional()}).optional()}),MF=T({assetId:ke,amount:NA,destination:b().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:ue().optional(),source:G(["spot","margin"]).optional()}),AIt=T({assetId:ke});var tle="OPERATIONS_BLOCKED",rle="OVERLOADED";function nle(e){if(!(e instanceof Zt)||!e.retryable)return e;if(!(e.statusCode===void 0||e.statusCode>=500)||ole(e))return e;return e.retryable=!1,e.suggestion="The claim's outcome is unknown: it may have committed after this failure. Do not retry automatically, and do not rely on a balance read to decide — an admitted claim can still be queued, so an unchanged balance does not prove it will not commit. Treat the claim as pending and reconcile before issuing another; this endpoint has no idempotency key, so a retry can claim a second time.",e}function ole(e){let t=e.responseBody;if(t===null||typeof t!=="object")return!1;let{error:r,code:n}=t;return r===tle||n===rle}class qb extends Ve{async getConfig(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/config",{method:"GET"})}async listPayouts(e){if(e)ye(wA,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());let r=t.toString(),n=r?`/api/v1/buildercodes/payouts?${r}`:"/api/v1/buildercodes/payouts";return this.makeAuthenticatedRequest(n,{method:"GET"})}async getPayoutSummary(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/payouts/summary",{method:"GET"})}async getRewardsBalance(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/balance",{method:"GET"})}async claimBuildercodeRewards(e){let t=ye(SA,e);try{return await this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/claim",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}catch(r){throw nle(r)}}}class zA extends Ve{async upsertDelegatedAgent(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.list(),{method:"POST",body:JSON.stringify({agentAddress:e.agentAddress,name:e.name,expiresAt:e.expiresAt,allowedActions:e.allowedActions,allowedTradingPairIds:e.allowedTradingPairIds,allowedMarginAccountIds:e.allowedMarginAccountIds,allowedOrderTypes:e.allowedOrderTypes,allowedTimeInForce:e.allowedTimeInForce,maxLeverage:e.maxLeverage,maxOrderNotional:e.maxOrderNotional,maxOpenOrders:e.maxOpenOrders})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(ae.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(ae.delegatedAgents.owners())}async revokeDelegatedAgent(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.byId(e),{method:"DELETE"})}async createDelegatedSession(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:e.ownerUserId,sessionPublicKey:e.sessionPublicKey})})}}class Hb extends Ve{async mint(e){return await this.makeAuthenticatedRequest(ae.faucet.mint(),{method:"POST",body:JSON.stringify({turnstileToken:e.turnstileToken})})}async getInfo(){return await this.makeAuthenticatedRequest(ae.faucet.info(),{method:"GET"})}}class Gb extends Ve{async simulateFees(e){let t=ye(vA,e),r=new URLSearchParams;if(r.append("tradingPairId",t.tradingPairId),r.append("side",t.side),r.append("price",t.price),r.append("quantity",t.quantity),t.orderType!==void 0)r.append("orderType",t.orderType);if(t.slippageToleranceBps!==void 0)r.append("slippageToleranceBps",String(t.slippageToleranceBps));let n=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}async getMyFeeTier(e){let t=ye(TA,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let n=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}}class Vb extends Ve{async listMarginAccounts(e){if(e)ye(tF,e);return await this.makeAuthenticatedRequest(ae.marginAccounts.list(e?{page:e.page,pageSize:e.pageSize,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return ye(rF,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ae.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return ye(nF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return ye(oF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return ye(CA,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return ye(sF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return ye(aF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,applyToPositionMargin:e.applyToPositionMargin})})}async transferCollateralFromMarginAccount(e,t){return ye(CA,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferOut(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey,marginMode:t.marginMode})})}async transferCollateralFromParentMarginAccount(e){return ye(cF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return ye(uF,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ae.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return ye(dF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return ye(pF,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateOrderRisk(e),{method:"POST",body:JSON.stringify({tradingPairId:t.tradingPairId,side:t.side,positionSide:t.positionSide,orderType:t.orderType,price:t.price,quantity:t.quantity,leverage:t.leverage,reduceOnly:t.reduceOnly})})}async simulateParentMarginOrderRisk(e){return ye(fF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateParentMarginOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}async simulateRiskBucketOrderRisk(e){return ye(mF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}}class Zb extends Ve{async getPaginatedTradingPairs(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.marketType)t.append("marketType",e.marketType);if(e?.baseToken)t.append("baseToken",e.baseToken);if(e?.quoteToken)t.append("quoteToken",e.quoteToken);if(e?.isActive!==void 0)t.append("isActive",e.isActive.toString());if(e?.category)t.append("category",e.category);let r=t.toString(),n=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(n)}async getTradingPair(e){return ye(fi,{tradingPairId:e}),(await this.makePublicRequest(ae.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((n)=>n.symbol===e)}async getCandlesticks(e,t,r){ye(gF,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit,priceType:r?.priceType});let n=new URLSearchParams;if(r?.startTime!==void 0)n.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)n.append("endTime",r.endTime.toString());if(r?.limit!==void 0)n.append("limit",r.limit.toString());if(r?.priceType!==void 0)n.append("priceType",r.priceType);let o=n.toString(),i=o?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${o}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getPerpMarketSummary(e))}async getMarkPrice(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getMarkPrice(e))}async getIndexPrice(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getIndexPrice(e))}async getFundingState(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getFundingState(e))}async listFundingHistory(e,t){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return await this.makePublicRequest(ae.market.listAllFundingHistory(e))}async getOpenInterest(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(ae.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(ae.market.getMarketStats())}}class Wb extends Ve{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:n,magnitude:o,denomination:i}=t,s=new URLSearchParams;if(s.set("levels",String(r)),n)s.set("tradingMode",n);if(o!==void 0)s.set("magnitude",String(o));if(i)s.set("denomination",i.toLowerCase());let a=await this.makePublicRequest(`/api/v1/orderbook/${encodeURIComponent(e)}?${s.toString()}`);return{tradingPairId:a.tradingPairId,tradingMode:a.tradingMode,bids:a.data.bids.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),asks:a.data.asks.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),bestBid:a.data.bestBid,bestAsk:a.data.bestAsk,bidVolume:a.data.bidVolume,askVolume:a.data.askVolume,baseDecimals:a.baseDecimals,quoteDecimals:a.quoteDecimals,timestamp:a.timestamp,sequence:a.sequenceNumber}}}class Kb extends Ve{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me",{method:"GET"})}async setTraderCode(e){let t=ye(EA,{code:e});return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/pitpass/codes/available?${t}`,{method:"GET"});return{available:r.available,reason:r.reason?r.reason:void 0}}async getTraderCodeInfo(e){let t=encodeURIComponent(e.trim());return await this.makePublicRequest(`/api/v1/pitpass/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/balance",{method:"GET"})}async transferRewards(e){let t=ye(PA,e);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}}var Mm="/api/v1/accounts/me/portfolio";function Yb(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class Jb extends Ve{async getSummary(e){return await this.makeAuthenticatedRequest(Yb(`${Mm}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(Yb(`${Mm}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(Yb(`${Mm}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(Yb(`${Mm}/assets`,e))}async getMargin(){return await this.makeAuthenticatedRequest(`${Mm}/margin`)}}class Qb extends Ve{async listPositions(e){if(e)ye(xF,e);return await this.makeAuthenticatedRequest(ae.positions.list(e))}async getPosition(e){return ye(_F,{positionId:e}),await this.makeAuthenticatedRequest(ae.positions.get(e))}async closePosition(e,t){return ye(wF,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ae.positions.close(e),{method:"POST",body:JSON.stringify({closeType:t.closeType,limitPrice:t.limitPrice,slippageToleranceBps:t.slippageToleranceBps,quantity:t.quantity})})}async batchCloseAllPositions(e){if(e)ye(SF,e);return await this.makeAuthenticatedRequest(ae.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return ye(vF,{positionId:e}),await this.makeAuthenticatedRequest(ae.positions.risk(e))}async attachPositionTpSl(e,t){return ye(TF,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ae.positions.attachTpSl(e),{method:"POST",body:JSON.stringify({takeProfit:t.takeProfit?{triggerPrice:t.takeProfit.triggerPrice,orderType:t.takeProfit.orderType,limitPrice:t.takeProfit.limitPrice,quantity:t.takeProfit.quantity,closePosition:t.takeProfit.closePosition,timeInForce:t.takeProfit.timeInForce,slippageToleranceBps:t.takeProfit.slippageToleranceBps,expiresAt:t.takeProfit.expiresAt}:void 0,stopLoss:t.stopLoss?{triggerPrice:t.stopLoss.triggerPrice,orderType:t.stopLoss.orderType,limitPrice:t.stopLoss.limitPrice,quantity:t.stopLoss.quantity,closePosition:t.stopLoss.closePosition,timeInForce:t.stopLoss.timeInForce,slippageToleranceBps:t.stopLoss.slippageToleranceBps,expiresAt:t.stopLoss.expiresAt}:void 0,oco:t.oco})})}async listPositionHistory(e){if(e)ye(EF,e);return await this.makeAuthenticatedRequest(ae.positions.history(e))}async getPositionPnlHistory(e,t){return ye(PF,{positionId:e,params:t}),await this.makeAuthenticatedRequest(ae.positions.pnlHistory(e,t))}}class BA extends Ve{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)ye(IF,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.entryType!==void 0)t.append("entryType",e.entryType);if(e?.transactionType!==void 0)t.append("transactionType",e.transactionType);if(e?.assetId!==void 0)t.append("assetId",e.assetId);let r=t.toString(),n=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(n)}async getUserBalances(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());let r=t.toString(),n=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(n)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new Zt("assetId is required and cannot be empty",{endpoint:"/api/v1/accounts/balances/{assetId}"});let t=`/api/v1/accounts/balances/${e}`;return await this.makeAuthenticatedRequest(t)}async getPortfolioStats(e){let t=new URLSearchParams({period:e});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio?${t}`)}async getPortfolioChart(e,t){let r=new URLSearchParams({period:e,metric:t});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio/chart?${r}`)}async getUserTrades(e){if(e)ye(kF,e);let t=e?.page!==void 0&&e?.pageToken===void 0,r=new URLSearchParams;if(t&&e?.page!==void 0)r.append("page",e.page.toString());if(e?.pageSize!==void 0)r.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)r.append("tradingPairId",e.tradingPairId);if(!t)r.append("pageToken",e?.pageToken??"");let n=r.toString(),o=n?`/api/v1/accounts/trades?${n}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(o)}async*iterateUserTrades(e){let t="";for(;;){let r=await this.getUserTrades({...e,pageToken:t});if(yield*r.trades,!r.nextPageToken)return;t=r.nextPageToken}}async listFundingPayments(e){if(e)ye(RF,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);if(e?.positionId!==void 0)t.append("positionId",e.positionId);if(e?.marginAccountId!==void 0)t.append("marginAccountId",e.marginAccountId);let r=t.toString(),n=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(n)}async getSelfTradePreventionDefault(){return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention")}async setSelfTradePreventionDefault(e){let t=ye(AF,{mode:e});return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention",{method:"PUT",body:JSON.stringify(t)})}}class Xb extends Ve{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class ex extends Ve{async list(){return await this.makeAuthenticatedRequest(ae.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(ae.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(ae.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(ae.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(ae.subAccounts.limit(e,t),{method:"DELETE"})}}function ile(e){if(e==="spot")return"SPOT";if(e==="margin")return"MARGIN";throw new Pt(`Invalid deposit target: ${JSON.stringify(e)}. Expected "spot" or "margin".`)}class tx extends Ve{async register(e={}){let{depositTarget:t,...r}=e,n=t===void 0?r:{...r,depositTarget:ile(t)};return await this.makeAuthenticatedRequest(ae.sweeper.register(),{method:"POST",body:JSON.stringify(n)})}async getChains(){return await this.makePublicRequest(ae.sweeper.chains(),{method:"GET"})}}function $F(e){return{eventType:"trade",tradingPairId:e.tradingPairId,tradingMode:e.tradingMode.toUpperCase(),data:{tradeId:e.data.tradeId,price:e.data.price,quantity:e.data.quantity,makerSide:e.data.makerSide.toUpperCase(),executedAt:e.data.executedAt??""}}}class LA extends Ve{async getTrades(e,t={}){let{page:r=1}=t,n=t.pageSize!=null&&t.pageSize>0?Math.min(t.pageSize,100):25,o=new URLSearchParams;if(r>1)o.set("page",String(r));return o.set("pageSize",String(n)),(await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}?${o.toString()}`)).trades.map($F)}async getTradeById(e){let t=await this.makePublicRequest(ae.trades.byId(e));return $F(t)}}function rx(e){if(!e)return;return{triggerPrice:e.triggerPrice,orderType:e.orderType,limitPrice:e.limitPrice,timeInForce:e.timeInForce,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt,quantity:e.quantity,closePosition:e.closePosition}}class nx extends Ve{async placeLimitOrder(e,t,r,n,o){ye(GU,{tradingPairId:e,side:t,quantity:r,price:n,options:o});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:n,quantity:r,tradingMode:o?.tradingMode||"SPOT",useMasterBalance:o?.useMasterBalance,expirationDate:o?.expirationDate,timeInForce:o?.timeInForce,marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,postOnly:o?.postOnly,selfTradePreventionMode:o?.selfTradePreventionMode,clientOrderId:o?.clientOrderId,idempotencyKey:o?.idempotencyKey===void 0?crypto.randomUUID():o.idempotencyKey,takeProfit:rx(o?.takeProfit),stopLoss:rx(o?.stopLoss)};return await this.makeAuthenticatedRequest(ae.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,n){ye(VU,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:n?.slippageTolerance!==void 0?Math.round(n.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:n?.tradingMode||"SPOT",marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,selfTradePreventionMode:n?.selfTradePreventionMode,takeProfit:rx(n?.takeProfit),stopLoss:rx(n?.stopLoss),clientOrderId:n?.clientOrderId,idempotencyKey:n?.idempotencyKey===void 0?crypto.randomUUID():n.idempotencyKey};return await this.makeAuthenticatedRequest(ae.orders.create(),{method:"POST",body:JSON.stringify(o)})}async cancelOrder(e,t){ye(ZU,{orderId:e,remainingQuantityTarget:t?.remainingQuantityTarget});let r={orderId:e,...t?.remainingQuantityTarget!==void 0&&{remainingQuantityTarget:t.remainingQuantityTarget}};return await this.makeAuthenticatedRequest(ae.orders.cancel(),{method:"POST",body:JSON.stringify(r)})}async cancelConditionalOrder(e){return ye(RA,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return ye(RA,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)ye(YU,e);let{page:t=1,pageSize:r=20,marginAccountId:n,tradingPairId:o,state:i}=e||{};return await this.makeAuthenticatedRequest(ae.orders.listConditional({page:t,pageSize:Math.min(Math.max(r,1),100),marginAccountId:n,tradingPairId:o,state:i}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(ae.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?ae.orders.batchCancelAllByPair(e):ae.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){ye(WU,{orderId:e,newOrder:t});let r={useMasterBalance:t.useMasterBalance??!1};if(t.price!==void 0)r.price=t.price;if(t.quantity!==void 0)r.quantity=t.quantity;if(t.postOnly!==void 0)r.postOnly=t.postOnly;if(t.selfTradePreventionMode!==void 0)r.selfTradePreventionMode=t.selfTradePreventionMode;if(t.clientOrderId!==void 0)r.clientOrderId=t.clientOrderId;return await this.makeAuthenticatedRequest(ae.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){ye(XU,{orders:e});let t={orders:e.map((r)=>({tradingPairId:r.tradingPairId,orderType:r.orderType,side:r.side,price:r.price,quantity:r.quantity,tradingMode:r.tradingMode||"SPOT",slippageToleranceBps:r.slippageTolerance!==void 0?Math.round(r.slippageTolerance*1e4):void 0,useMasterBalance:r.useMasterBalance,expirationDate:r.expirationDate,timeInForce:r.timeInForce,marginAccountId:r.marginAccountId,marginMode:r.marginMode,riskBucketId:r.riskBucketId,riskBucketCollateral:r.riskBucketCollateral,strategyKey:r.strategyKey,positionSide:r.positionSide,leverage:r.leverage,reduceOnly:r.reduceOnly,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId,idempotencyKey:r.idempotencyKey===void 0?crypto.randomUUID():r.idempotencyKey}))};return this.makeAuthenticatedRequest(ae.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){ye(eF,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ae.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)ye(KU,e);let{page:t,pageSize:r=10,status:n,tradingPairId:o,tradingMode:i,marginAccountId:s,pageToken:a}=e||{},c=r>0?r:10,d=t!==void 0&&a===void 0,l=Math.min(c,d?100:1000),p=new URLSearchParams;if(d){let y=t>0?t:1;p.append("page",y.toString())}p.append("pageSize",l.toString());let m=typeof n==="string"?n:n?.join(",");if(m)p.append("status",m);if(o)p.append("tradingPairId",o);if(i)p.append("tradingMode",i);if(s)p.append("marginAccountId",s);if(!d)p.append("pageToken",a??"");let h=`/api/v1/orders?${p.toString()}`;return await this.makeAuthenticatedRequest(h,{method:"GET"})}async*iterateOrders(e){let t="";for(;;){let r=await this.getPaginatedOrders({...e,pageToken:t});if(yield*r.orders,!r.nextPageToken)return;t=r.nextPageToken}}async getOrder(e){return{order:await this.makeAuthenticatedRequest(ae.orders.get(e),{method:"GET"}),status:"SUCCESS"}}async createTwapOrder(e,t,r,n){ye(JU,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,side:t,quantity:r,durationSeconds:n.durationSeconds!==void 0?Number(n.durationSeconds):void 0,startTime:n.startTime,endTime:n.endTime,limitPrice:n.limitPrice,slippageToleranceBps:n.slippageToleranceBps,randomize:n.randomize,reduceOnly:n.reduceOnly,tradingMode:n.tradingMode||"SPOT",marginAccountId:n.marginAccountId,riskBucketId:n.riskBucketId,marginMode:n.marginMode,leverage:n.leverage,strategyKey:n.strategyKey,useMasterBalance:n.useMasterBalance,clientTwapId:n.clientTwapId,executionStyle:n.executionStyle,triggerPrice:n.triggerPrice,triggerDirection:n.triggerDirection,conditionalExpiry:n.conditionalExpiry};return await this.makeAuthenticatedRequest(ae.orders.createTwap(),{method:"POST",body:JSON.stringify(o)})}async cancelTwapOrder(e){return ye(Ub,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.cancelTwap(e),{method:"POST"})}async getTwapOrder(e){return ye(Ub,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getTwap(e),{method:"GET"})}async getTwapOrderTca(e){return ye(Ub,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getTwapTca(e),{method:"GET"})}async listTwapOrders(e){if(e)ye(QU,e);let{page:t=1,pageSize:r=20,state:n,tradingPairId:o}=e||{};return await this.makeAuthenticatedRequest(ae.orders.listTwap({page:t,pageSize:Math.min(Math.max(r,1),100),state:n,tradingPairId:o}),{method:"GET"})}}var DA=[{inputs:[{internalType:"address",name:"factory_",type:"address"},{internalType:"address",name:"unwrapHelper_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"BridgeFeeTooHigh",type:"error"},{inputs:[],name:"ChainNotConfigured",type:"error"},{inputs:[],name:"ComposeNotSupported",type:"error"},{inputs:[],name:"ComposeSourceMismatch",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeNotAccepted",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NoRoute",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotHub",type:"error"},{inputs:[],name:"NotRemote",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OftCannotUnwrap",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[],name:"QuoteNotBound",type:"error"},{inputs:[],name:"RoutedToken",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",type:"error"},{inputs:[],name:"StaleQuote",type:"error"},{inputs:[],name:"SweepParamsRequired",type:"error"},{inputs:[],name:"UnexpectedBridgeDebit",type:"error"},{inputs:[],name:"UnexpectedParams",type:"error"},{inputs:[],name:"UnexpectedValue",type:"error"},{inputs:[],name:"UnswapPathMissing",type:"error"},{inputs:[],name:"UntrustedComposeCaller",type:"error"},{inputs:[],name:"UntrustedComposeSource",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"address",name:"bridgeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"amountBridged",type:"uint256"},{indexed:!1,internalType:"address",name:"destination",type:"address"}],name:"Bridged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Refunded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"RefundedNative",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Swept",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"tokenIn",type:"address"},{indexed:!0,internalType:"address",name:"tokenOut",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountOut",type:"uint256"}],name:"Unswapped",type:"event"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"hubToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{internalType:"contract ISweeperFactory",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"bytes",name:"message",type:"bytes"},{internalType:"address",name:"",type:"address"},{internalType:"bytes",name:"",type:"bytes"}],name:"lzCompose",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"feeRefundAddress",type:"address"}],name:"sweepWithRefund",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{stateMutability:"payable",type:"receive"}];var UA=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[],name:"ImplementationNotSet",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidFeeCap",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousExecutor",type:"address"},{indexed:!0,internalType:"address",name:"newExecutor",type:"address"}],name:"ExecutorUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"rollup",type:"address"},{indexed:!1,internalType:"address",name:"bridgedStable",type:"address"},{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"address",name:"lzEndpoint",type:"address"}],name:"HubConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint16",name:"previousCapBps",type:"uint16"},{indexed:!1,internalType:"uint16",name:"newCapBps",type:"uint16"}],name:"PermissionlessBridgeFeeCapUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"uint32",name:"cctpDestinationDomain",type:"uint32"},{indexed:!1,internalType:"uint32",name:"stargateDestinationEid",type:"uint32"}],name:"RemoteConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],indexed:!1,internalType:"struct BridgeRoute",name:"route",type:"tuple"}],name:"RouteSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"sweeper",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"string",name:"applicationId",type:"string"},{indexed:!1,internalType:"address",name:"hubToken",type:"address"}],name:"SweeperDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousImplementation",type:"address"},{indexed:!0,internalType:"address",name:"newImplementation",type:"address"}],name:"SweeperImplementationUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"stargate",type:"address"},{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"TrustedStargateSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"hubToken",type:"address"},{indexed:!1,internalType:"bytes",name:"path",type:"bytes"}],name:"UnswapPathSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"bridgedStable",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"cctpDestinationDomain",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[],name:"chainMode",outputs:[{internalType:"enum ChainMode",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"rollup_",type:"address"},{internalType:"address",name:"bridgedStable_",type:"address"},{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"address",name:"lzEndpoint_",type:"address"}],name:"configureHub",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"uint32",name:"cctpDestinationDomain_",type:"uint32"},{internalType:"uint32",name:"stargateDestinationEid_",type:"uint32"}],name:"configureRemote",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"deploy",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"deployReceiver",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"executor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"forwarder",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner_",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"lzEndpoint",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"permissionlessBridgeFeeCapBps",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"receiverFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"refundToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"route",outputs:[{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"executor_",type:"address"}],name:"setExecutor",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint16",name:"capBps",type:"uint16"}],name:"setPermissionlessBridgeFeeCapBps",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"route_",type:"tuple"}],name:"setRoute",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"setSweeperImplementation",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"setTrustedStargate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"path",type:"bytes"}],name:"setUnswapPath",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"stargateDestinationEid",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"}],name:"stargateToken",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"swapRouter",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweepWithParams",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"sweeperFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"sweeperImplementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"}],name:"unswapPath",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"}];var FA=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AccessControlBadConfirmation",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"bytes32",name:"neededRole",type:"bytes32"}],name:"AccessControlUnauthorizedAccount",type:"error"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"InvalidSeed",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[],name:"InvalidTimestamp",type:"error"},{inputs:[],name:"NonceAlreadyUsed",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[],name:"ReentrancyGuardReentrantCall",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newFeeCollector",type:"address"}],name:"FeeCollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newSettlementContract",type:"address"}],name:"SettlementContractChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"maker",type:"address"},{indexed:!0,internalType:"address",name:"taker",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"fee",type:"uint256"}],name:"SettlementTransfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdrawal",type:"event"},{inputs:[],name:"DEBUGGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"FEE_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PAUSER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"SETTLEMENT_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"seed",type:"bytes"}],name:"decodeSeed",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"depositERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],name:"depositNative",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"feeCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getChainID",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_admin",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"callerConfirmation",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newFeeCollector",type:"address"}],name:"setFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_settlementContract",type:"address"}],name:"setSettlementContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"settlementContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"maker",type:"address"},{internalType:"address",name:"taker",type:"address"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"fee",type:"uint256"}],name:"transferOnSettlement",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdrawNative",outputs:[],stateMutability:"nonpayable",type:"function"}];var l2t=new Uint8Array(32);function ox(e,t){return sle(t),t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}function sle(e){if(e!=="spot"&&e!=="margin")throw Error(`Invalid deposit target: ${JSON.stringify(e)}. `+'Expected "spot" or "margin" — lowercase, not the wire form "SPOT"/"MARGIN".')}var jA={vault:FA,sweeper:DA,sweeperFactory:UA};var ale=5000,cle=300000,ule=(e)=>new Promise((t)=>setTimeout(t,e));class ix extends Ve{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,n,o,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=n,this.profileAPI=o}setWalletClient(e){this.walletClient=e}async getVaultAddress(){return(await this.applicationsAPI.getApplicationConfig()).vaultContractAddress}async getClientId(){return(await this.applicationsAPI.getApplicationConfig()).clientId}async resolveAsset(e){let t,r;try{let n=await this.profileAPI.getUserBalanceByAssetId(e);t=n.token,r=n.wrappedNative===!0}catch(n){if(n instanceof Zt){if(n.statusCode===404)throw new Vi(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:n});throw new Vi(`Failed to resolve asset ID '${e}': ${n.retryable?"Network error occurred":"API request failed"}`,{revertReason:n.retryable?"NETWORK_ERROR":"API_ERROR",cause:n})}throw new Vi(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:n instanceof Error?n:void 0})}return{tokenAddress:t,isWrappedNative:r}}async approve(e,t,r=!0){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");ye(OF,{assetId:e,amount:t,autoWait:r});let n=await this.getVaultAddress(),{tokenAddress:o}=await this.resolveAsset(e),i=this.walletClient.account;if(!i)throw new Pt("No account available in wallet client","account");let s=i.getNonce?await i.getNonce():0n,a=await this.walletClient.writeContract({address:o,abi:Wt,functionName:"approve",args:[n,t],chain:this.chain,account:i}),c={nonce:s,hash:a,status:"pending"};return await this.waitForTransaction(c,r)}async deposit(e,t,r=!0,n="spot",o={}){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");ye(CF,{assetId:e,amount:t,autoWait:r,target:n,options:o});let i=await this.getVaultAddress(),s=await this.getClientId(),a=ox(s,n),{tokenAddress:c,isWrappedNative:d}=await this.resolveAsset(e),l=d&&o.asErc20!==!0;if(!l){if(await this.needsApproval(e,t,o))throw new Vi(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${c}).`,{revertReason:"APPROVAL_REQUIRED"})}let p=this.walletClient.account;if(!p)throw new Pt("No account available in wallet client","account");let m;if(l)m=await this.walletClient.writeContract({address:i,abi:jA.vault,functionName:"depositNative",args:[p.address,a],account:p,chain:this.chain,value:t});else m=await this.walletClient.writeContract({address:i,abi:jA.vault,functionName:"depositERC20",args:[p.address,a,c,t],account:p,chain:this.chain});let h=p.getNonce?await p.getNonce():0n,y={hash:m,status:"pending",nonce:h};return await this.waitForTransaction(y,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??ale,n=t?.timeoutMs??cle,o=Date.now()+n;for(;;){try{let{vaultAddress:i,calldata:s}=await this.makePublicRequest(`/api/v1/withdrawals/${e}`);if(s&&s!=="0x")return{vaultAddress:i,calldata:s}}catch(i){if(!(i instanceof Zt&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>o)return null;await ule(r)}}async withdraw(e,t,r=!0,n,o){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let i=this.walletClient.account;if(!i)throw new Pt("No account available in wallet client","account");let s=i.address.toLowerCase(),a=typeof n==="string"?n:"spot",c=typeof n==="string"?o:n;ye(MF,{assetId:e,amount:t,destination:s,autoWait:r,source:a});let{withdrawalIndex:d}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:s,source:a})});if(!r)return{withdrawalIndex:d,status:"awaiting_proof"};let l=await this.pollWithdrawalCalldata(d,c);if(!l)return{withdrawalIndex:d,status:"awaiting_proof"};let{vaultAddress:p,calldata:m}=l,h;try{h=await this.walletClient.sendTransaction({to:p,data:m,account:i,chain:this.chain})}catch(w){throw new Vi(`Failed to submit executeWithdrawal for withdrawal ${d}: ${w instanceof Error?w.message:"unknown error"}`,{cause:w instanceof Error?w:void 0})}let y=i.getNonce?await i.getNonce():0n,x={hash:h,status:"pending",nonce:y};return{...await this.waitForTransaction(x,r),withdrawalIndex:d}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let n=this.walletClient.account;if(!n)throw new Pt("No account available in wallet client","account");let o=await this.pollWithdrawalCalldata(e,r);if(!o)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:s}=o,a;try{a=await this.walletClient.sendTransaction({to:i,data:s,account:n,chain:this.chain})}catch(p){throw new Vi(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${p instanceof Error?p.message:"unknown error"}`,{cause:p instanceof Error?p:void 0})}let c=n.getNonce?await n.getNonce():0n,d={hash:a,status:"pending",nonce:c};return{...await this.waitForTransaction(d,t),withdrawalIndex:e}}async getBalance(e){throw new Zt("getBalance() is deprecated and no longer supported. Please use profileAPI.getUserBalances() or profileAPI.getUserBalanceByAssetId() instead for balance data.",{statusCode:410})}async getAllowance(e){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let t=await this.getVaultAddress(),n=(await this.walletClient.getAddresses())[0];if(!n)throw new Pt("No account found in wallet client.","walletClient");let{tokenAddress:o}=await this.resolveAsset(e);return await this.publicClient.readContract({address:o,abi:Wt,functionName:"allowance",args:[n,t]})}async needsApproval(e,t,r={}){let{isWrappedNative:n}=await this.resolveAsset(e);if(n&&r.asErc20!==!0)return!1;return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:n=1,timeout:o=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:n,timeout:o});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class sx extends Ve{async submit(e){return await this.makePublicRequest(ae.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class qA extends Ve{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(ae.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:e.assetId,amount:e.amount,destination:e.destination,source:e.source??"spot"})})}async getWithdrawal(e){return this.makePublicRequest(ae.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return this.makeAuthenticatedRequest(ae.withdrawals.list({page:e?.page,pageSize:e?.pageSize}))}}class ax extends Ve{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let r=this.walletClient.account;if(!r)throw new Pt("No account available in wallet client","account");let n=z0(),o={publicKey:B0(n),privateKey:L0(n)},i=await this.createChallenge(r.address,e,o.publicKey),s=await this.signChallenge(i.message);return await this.verifySignature(r.address,s,i.nonce,e,o,t)}async signChallenge(e){if(!this.walletClient)throw new Pt("Wallet client not set. Connect a wallet first.","walletClient");let t=this.walletClient.account;if(!t)throw new Pt("No account available in wallet client","account");return await this.walletClient.signMessage({account:t,message:e})}async createChallenge(e,t,r){let n=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:n.nonce,message:n.message,expiresAt:n.expiresAt}}async verifySignature(e,t,r,n,o,i){let s=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:n,chainId:this.chain.id,sessionPublicKey:o.publicKey,...i?{referralCode:i}:{}})});return{sessionPublicKey:o.publicKey,sessionPrivateKey:o.privateKey,expiresAt:s.expiresAt,user:{id:s.user.id,address:s.user.address,username:s.user.username}}}async refreshSession(){return{expiresAt:(await this.makeAuthenticatedRequest("/api/v1/auth/refresh",{method:"POST"})).expiresAt}}async revokeSession(){await this.makeAuthenticatedRequest("/api/v1/auth/revoke",{method:"POST"})}}var dle=750;function NF(e,t){try{new URL(e)}catch(r){throw new Pt(`${t} must be a valid URL, got: ${e}`,t)}return e}class GA{auth;delegatedAgents;applications;fees;buildercodes;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;whitelist;profile;pulse;orderbook;trades;ws;walletClient;publicClient;authState;network;chain;propagateSession(e){this.auth.setSessionKeypair(e),this.delegatedAgents.setSessionKeypair(e),this.applications.setSessionKeypair(e),this.fees.setSessionKeypair(e),this.buildercodes.setSessionKeypair(e),this.pitpass.setSessionKeypair(e),this.vault.setSessionKeypair(e),this.withdrawals.setSessionKeypair(e),this.trading.setSessionKeypair(e),this.market.setSessionKeypair(e),this.marginAccounts.setSessionKeypair(e),this.positions.setSessionKeypair(e),this.portfolio.setSessionKeypair(e),this.subAccounts.setSessionKeypair(e),this.faucet.setSessionKeypair(e),this.sweeper.setSessionKeypair(e),this.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}setServerKey(e){this.auth.setServerKey(e),this.delegatedAgents.setServerKey(e),this.applications.setServerKey(e),this.fees.setServerKey(e),this.buildercodes.setServerKey(e),this.pitpass.setServerKey(e),this.vault.setServerKey(e),this.withdrawals.setServerKey(e),this.trading.setServerKey(e),this.market.setServerKey(e),this.marginAccounts.setServerKey(e),this.positions.setServerKey(e),this.portfolio.setServerKey(e),this.subAccounts.setServerKey(e),this.faucet.setServerKey(e),this.sweeper.setServerKey(e),this.whitelist.setServerKey(e),this.pulse.setServerKey(e),this.profile.setServerKey(e),this.orderbook.setServerKey(e),this.trades.setServerKey(e)}sessionFromAuthState(e){return{publicKey:e.sessionPublicKey,privateKey:e.sessionPrivateKey}}constructor(e){let t=["mainnet","development","staging","local"];if(!e.network||!t.includes(e.network))throw new Pt(`network must be one of: ${t.join(", ")}. Got: ${e.network}`,"network");if(this.network=e.network,!e.seiRpcUrl)throw new Pt("seiRpcUrl is required","seiRpcUrl");try{new URL(e.seiRpcUrl)}catch(a){throw new Pt(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?NF(e.wsUrl,"wsUrl"):uT(this.network),n=this.network==="mainnet"?Am:Im;if(this.chain=n,e.pollingInterval!==void 0&&(!Number.isFinite(e.pollingInterval)||e.pollingInterval<=0))throw new Pt(`pollingInterval must be a positive number of milliseconds, got: ${e.pollingInterval}`,"pollingInterval");let o=Pm(e.seiRpcUrl);this.publicClient=pA({chain:n,transport:o,pollingInterval:e.pollingInterval??dle});let i=e.apiUrl?NF(e.apiUrl,"apiUrl"):cT(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==n.id)throw new Pt(`Wallet client chain mismatch. Expected ${n.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}let s=(a)=>(a.setRequestSigning(e.requestSigning??"legacy"),a);this.applications=s(new $b(i)),this.market=s(new Zb(i)),this.marginAccounts=s(new Vb(i)),this.positions=s(new Qb(i)),this.portfolio=s(new Jb(i)),this.subAccounts=s(new ex(i)),this.faucet=s(new Hb(i)),this.sweeper=s(new tx(i)),this.whitelist=s(new sx(i)),this.pulse=s(new Xb(i)),this.auth=s(new ax(this.walletClient,this.chain,i)),this.delegatedAgents=s(new zA(i)),this.fees=s(new Gb(i)),this.buildercodes=s(new qb(i)),this.pitpass=s(new Kb(i)),this.profile=s(new BA(i)),this.vault=s(new ix(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i)),this.withdrawals=s(new qA(i)),this.trading=s(new nx(i)),this.orderbook=s(new Wb(i)),this.trades=s(new LA(i)),this.ws=tT(r,e.ws),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new Zt("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:HA.StatusCodes.UNAUTHORIZED});let t=z0(),r={publicKey:B0(t),privateKey:L0(t)},n=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:n.expiresAt,user:{id:n.ownerUserId,address:n.agentAddress}},this.propagateSession(this.sessionFromAuthState(this.authState)),this.authState}getAuthState(){return this.authState}setAuthState(e){this.authState=e,this.propagateSession(this.sessionFromAuthState(e))}async logout(){if(this.authState)try{await this.auth.revokeSession()}catch(e){console.warn("Failed to revoke session on logout:",e)}this.authState=void 0,this.propagateSession(void 0),this.ws.disconnect()}async refreshAuth(){if(!this.authState)throw new Zt("No active session to refresh",{endpoint:"auth/refresh",statusCode:HA.StatusCodes.UNAUTHORIZED});try{let e=await this.auth.refreshSession();return this.authState={...this.authState,expiresAt:e.expiresAt},this.authState}catch(e){throw this.authState=void 0,this.propagateSession(void 0),e}}isAuthenticated(){return!!this.authState}isConnected(){return!!this.walletClient&&!!this.publicClient}setWalletClient(e){if(e.chain?.id!==this.chain.id)throw new Pt(`Wallet client chain mismatch. Expected ${this.chain.id}, got ${e.chain?.id}`,"walletClient");this.walletClient=e,this.auth.setWalletClient(e),this.vault.setWalletClient(e)}getAccountAddress(){if(!this.walletClient)throw new Of("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new Of("No account available","account")}getNetwork(){return this.network}getChainId(){return this.chain.id}async waitForTransaction(e,t,r){return this.publicClient.waitForTransactionReceipt({hash:e,confirmations:t,timeout:r})}}function VA(e){return new GA(e)}hm();Fe();ei();Cn();function zF(e){if(typeof e==="string"){if(!ht(e,{strict:!1}))throw new Ft({address:e});return{address:e,type:"json-rpc"}}if(!ht(e.address,{strict:!1}))throw new Ft({address:e.address});return{address:e.address,nonceManager:e.nonceManager,sign:e.sign,signAuthorization:e.signAuthorization,signMessage:e.signMessage,signTransaction:e.signTransaction,signTypedData:e.signTypedData,source:"custom",type:"local"}}hm();xr();Fe();var ZA=!1;async function mi({hash:e,privateKey:t,to:r="object"}){let{r:n,s:o,recovery:i}=hs.sign(e.slice(2),t.slice(2),{lowS:!0,extraEntropy:Kt(ZA,{strict:!1})?pr(ZA):ZA}),s={r:H(n,{size:32}),s:H(o,{size:32}),v:i?28n:27n,yParity:i};return(()=>{if(r==="bytes"||r==="hex")return yb({...s,to:r});return s})()}async function BF(e){let{chainId:t,nonce:r,privateKey:n,to:o="object"}=e,i=e.contractAddress??e.address,s=await mi({hash:Yy({address:i,chainId:t,nonce:r}),privateKey:n,to:o});if(o==="object")return{address:i,chainId:t,nonce:r,...s};return s}async function LF({message:e,privateKey:t}){return await mi({hash:gl(e),privateKey:t,to:"hex"})}Kn();on();Fe();function DF(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...i}=r,s=r.address;t.push([n?Jt(n):"0x",s,o?Jt(o):"0x",...Rl({},i)])}return t}Fe();QE();ei();He();Jf();ls();Cn();mn();Ji();lr();function UF(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!ht(o))throw new Ft({address:o});if(n<0)throw new md({chainId:n})}cx(e)}function FF(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new bm;for(let r of t){let n=et(r),o=Yt(gn(r,0,1));if(n!==32)throw new wP({hash:r,size:n});if(o!==Xy)throw new SP({hash:r,version:o})}}cx(e)}function cx(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new md({chainId:t});if(o&&!ht(o))throw new Ft({address:o});if(n&&n>Kd)throw new Ro({maxFeePerGas:n});if(r&&n&&r>n)throw new ds({maxFeePerGas:n,maxPriorityFeePerGas:r})}function jF(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(t<=0)throw new md({chainId:t});if(i&&!ht(i))throw new Ft({address:i});if(r||o)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Kd)throw new Ro({maxFeePerGas:n})}function qF(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(i&&!ht(i))throw new Ft({address:i});if(typeof t<"u"&&t<=0)throw new md({chainId:t});if(r||o)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Kd)throw new Ro({maxFeePerGas:n})}ei();on();Cn();function $m(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:o}=e[r];for(let i=0;i<o.length;i++)if(o[i].length-2!==64)throw new TE({storageKey:o[i]});if(!ht(n,{strict:!1}))throw new Ft({address:n});t.push([n,o])}return t}function HF(e,t){let r=tb(e);if(r==="eip1559")return fle(e,t);if(r==="eip2930")return mle(e,t);if(r==="eip4844")return ple(e,t);if(r==="eip7702")return lle(e,t);return hle(e,t)}function lle(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:i,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:l,data:p}=e;UF(e);let m=$m(l),h=DF(r);return Qt(["0x04",gs([H(n),i?H(i):"0x",d?H(d):"0x",c?H(c):"0x",o?H(o):"0x",s??"0x",a?H(a):"0x",p??"0x",m,h,...Rl(e,t)])])}function ple(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:l,data:p}=e;FF(e);let{blobVersionedHashes:m,sidecars:h}=e;if(e.blobs&&(typeof m>"u"||typeof h>"u")){let S=typeof e.blobs[0]==="string"?e.blobs:e.blobs.map((k)=>mt(k)),v=e.kzg,P=el({blobs:S,kzg:v});if(typeof m>"u")m=Qy({commitments:P});if(typeof h>"u"){let k=tl({blobs:S,commitments:P,kzg:v});h=eb({blobs:S,commitments:P,proofs:k})}}let y=$m(l),x=[H(r),o?H(o):"0x",d?H(d):"0x",c?H(c):"0x",n?H(n):"0x",i??"0x",s?H(s):"0x",p??"0x",y,a?H(a):"0x",m??[],...Rl(e,t)],_=[],w=[],A=[];if(h)for(let S=0;S<h.length;S++){let{blob:v,commitment:P,proof:k}=h[S];_.push(v),w.push(P),A.push(k)}return Qt(["0x03",h?gs([x,_,w,A]):gs(x)])}function fle(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:d,data:l}=e;cx(e);let p=$m(d),m=[H(r),o?H(o):"0x",c?H(c):"0x",a?H(a):"0x",n?H(n):"0x",i??"0x",s?H(s):"0x",l??"0x",p,...Rl(e,t)];return Qt(["0x02",gs(m)])}function mle(e,t){let{chainId:r,gas:n,data:o,nonce:i,to:s,value:a,accessList:c,gasPrice:d}=e;jF(e);let l=$m(c),p=[H(r),i?H(i):"0x",d?H(d):"0x",n?H(n):"0x",s??"0x",a?H(a):"0x",o??"0x",l,...Rl(e,t)];return Qt(["0x01",gs(p)])}function hle(e,t){let{chainId:r=0,gas:n,data:o,nonce:i,to:s,value:a,gasPrice:c}=e;qF(e);let d=[i?H(i):"0x",c?H(c):"0x",n?H(n):"0x",s??"0x",a?H(a):"0x",o??"0x"];if(t){let l=(()=>{if(t.v>=35n){if((t.v-35n)/2n>0)return t.v;return 27n+(t.v===35n?0n:1n)}if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let h=27n+(t.v===27n?0n:1n);if(t.v!==h)throw new SE({v:t.v});return h})(),p=$r(t.r),m=$r(t.s);d=[...d,H(l),p==="0x00"?"0x":p,m==="0x00"?"0x":m]}else if(r>0)d=[...d,H(r),"0x","0x"];return gs(d)}function Rl(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let i=$r(r.r),s=$r(r.s);return[(()=>{if(typeof o==="number")return o?H(1):"0x";if(n===0n)return"0x";if(n===1n)return H(1);return n===27n?"0x":H(1)})(),i==="0x00"?"0x":i,s==="0x00"?"0x":s]}async function GF(e){let{privateKey:t,transaction:r,serializer:n=HF}=e,o=(()=>{if(r.type==="eip4844")return{...r,sidecars:!1};return r})(),i=await mi({hash:St(await n(o)),privateKey:t});return await n(r,i)}async function VF(e){let{privateKey:t,...r}=e;return await mi({hash:_b(r),privateKey:t,to:"hex"})}function WA(e,t={}){let{nonceManager:r}=t,n=Jt(hs.getPublicKey(e.slice(2),!1)),o=Ky(n);return{...zF({address:o,nonceManager:r,async sign({hash:s}){return mi({hash:s,privateKey:e,to:"hex"})},async signAuthorization(s){return BF({...s,privateKey:e})},async signMessage({message:s}){return LF({message:s,privateKey:e})},async signTransaction(s,{serializer:a}={}){return GF({privateKey:e,transaction:s,serializer:a})},async signTypedData(s){return VF({...s,privateKey:e})}}),publicKey:n,source:"privateKey"}}var KA=null;var gle={privateKeyToAccount:WA,createWalletClient:gA,http:Pm,createMonacoSDK:VA,sei:Am,seiTestnet:Im};function yle(e,t=gle){let r=e.network==="mainnet"?t.sei:t.seiTestnet,n;if(e.privateKey){let o=t.privateKeyToAccount(e.privateKey);n=t.createWalletClient({account:o,chain:r,transport:t.http(e.seiRpcUrl)})}return t.createMonacoSDK({walletClient:n,network:e.network,seiRpcUrl:e.seiRpcUrl})}function Ze(e){if(!KA){let t=e??lc();KA=yle(t)}return KA}var ble=60,ux=null;function xle(){return Math.floor(Date.now()/1000)}function ZF(e){return e-ble<=xle()}function _le(e){for(let t=e,r=0;t instanceof Error&&r<5;r++){if(t instanceof Zt&&t.statusCode===401)return!0;t=t.cause}return!1}function YA(e){if(!ux)ux=e().finally(()=>{ux=null});return ux}async function WF(e,t){if(await e.login(t.clientId),t.delegatedOwnerUserId){try{let r=await e.loginAsDelegatedOwner(t.delegatedOwnerUserId);console.error(`Adopted delegated owner ${r.user.id} (session expires at ${new Date(r.expiresAt*1000).toISOString()})`)}catch(r){throw await e.logout().catch(()=>{}),r}return}console.error(`Authenticated as ${e.getAccountAddress()}`)}async function KF(e,t){try{await e.refreshAuth()}catch{await WF(e,t)}}async function X(e){let t=Ze(e),r=e??lc(),n=t.getAuthState(),o=r.delegatedOwnerUserId!=null&&n?.user?.id!==r.delegatedOwnerUserId;if(!n||o)return await YA(()=>WF(t,r)),t;if(ZF(n.expiresAt))await YA(()=>KF(t,r));return t}async function wle(e){let t=e??lc();if(!t.privateKey)return!1;let r=Ze(e);return await YA(()=>KF(r,t)),!0}function YF(e,t){async function r(...n){let o=Ze(t).getAuthState(),i=o!==void 0&&!ZF(o.expiresAt);try{return await e(...n)}catch(s){if(!_le(s))throw s;if(!(i&&Ze(t).getAuthState()!==o)){if(!await wle(t))throw s}return await e(...n)}}return r}function L(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function dx(e){return{content:[{type:"text",text:e}]}}function JF(e,t){if(t.network==="mainnet")return;e.registerTool("get_faucet_info",{description:"Get the authenticated wallet's faucet quota: remaining requests in the rolling 24h window, when the next request becomes available, and the 5 most recent faucet requests. Check this before request_faucet to avoid rate-limit errors. Only available on non-mainnet networks (development, staging, local).",inputSchema:{}},async()=>{let n=await(await X()).faucet.getInfo();return L(n)})}function QF(e,t){if(t.network==="mainnet")return;e.registerTool("request_faucet",{description:"Request test funds from the faucet for all active trading pairs. Requires a Cloudflare Turnstile token (the faucet rejects requests without one). Only available on non-mainnet networks (development, staging, local).",inputSchema:T({turnstileToken:b().describe("Cloudflare Turnstile token proving the request came from a real client (required by the faucet).")})},async({turnstileToken:r})=>{let o=await(await X()).faucet.mint({turnstileToken:r});return L(o)})}function XF(e,t){QF(e,t),JF(e,t)}function ej(e){e.registerTool("get_my_fee_tier",{description:"Get the authenticated user's current fee tier, rolling 14-day volumes (with spot/perp breakdown), the volume needed to reach the next tier, and the requested pair's six-row fee schedule.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:t})=>{let n=await(await X()).fees.getMyFeeTier({tradingPairId:t});return L(n)})}function tj(e){e.registerTool("simulate_fees",{description:"Simulate the fees for an order before placing it. Returns Monaco protocol fees, application fees, and total amounts.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side"),price:b().describe("Price per unit as a decimal string"),quantity:b().describe("Quantity to trade as a decimal string")})},async({tradingPairId:t,side:r,price:n,quantity:o})=>{let s=await(await X()).fees.simulateFees({tradingPairId:t,side:r,price:n,quantity:o});return L(s)})}function rj(e){tj(e),ej(e)}function nj(e){e.registerTool("get_available_collateral",{description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",inputSchema:T({asset:b().optional().describe("Optional collateral asset symbol or ID to scope the query")})},async({asset:t})=>{let n=await(await X()).marginAccounts.getAvailableCollateral({asset:t});return L(n)})}function oj(e){e.registerTool("get_margin_accounts",{description:"List your margin accounts with optional filters (state, trading pair).",inputSchema:T({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),state:b().optional().describe("Filter by margin account state"),tradingPairId:b().optional().describe("Filter by trading pair UUID")})},async({page:t,pageSize:r,state:n,tradingPairId:o})=>{let s=await(await X()).marginAccounts.listMarginAccounts({page:t,pageSize:r,state:n,tradingPairId:o});return L(s)})}function ij(e){e.registerTool("get_parent_margin_account_movements",{description:"List collateral movements for your parent (cross) margin account.",inputSchema:T({movementType:b().optional().describe("Filter by movement type"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({movementType:t,page:r,pageSize:n})=>{let i=await(await X()).marginAccounts.getParentMarginAccountMovements({movementType:t,page:r,pageSize:n});return L(i)})}function sj(e){e.registerTool("get_parent_margin_account_summary",{description:"Get your parent (cross) margin account summary.",inputSchema:T({tradingPairId:b().optional().describe("Optional trading pair UUID to scope the summary")})},async({tradingPairId:t})=>{let n=await(await X()).marginAccounts.getParentMarginAccountSummary({tradingPairId:t});return L(n)})}function aj(e){e.registerTool("simulate_parent_margin_order_risk",{description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:G(["LIMIT","MARKET"]).describe("Order type"),quantity:b().describe("Order quantity as a decimal string"),price:b().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:b().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:ue().optional().describe("Whether the order can only reduce exposure")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]})},async({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a})=>{let d=await(await X()).marginAccounts.simulateParentMarginOrderRisk({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a});return L(d)})}function cj(e){e.registerTool("simulate_risk_bucket_order_risk",{description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:G(["LIMIT","MARKET"]).describe("Order type"),quantity:b().describe("Order quantity as a decimal string"),price:b().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:b().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:ue().optional().describe("Whether the order can only reduce exposure"),marginMode:G(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),strategyKey:b().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),selectedTradingPairIds:Ce(b()).optional().describe("Cross risk bucket trading pair UUIDs (CROSS only; must include tradingPairId)")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.marginMode!=="CROSS"||t.selectedTradingPairIds!==void 0&&t.selectedTradingPairIds.length>0,{message:"selectedTradingPairIds is required for CROSS risk buckets",path:["selectedTradingPairIds"]}).refine((t)=>t.marginMode!=="CROSS"||t.selectedTradingPairIds?.includes(t.tradingPairId),{message:"selectedTradingPairIds must include tradingPairId for CROSS risk buckets",path:["selectedTradingPairIds"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode==="CROSS"||t.selectedTradingPairIds===void 0,{message:"selectedTradingPairIds is only allowed for CROSS risk buckets",path:["selectedTradingPairIds"]})},async({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a,marginMode:c,strategyKey:d,selectedTradingPairIds:l})=>{let p=await X(),m={tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a},h=c==="CROSS"?await p.marginAccounts.simulateRiskBucketOrderRisk({...m,marginMode:c,selectedTradingPairIds:l??[]}):await p.marginAccounts.simulateRiskBucketOrderRisk({...m,marginMode:c,strategyKey:d});return L(h)})}function uj(e){e.registerTool("transfer_collateral_from_parent_margin_account",{description:"Move collateral out of your parent (cross) margin account back to spot.",inputSchema:T({asset:b().describe("Collateral asset symbol or ID"),amount:b().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await X()).marginAccounts.transferCollateralFromParentMarginAccount({asset:t,amount:r});return L(o)})}function dj(e){e.registerTool("transfer_collateral_to_parent_margin_account",{description:"Move collateral from spot into your parent (cross) margin account.",inputSchema:T({asset:b().describe("Collateral asset symbol or ID"),amount:b().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await X()).marginAccounts.transferCollateralToParentMarginAccount({asset:t,amount:r});return L(o)})}function lj(e){e.registerTool("transfer_collateral_to_risk_bucket",{description:"Allocate collateral into an isolated or cross risk bucket. A cross transfer names no pairs: cross scope is derived from trading (a pair joins the cross bucket when a cross order on it succeeds and leaves when its positions close).",inputSchema:T({asset:b().describe("Collateral asset symbol or ID"),amount:b().describe("Amount to transfer as a decimal string"),marginMode:G(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),tradingPairId:b().optional().describe("Trading pair UUID (required for ISOLATED; not allowed for CROSS)"),strategyKey:b().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),applyToPositionMargin:ue().optional().describe("ISOLATED only. Omitted/true (Adjust Margin, the default): commit the amount to the sole open position's stored margin — leverage drops and stays down, initial margin required rises, free collateral is unchanged. false: plain allocation — free collateral rises and the next order can spend it; funding loops targeting free collateral MUST pass false.")}).strict().refine((t)=>t.marginMode==="CROSS"||t.tradingPairId!==void 0,{message:"tradingPairId is required for ISOLATED risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.tradingPairId===void 0,{message:"tradingPairId is not allowed for CROSS risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode!=="CROSS"||t.applyToPositionMargin===void 0,{message:"applyToPositionMargin is only allowed for ISOLATED risk buckets",path:["applyToPositionMargin"]})},async({asset:t,amount:r,marginMode:n,tradingPairId:o,strategyKey:i,applyToPositionMargin:s})=>{let a=await X(),c=n==="CROSS"?await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n}):await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n,tradingPairId:o??"",strategyKey:i,applyToPositionMargin:s});return L(c)})}function pj(e){oj(e),sj(e),nj(e),ij(e),aj(e),cj(e),dj(e),uj(e),lj(e)}function fj(e){e.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),interval:G(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:M().optional().describe("Start time as Unix timestamp (seconds)"),endTime:M().optional().describe("End time as Unix timestamp (seconds)"),limit:M().optional().describe("Max number of candlesticks to return")})},async({tradingPairId:t,interval:r,startTime:n,endTime:o,limit:i})=>{let a=await Ze().market.getCandlesticks(t,r,{startTime:n,endTime:o,limit:i});return L(a)})}function mj(e){e.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getMarketMetadata(t);return L(n)})}function hj(e){e.registerTool("get_market_stats",{description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets."},async()=>{let r=await Ze().market.getMarketStats();return L(r)})}function gj(e){e.registerTool("get_screener",{description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",inputSchema:T({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),marketType:G(["SPOT","MARGIN"]).optional().describe("Filter by market type"),isActive:ue().optional().describe("Filter by active status"),category:b().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async({page:t,pageSize:r,marketType:n,isActive:o,category:i})=>{let a=await Ze().market.getScreener({page:t,pageSize:r,marketType:n,isActive:o,category:i});return L(a)})}function yj(e){e.registerTool("get_trading_pair_by_symbol",{description:"Look up a specific trading pair by its symbol (e.g. 'BTC/USDC'). Returns the pair's full details including its UUID.",inputSchema:T({symbol:b().describe("Trading pair symbol (e.g. 'BTC/USDC')")})},async({symbol:t})=>{let n=await Ze().market.getTradingPairBySymbol(t);if(!n)return dx(`Trading pair '${t}' not found.`);return L(n)})}function bj(e){e.registerTool("get_trading_pairs",{description:"Get a paginated list of trading pairs available on Monaco. Returns pair IDs, symbols, base/quote tokens, and status.",inputSchema:T({page:M().optional().describe("Page number (starts from 1)"),pageSize:M().optional().describe("Number of items per page (max 100)"),marketType:G(["SPOT","MARGIN"]).optional().describe("Filter by market type"),baseToken:b().optional().describe("Filter by base token"),quoteToken:b().optional().describe("Filter by quote token"),isActive:ue().optional().describe("Filter by active status"),category:b().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async(t)=>{let n=await Ze().market.getPaginatedTradingPairs(t);return L(n)})}function xj(e){bj(e),yj(e),fj(e),mj(e),gj(e),hj(e)}function _j(e){e.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),depth:M().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:G(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:M().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:G(["BASE","QUOTE"]).optional().describe("Quantity denomination: BASE or QUOTE")})},async({tradingPairId:t,depth:r,tradingMode:n,magnitude:o,denomination:i})=>{let a=await Ze().orderbook.getOrderbook(t,{depth:r,tradingMode:n,magnitude:o,denomination:i});return L(a)})}function wj(e){_j(e)}function Sj(e){e.registerTool("get_all_funding_history",{description:"List historical funding-rate records across all perpetual markets.",inputSchema:T({startTime:b().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:b().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),orderBy:G(["ASC","DESC"]).optional().describe("Sort order by time")})},async({startTime:t,endTime:r,page:n,pageSize:o,orderBy:i})=>{let a=await Ze().market.listAllFundingHistory({startTime:t,endTime:r,page:n,pageSize:o,orderBy:i});return L(a)})}function vj(e){e.registerTool("get_funding_history",{description:"List historical funding-rate records for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),startTime:b().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:b().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),orderBy:G(["ASC","DESC"]).optional().describe("Sort order by time")})},async({tradingPairId:t,startTime:r,endTime:n,page:o,pageSize:i,orderBy:s})=>{let c=await Ze().market.listFundingHistory(t,{startTime:r,endTime:n,page:o,pageSize:i,orderBy:s});return L(c)})}function Tj(e){e.registerTool("get_funding_state",{description:"Get the current funding rate and next funding time for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getFundingState(t);return L(n)})}function Ej(e){e.registerTool("get_index_price",{description:"Get the current index (oracle) price for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getIndexPrice(t);return L(n)})}function Pj(e){e.registerTool("get_mark_price",{description:"Get the current mark price for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getMarkPrice(t);return L(n)})}function Aj(e){e.registerTool("get_open_interest",{description:"Get the current open interest for a perpetual market.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getOpenInterest(t);return L(n)})}function Ij(e){e.registerTool("get_perp_market_config",{description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getPerpMarketConfig(t);return L(n)})}function kj(e){e.registerTool("get_perp_market_summary",{description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getPerpMarketSummary(t);return L(n)})}function Rj(e){Ij(e),kj(e),Pj(e),Ej(e),Tj(e),Aj(e),vj(e),Sj(e)}function Oj(e){e.registerTool("check_trader_code_availability",{description:"Public advisory check of whether a custom PitPass TraderCode handle is available. Returns `available` and, when unavailable, a `reason` (one of taken, too_short, too_long, reserved, invalid_char, looks_like_address). Advisory only — the authoritative gate is the atomic claim in set_trader_code, so a positive result is not a reservation.",inputSchema:T({code:b().describe("The custom handle to check for availability.")})},async({code:t})=>{let n=await Ze().pitpass.checkTraderCodeAvailability(t);return L(n)})}function Cj(e){e.registerTool("clear_trader_code",{description:"Clear the authenticated caller's custom PitPass TraderCode handle, reverting to the wallet-derived default. The freed handle enters a cooldown before anyone else can claim it. Returns the caller's TraderCode identity after the revert.",inputSchema:T({})},async()=>{let r=await(await X()).pitpass.clearTraderCode();return L(r)})}function Mj(e){e.registerTool("get_my_trader_code",{description:"Return the authenticated caller's PitPass TraderCode — their normalized wallet address. Clients render it as `Monaco - <address>`. Never 404s; ensures the backing row so referrals attributed to this wallet link correctly.",inputSchema:T({})},async()=>{let r=await(await X()).pitpass.getMyTraderCode();return L(r)})}function $j(e){e.registerTool("get_rewards_balance",{description:"Return the authenticated caller's current PitPass rewards-bucket balances across all reward tokens. Returns an empty list when no rewards have been earned yet. Use transfer_rewards to move earned rewards into a tradeable balance.",inputSchema:T({})},async()=>{let r=await(await X()).pitpass.getRewardsBalance();return L(r)})}function Nj(e){e.registerTool("get_trader_code_info",{description:"Public lookup of a PitPass TraderCode (wallet address or 'Monaco - <address>' form). Returns the resolved normalized code when it belongs to a known wallet, or a 404 error if not found. Use this to validate a referral code before sign-up.",inputSchema:T({code:b().describe("The TraderCode to look up — a wallet address (0x-prefixed) or the 'Monaco - <address>' display form.")})},async({code:t})=>{let n=await Ze().pitpass.getTraderCodeInfo(t);return L(n)})}function zj(e){e.registerTool("set_trader_code",{description:"Claim or edit the authenticated caller's custom (vanity) PitPass TraderCode handle. Stored exactly as entered (case preserved); uniqueness is case-insensitive. Must start with a letter and be 5–20 characters of letters, digits, or underscores. The server is the authoritative gate: 409 if the handle is taken, 422 on validation failure, 429 when the per-hour edit limit is hit, 403 when the feature is disabled.",inputSchema:T({code:b().describe("The custom handle to claim or edit to — letter-first [A-Za-z0-9_], 5–20 characters. Case is preserved.")})},async({code:t})=>{let n=await(await X()).pitpass.setTraderCode(t);return L(n)})}function Bj(e){e.registerTool("transfer_rewards",{description:"Transfer earned PitPass rewards from your rewards bucket into your trading balance, making them immediately tradeable. Ledger-only — no on-chain transaction. Fails if the rewards balance is insufficient.",inputSchema:T({token:b().describe("Reward token contract address (0x-prefixed EVM address) to transfer."),amount:b().describe("Amount to transfer in RAW atomic units of the token (positive integer string).")})},async({token:t,amount:r})=>{let o=await(await X()).pitpass.transferRewards({token:t,amount:r});return L(o)})}function Lj(e){Nj(e),Oj(e)}function Dj(e){Mj(e),$j(e),Bj(e),zj(e),Cj(e)}function Uj(e){e.registerTool("get_portfolio_assets",{description:"Get your per-asset portfolio allocation and balances over a period.",inputSchema:T({period:G(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getAssets({period:t});return L(n)})}function Fj(e){e.registerTool("get_portfolio_margin",{description:"Get your portfolio margin overview (collateral, maintenance margin, health)."},async()=>{let r=await(await X()).portfolio.getMargin();return L(r)})}function jj(e){e.registerTool("get_portfolio_performance",{description:"Get your portfolio performance time series over a period.",inputSchema:T({period:G(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getPerformance({period:t});return L(n)})}function qj(e){e.registerTool("get_portfolio_realized_pnl",{description:"Get your realized PnL breakdown over a period.",inputSchema:T({period:G(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getRealizedPnl({period:t});return L(n)})}function Hj(e){e.registerTool("get_portfolio_summary",{description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",inputSchema:T({period:G(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getSummary({period:t});return L(n)})}function Gj(e){Hj(e),jj(e),qj(e),Uj(e),Fj(e)}function Vj(e){e.registerTool("close_position",{description:"Close a perpetual position with a market, limit, or IOC reduce order.",inputSchema:T({positionId:b().describe("Position UUID"),closeType:G(["MARKET","LIMIT","IOC"]).describe("Close order type"),limitPrice:b().optional().describe("Limit price as a decimal string — required for LIMIT and IOC, not allowed for MARKET"),slippageToleranceBps:M().optional().describe("Slippage tolerance in basis points (MARKET/IOC)"),quantity:b().optional().describe("Quantity to close as a decimal string (defaults to full position)")}).refine((t)=>t.closeType==="MARKET"||t.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["limitPrice"]}).refine((t)=>t.closeType!=="MARKET"||t.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["limitPrice"]})},async({positionId:t,closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i})=>{let a=await(await X()).positions.closePosition(t,{closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i});return L(a)})}function Zj(e){e.registerTool("get_position",{description:"Get details for a specific perpetual position by ID.",inputSchema:T({positionId:b().describe("Position UUID")})},async({positionId:t})=>{let n=await(await X()).positions.getPosition(t);return L(n)})}function Wj(e){e.registerTool("get_position_history",{description:"List historical (closed/reduced) perpetual position records with optional filters.",inputSchema:T({positionId:b().optional().describe("Filter by position UUID"),marginAccountId:b().optional().describe("Filter by margin account UUID"),tradingPairId:b().optional().describe("Filter by trading pair UUID"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),reductionOnly:ue().optional().describe("Only include reduction events")})},async({positionId:t,marginAccountId:r,tradingPairId:n,page:o,pageSize:i,reductionOnly:s})=>{let c=await(await X()).positions.listPositionHistory({positionId:t,marginAccountId:r,tradingPairId:n,page:o,pageSize:i,reductionOnly:s});return L(c)})}function Kj(e){e.registerTool("get_position_pnl_history",{description:"Get the PnL history time series for a perpetual position over an interval.",inputSchema:T({positionId:b().describe("Position UUID"),interval:G(["1m","5m","15m","1h","4h","1d"]).describe("Sampling interval"),startTime:M().int().min(0).optional().describe("Start time as a Unix timestamp in milliseconds"),endTime:M().int().min(0).optional().describe("End time as a Unix timestamp in milliseconds")}).refine((t)=>t.startTime===void 0||t.endTime===void 0||t.startTime<t.endTime,{message:"startTime must be less than endTime",path:["startTime"]})},async({positionId:t,interval:r,startTime:n,endTime:o})=>{let s=await(await X()).positions.getPositionPnlHistory(t,{interval:r,startTime:n,endTime:o});return L(s)})}function Yj(e){e.registerTool("get_position_risk",{description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",inputSchema:T({positionId:b().describe("Position UUID")})},async({positionId:t})=>{let n=await(await X()).positions.getPositionRisk(t);return L(n)})}function Jj(e){e.registerTool("get_positions",{description:"List your perpetual positions with optional filters (margin account, trading pair, status).",inputSchema:T({marginAccountId:b().optional().describe("Filter by margin account UUID"),tradingPairId:b().optional().describe("Filter by trading pair UUID"),status:G(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"]).optional().describe("Filter by position status"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({marginAccountId:t,tradingPairId:r,status:n,page:o,pageSize:i})=>{let a=await(await X()).positions.listPositions({marginAccountId:t,tradingPairId:r,status:n,page:o,pageSize:i});return L(a)})}function Qj(e){Jj(e),Zj(e),Yj(e),Wj(e),Kj(e),Vj(e)}function Xj(e){e.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:T({assetId:b().describe("The asset UUID")})},async({assetId:t})=>{let n=await(await X()).profile.getUserBalanceByAssetId(t);return L(n)})}function eq(e){e.registerTool("get_balances",{description:"Get the authenticated user's token balances with pagination.",inputSchema:T({page:M().optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().optional().describe("Number of items per page (default: 20, max: 100)")})},async({page:t,pageSize:r})=>{let o=await(await X()).profile.getUserBalances({page:t,pageSize:r});return L(o)})}function tq(e){e.registerTool("get_funding_payments",{description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",inputSchema:T({tradingPairId:b().optional().describe("Filter by trading pair UUID"),positionId:b().optional().describe("Filter by position UUID"),marginAccountId:b().optional().describe("Filter by margin account UUID"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({tradingPairId:t,positionId:r,marginAccountId:n,page:o,pageSize:i})=>{let a=await(await X()).profile.listFundingPayments({tradingPairId:t,positionId:r,marginAccountId:n,page:o,pageSize:i});return L(a)})}function rq(e){e.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history) with pagination.",inputSchema:T({page:M().int().min(1).optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().int().min(1).max(100).optional().describe("Items per page (default: 20, max: 100)"),entryType:G(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:G(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"]).optional().describe("Filter by transaction type (e.g. DEPOSIT, WITHDRAWAL, TRADE, FEE, FUNDING, LIQUIDATION, INTEREST, REWARD)"),assetId:b().uuid().optional().describe("Filter by asset ID (UUID)")})},async({page:t,pageSize:r,entryType:n,transactionType:o,assetId:i})=>{let a=await(await X()).profile.getPaginatedUserMovements({page:t,pageSize:r,entryType:n,transactionType:o,assetId:i});return L(a)})}function nq(e){e.registerTool("get_profile",{description:"Get the authenticated user's profile including address, username, account type, and withdrawal status. Use get_balances, get_movements, and get_orders for detailed account data."},async()=>{let r=await(await X()).profile.getProfile();return L(r)})}function oq(e){e.registerTool("get_user_trades",{description:"List your own trade fills with optional filters and cursor pagination.",inputSchema:T({tradingPairId:b().optional().describe("Filter by trading pair UUID"),pageSize:M().optional().describe("Items per page"),pageToken:b().optional().describe("Cursor for the next page"),page:M().optional().describe("Page number (legacy offset mode; prefer pageToken)")})},async({tradingPairId:t,pageSize:r,pageToken:n,page:o})=>{let s=await(await X()).profile.getUserTrades({tradingPairId:t,pageSize:r,pageToken:n,page:o});return L(s)})}function iq(e){nq(e),eq(e),Xj(e),rq(e),oq(e),tq(e)}function sq(e){e.registerTool("get_pulse",{description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags."},async()=>{let r=await Ze().pulse.getPulse();return L(r)})}function aq(e){sq(e)}var Sle="https://docs.0xmonaco.com/mcp",vle="SearchMonacoDocs",lx=null;async function cq(e,t,r){let n=await fetch(Sle,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...lx?{"Mcp-Session-Id":lx}:{}},body:JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t})});if(!n.ok)throw Error(`Mintlify MCP error: ${n.status}`);let o=n.headers.get("mcp-session-id");if(o)lx=o;let s=(await n.text()).split(`
|
|
152
|
+
`).find((a)=>a.startsWith("data: "));if(!s)throw Error("No data in Mintlify MCP response");return JSON.parse(s.slice(6))}async function Tle(){if(lx)return;await cq("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:w0.version}},0)}async function Ele(e){return await Tle(),(await cq("tools/call",{name:vle,arguments:{query:e}},1))?.result}function uq(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:T({query:b().describe("The search query")})},async({query:t})=>{try{let r=await Ele(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return L(r)}catch(r){return dx(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function dq(e){uq(e)}function lq(e){e.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),page:M().optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:t,page:r,pageSize:n})=>{let i=await Ze().trades.getTrades(t,{page:r,pageSize:n});return L(i)})}function pq(e){lq(e)}function fq(e){e.registerTool("batch_cancel_all_orders",{description:"Cancel EVERY one of your open orders in one call. Destructive and unfiltered by default — with no tradingPairId it cancels your entire open-order book across all pairs; pass a tradingPairId to limit it to that pair.",inputSchema:T({tradingPairId:b().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let n=await(await X()).trading.batchCancelAll(t);return L(n)})}function mq(e){e.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request. Non-atomic and best-effort: each order is cancelled independently, so a failed leg does not stop the others. Inspect the per-order results and reconcile (retry or re-check) any that did not cancel.",inputSchema:T({orderIds:Ce(b()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let n=await(await X()).trading.batchCancel(t);return L(n)})}function hq(e){e.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to a specific trading pair. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:T({tradingPairId:b().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:M().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:t,slippageToleranceBps:r})=>{let o=await(await X()).positions.batchCloseAllPositions({tradingPairId:t,slippageToleranceBps:r});return L(o)})}function gq(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:T({orderId:b().describe("The order ID to cancel")})},async({orderId:t})=>{let n=await(await X()).trading.cancelOrder(t);return L(n)})}function yq(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:T({orderId:b().describe("The order ID to look up")})},async({orderId:t})=>{let n=await(await X()).trading.getOrder(t);return L(n)})}var Ple=T({applicationId:b().uuid(),enrolled:ue(),payoutAddress:b().nullable().optional(),buildercodesEnabled:ue(),buildercodesBudgetBps:M().int().min(0).max(1e4)}),Ale=T({page:M().int().min(1).max(1e4).optional(),pageSize:M().int().min(1).max(100).optional()}),bq=T({tradeId:b().uuid(),payoutAddress:b(),token:b(),amount:b(),appliedBps:M().int(),createdAt:b()}),Ile=T({payouts:Ce(bq),total:M().int().nonnegative(),page:M().int().positive(),pageSize:M().int().positive(),totalPages:M().int().nonnegative()}),xq=T({token:b(),totalAmount:b(),payoutCount:M().int().nonnegative(),lastCreditedAt:b()}),kle=T({totalPayouts:M().int().nonnegative(),lastCreditedAt:b().nullable().optional(),byToken:Ce(xq)}),_q=T({token:b(),available:b()}),Rle=T({balances:Ce(_q)}),Ole=T({token:b().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:b().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Cle=T({payoutBalance:b(),tradingBalance:b()});var Mle=T({tradingPairId:b().trim().min(1,"Trading pair ID is required and cannot be empty"),side:G(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:b().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:b().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:G(["LIMIT","MARKET"]).optional(),slippageToleranceBps:M().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:Go.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),$le=T({applicationName:b().nullable().optional(),applicationTakerFee:b(),applicationTakerFeeBps:M(),buyOrderLockAmount:b().nullable().optional(),makerTotalReceipt:b(),monacoMakerRebate:b(),monacoMakerRebateBps:M(),monacoMakerRebateBpsExact:b(),monacoTakerFee:b(),monacoTakerFeeBps:M(),monacoTakerFeeBpsExact:b(),notional:b(),takerTotalPayment:b(),totalTakerFees:b(),maxQuantity:b().nullable(),maxQuantityRaw:b().nullable(),slippageToleranceBps:M().nullable()}),Nle=T({tradingPairId:b().trim().min(1,"Trading pair ID is required and cannot be empty")}),wq=T({tierLevel:M().int(),minVolumeThreshold:b(),makerFeeBps:b(),takerFeeBps:b()}),zle=T({currentTierLevel:M().int(),weightedVolume14d:b(),spotVolume14d:b(),perpVolume14d:b(),volumeToNextTier:b().nullable().optional(),nextTierLevel:M().int().nullable().optional(),feeSchedule:Ce(wq)});var Sq=T({token:b(),available:b()}),Ble=T({balances:Ce(Sq)}),Lle=T({code:b(),createdAt:b(),customCode:b(),isCustom:ue(),display:b()}),vq=G(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Dle=T({available:ue(),reason:Bp((e)=>e===""||e===null?void 0:e,vq.optional())}),Ule=T({code:b().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")}),Fle=T({code:b()}),jle=T({token:b().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:b().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),qle=T({rewardsBalance:b(),tradingBalance:b()});var Ol=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Cl=G(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),Nm=G(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),hx=G(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),zm=G(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),Tq=G(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),JA=G(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Kc=G(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Ml=G(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),dt=b().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),Re=R5({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Ra=Ou.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),Eq=M().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Bm=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),Hle=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),px=T({triggerPrice:dt,orderType:Ml,limitPrice:dt.optional(),quantity:dt.optional(),closePosition:ue().optional(),timeInForce:JA.optional(),slippageToleranceBps:Bm.optional(),expiresAt:Ra.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"]}),fx=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,QA=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),XA=b().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),gzt=T({tradingPairId:Re,side:Cl,quantity:dt,price:dt,options:T({idempotencyKey:XA.optional(),tradingMode:Nm.optional(),useMasterBalance:ue().optional(),expirationDate:Ra.optional(),timeInForce:Tq.optional(),marginAccountId:Re.optional(),marginMode:hx.optional(),riskBucketId:Re.optional(),riskBucketCollateral:dt.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:zm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional(),takeProfit:px.optional(),stopLoss:px.optional()}).optional()}).refine((e)=>QA(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)=>!fx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!fx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),yzt=T({tradingPairId:Re,side:Cl,quantity:dt,options:T({idempotencyKey:XA.optional(),tradingMode:Nm.optional(),slippageTolerance:Eq,marginAccountId:Re.optional(),marginMode:hx.optional(),riskBucketId:Re.optional(),riskBucketCollateral:dt.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:zm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),selfTradePreventionMode:Kc.optional(),takeProfit:px.optional(),stopLoss:px.optional()}).optional()}).refine((e)=>QA(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)=>!fx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!fx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),bzt=T({orderId:Re,remainingQuantityTarget:dt.optional()}),xzt=T({orderId:Re,newOrder:T({price:dt.optional(),quantity:dt.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()})}),_zt=T({status:st([G(Ol),Ce(G(Ol)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Re.optional(),tradingMode:Nm.optional(),marginAccountId:Re.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:b().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Go.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),wzt=G(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),Szt=G(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),Gle=G(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),vzt=G(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),Tzt=T({conditionalOrderId:Re}),Ezt=T({marginAccountId:Re.optional(),tradingPairId:Re.optional(),state:Gle.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Vle=G(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),Zle=st([M().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),b().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Wle=2592000000,Pzt=T({tradingPairId:Re,side:Cl,quantity:dt,options:T({durationSeconds:Zle.optional(),startTime:Ra.optional(),endTime:Ra.optional(),limitPrice:dt.optional(),slippageToleranceBps:Hle.optional(),randomize:ue().optional(),executionStyle:G(["TAKER","PASSIVE"]).optional(),reduceOnly:ue().optional(),tradingMode:Nm.optional(),marginAccountId:Re.optional(),riskBucketId:Re.optional(),marginMode:hx.optional(),leverage:dt.optional(),strategyKey:b().min(1).max(128).optional(),useMasterBalance:ue().optional(),clientTwapId:b().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:dt.optional(),triggerDirection:G(["ABOVE","BELOW"]).optional(),conditionalExpiry:Ra.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).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()<=Wle},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),Azt=T({twapOrderId:Re}),Izt=T({state:Vle.optional(),tradingPairId:Re.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Kle=T({tradingPairId:Re,orderType:Ml,side:Cl,price:dt.optional(),quantity:dt,idempotencyKey:XA.optional(),tradingMode:Nm.optional(),slippageTolerance:Eq,useMasterBalance:ue().optional(),expirationDate:Ra.optional(),timeInForce:Tq.optional(),marginAccountId:Re.optional(),marginMode:hx.optional(),riskBucketId:Re.optional(),riskBucketCollateral:dt.optional(),strategyKey:b().min(1).max(128).optional(),positionSide:zm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>QA(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"]}),mx=100,kzt=T({orders:Ce(Kle).min(1,"At least one order is required").max(mx,`At most ${mx} orders per batch request`)}),Yle=T({orderId:Re,price:dt.optional(),quantity:dt.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),Rzt=T({orders:Ce(Yle).min(1,"At least one order is required").max(mx,`At most ${mx} orders per batch request`)});var eI=T({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),$zt=eI.extend({state:b().trim().min(1,"State cannot be empty").optional(),tradingPairId:Re.optional()}),Nzt=T({marginAccountId:Re,tradingPairId:Re.optional()}),zzt=T({tradingPairId:Re.optional()}).optional(),Bzt=T({asset:b().trim().min(1,"Asset cannot be empty").optional()}).optional(),Jle=T({asset:b().trim().min(1,"Asset cannot be empty"),amount:dt,tradingPairId:Re.optional(),strategyKey:b().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:G(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),gx=T({asset:b().trim().min(1,"Asset cannot be empty"),amount:dt}),Qle=T({tradingPairId:Re,strategyKey:b().trim().min(1,"Strategy key cannot be empty").optional()}),Xle=Ce(Re).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),Pq=Qle.extend({marginMode:_e("ISOLATED").optional(),selectedTradingPairIds:uo().optional(),applyToPositionMargin:ue().optional()}),epe=T({marginMode:_e("CROSS"),selectedTradingPairIds:Xle,strategyKey:uo().optional()}),tpe=T({marginMode:_e("CROSS"),selectedTradingPairIds:uo().optional(),strategyKey:uo().optional(),tradingPairId:uo().optional()}),Lzt=T({marginAccountId:Re,request:Jle}),Dzt=T({request:gx}),rpe=T({marginMode:G(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.marginMode==="CROSS"&&e.selectedTradingPairIds!==void 0)t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare"})}),Uzt=T({request:rpe.pipe(st([gx.merge(Pq).strict(),gx.merge(tpe).strict()]))}),Fzt=T({request:gx}),jzt=eI.extend({marginAccountId:Re,movementType:b().trim().min(1,"Movement type cannot be empty").optional()}),qzt=eI.extend({movementType:b().trim().min(1,"Movement type cannot be empty").optional()}).optional(),tI=T({tradingPairId:Re,side:Cl,positionSide:zm.optional(),orderType:Ml,price:dt.optional(),quantity:dt,leverage:dt.optional(),reduceOnly:ue().optional()}),rI=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:Go.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:Go.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},Aq=tI.strict().superRefine(rI),npe=tI.merge(Pq).strict().superRefine(rI),ope=tI.merge(epe).strict().superRefine(rI).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),ipe=st([npe,ope]),Hzt=T({marginAccountId:Re,request:Aq}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Gzt=T({request:Aq}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Vzt=T({request:ipe}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var Iq=G(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),spe=31536000000,ape=946684800000,yx=M().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(ape,{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()+spe,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),Yzt=T({tradingPairId:Re,interval:Iq,startTime:yx,endTime:yx}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),Jzt=b().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")'}),cpe=M().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),Qzt=T({tradingPairId:Re,interval:Iq,startTime:yx.optional(),endTime:yx.optional(),limit:cpe,priceType:G(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var Xzt=T({tradingPairId:Re}),eBt=T({query:b().min(1,"Search query cannot be empty").optional(),pageSize:M().int().min(1).max(100).optional(),page:M().int().min(1).optional()}),tBt=T({tradingPairId:Re});var Rq=T({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),upe=G(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),dpe=G(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),nI=T({positionId:Re}),iBt=Rq.extend({marginAccountId:Re.optional(),tradingPairId:Re.optional(),status:upe.optional()});var sBt=nI.extend({request:T({closeType:dpe,limitPrice:dt.optional(),slippageToleranceBps:Bm.optional(),quantity:dt.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"]}),aBt=T({tradingPairId:Re.optional(),slippageToleranceBps:Bm.optional()});var kq=T({triggerPrice:dt,orderType:Ml,limitPrice:dt.optional(),quantity:dt.optional(),closePosition:ue().optional(),timeInForce:JA.optional(),slippageToleranceBps:Bm.optional(),expiresAt:Ra.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"]}),cBt=nI.extend({request:T({takeProfit:kq.optional(),stopLoss:kq.optional(),oco:ue().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),uBt=Rq.extend({positionId:Re.optional(),marginAccountId:Re.optional(),tradingPairId:Re.optional(),reductionOnly:ue().optional()}),lpe=G(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),dBt=nI.extend({params:T({interval:lpe,startTime:M().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:M().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 ppe=G(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),fpe=G(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),mBt=T({mode:Kc}),hBt=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:ppe.optional(),transactionType:fpe.optional(),assetId:Re.optional()}),gBt=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:Re.optional(),pageToken:b().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Go.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),yBt=T({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:Re.optional(),positionId:Re.optional(),marginAccountId:Re.optional()});var wBt=b().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),oI=st([b().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),C5().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),SBt=T({assetId:Re,amount:oI,autoWait:ue().optional()}),vBt=T({assetId:Re,amount:oI,autoWait:ue().optional(),target:G(["spot","margin"]).optional(),options:T({asErc20:ue().optional()}).optional()}),TBt=T({assetId:Re,amount:oI,destination:b().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:ue().optional(),source:G(["spot","margin"]).optional()}),EBt=T({assetId:Re});function Oq(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit both page and pageToken for the newest orders; pass the previous response's nextPageToken to fetch the next page. A response with zero orders and an empty nextPageToken means the walk is exhausted. Cursor responses have no exact totals (total/totalPages are 0).",inputSchema:T({status:G(Ol).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:b().optional().describe("Filter by trading pair UUID"),page:M().optional().describe("Deprecated: page number for legacy offset pagination, which only sees recent history. Use pageToken instead."),pageSize:M().optional().describe("Orders per page (default: 10; max 100 in legacy page mode, up to 1000 with pageToken)"),pageToken:b().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it (and page) to start from the newest orders.")})},async({status:t,tradingPairId:r,page:n,pageSize:o,pageToken:i})=>{let a=await(await X()).trading.getPaginatedOrders({status:t,tradingPairId:r,page:n,pageSize:o,pageToken:i});return L(a)})}function Cq(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. Limit orders execute only when the market reaches the specified price. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side"),quantity:b().describe("Order quantity as a decimal string"),price:b().describe("Limit price as a decimal string"),tradingMode:G(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:G(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:b().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:b().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:G(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:b().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:b().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:b().optional().describe("Optional client strategy key"),positionSide:G(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:b().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:ue().optional().describe("Whether the order can only reduce existing exposure"),postOnly:ue().optional().describe("Maker-only: rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if this order would cross the book. GTC time in force only; rejected with IOC/FOK."),selfTradePreventionMode:G(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Per-order self-trade-prevention override for matches against your own resting orders. CANCEL_MAKER cancels your resting orders and keeps matching; CANCEL_TAKER cancels this order's remainder at the first self-touch; CANCEL_BOTH does both; SKIP trades around your orders and cancels a remainder that would cross them. Omitted, your wallet default applies, else the platform default CANCEL_MAKER. Echoed back as selfTradePreventionMode on order reads."),idempotencyKey:b().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:b().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests, and is released on fill/cancel/expiry/rejection, so a marketable order that fills on arrival never takes it. Never resubmit on a lost response without the original idempotencyKey — a resubmission can execute a second time. Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,price:o,tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:d,riskBucketId:l,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:_,selfTradePreventionMode:w,clientOrderId:A,idempotencyKey:S})=>{let P=await(await X()).trading.placeLimitOrder(t,r,n,o,{tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:d,riskBucketId:l,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:_,selfTradePreventionMode:w,clientOrderId:A,idempotencyKey:S});return L(P)})}function Mq(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. It executes immediately against resting liquidity, but only inside a mandatory 1,000 bps (10%) server-side protective price band anchored to the mark/last-trade reference price. Fills stop at the edge of the band, so a market order may partially fill and cancel the remainder, be rejected when no liquidity sits inside the band, or be rejected when the market has no trustworthy price anchor. Optional slippageTolerance is merged tighter-wins with this band: it can only TIGHTEN execution, never widen past the mandatory band; omitting it applies the full 1,000 bps band. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:T({tradingPairId:b().describe("Trading pair UUID"),side:G(["BUY","SELL"]).describe("Order side"),quantity:b().describe("Order quantity as a decimal string"),tradingMode:G(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:M().optional().describe("Tightens the mandatory 1,000 bps band, as a decimal (e.g. 0.01 for 1%; 0 for best price only). Can only tighten, never widen; omit to apply the full band."),marginAccountId:b().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:G(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:b().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:b().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:b().optional().describe("Optional client strategy key"),positionSide:G(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:b().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:ue().optional().describe("Whether the order can only reduce existing exposure"),idempotencyKey:b().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:b().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key. A market order never rests, so it never claims the handle and no duplicate-submission guard can fire for it: Without idempotencyKey, NEVER resubmit a market order on a lost response — it can execute again and increase your exposure (or reject, or fill at a different price; you cannot tell which in advance). Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:d,strategyKey:l,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y,idempotencyKey:x})=>{let w=await(await X()).trading.placeMarketOrder(t,r,n,{tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:d,strategyKey:l,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y,idempotencyKey:x});return L(w)})}function $q(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent, and MCP has no order-stream tool, so an ambiguous outcome (timeout, network error, or a 5xx with no order returned) CANNOT be resolved from inside MCP: do NOT retry. get_orders/get_order are replica-backed and an order rejected before acceptance is never written to them, so a missing row is not evidence the order failed. Check whether the position or balance moved, and otherwise report the ambiguity to the user rather than resubmitting. A retry here cannot double your exposure — replace names the original order id and a second attempt returns ORDER_NOT_FOUND once the first succeeded — but that code does not distinguish a landed replacement from an original that filled or was cancelled, so retrying still reports the wrong state.",inputSchema:T({orderId:b().describe("The order ID to replace"),price:b().optional().describe("New price as a decimal string"),quantity:b().optional().describe("New quantity as a decimal string"),postOnly:ue().optional().describe("Re-states maker-only intent for the replacement (nothing is inherited from the original order): rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if it would cross the book."),selfTradePreventionMode:G(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Re-states the per-order self-trade-prevention override for the replacement (nothing is inherited from the original order). Omitted, your wallet default applies, else the platform default CANCEL_MAKER."),clientOrderId:b().optional().describe("Client-assigned correlation handle for the replacement order, echoed back on order reads and order WebSocket events. Nothing is inherited from the original order — re-state it here to keep the handle across a requote. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests and is released on fill/cancel/expiry/rejection, so it cannot make a lost-response retry safe. Reconciling a lost response needs the order WebSocket stream, which is outside MCP — this server exposes no stream tool.")})},async({orderId:t,price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s})=>{let c=await(await X()).trading.replaceOrder(t,{price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s});return L(c)})}function Nq(e){Cq(e),Mq(e),gq(e),mq(e),fq(e),hq(e),$q(e),Oq(e),yq(e)}function zq(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:T({assetId:b().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let n=await(await X()).vault.getAllowance(t);return L({assetId:t,allowance:n.toString()})})}function Bq(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:T({assetId:b().describe("The asset UUID to approve"),amount:b().regex(/^\d+$/,"Must be a non-negative integer string").describe("Max amount to approve as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.approve(t,BigInt(r));return L({hash:o.hash,status:o.status})})}function Lq(e){e.registerTool("vault_deposit",{description:"Deposit tokens into the Monaco vault. Requires prior approval for ERC20 tokens (use vault_approve first). Set target to 'margin' to route the deposit straight into margin collateral instead of the spot wallet.",inputSchema:T({assetId:b().describe("The asset UUID to deposit"),amount:b().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to deposit as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)"),target:G(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:n})=>{let i=await(await X()).vault.deposit(t,BigInt(r),void 0,n);return L({hash:i.hash,status:i.status})})}function Dq(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:T({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({page:t,pageSize:r})=>{let o=await(await X()).withdrawals.listPendingWithdrawals({page:t,pageSize:r});return L(o)})}function Uq(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:T({assetId:b().describe("The asset UUID to check"),amount:b().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.needsApproval(t,BigInt(r));return L({assetId:t,amount:r,needs_approval:o})})}function Fq(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:T({assetId:b().describe("The asset UUID to withdraw"),amount:b().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to withdraw as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.withdraw(t,BigInt(r));return L({withdrawalIndex:o.withdrawalIndex,status:o.status,hash:o.hash})})}function jq(e){Bq(e),Lq(e),Fq(e),zq(e),Uq(e),Dq(e)}function mpe(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let n=YF(r);return[...e.slice(0,t),n]}function hpe(e,t){let[r,...n]=t;if(!r||typeof r!=="object")return t;let o=B4(e);if(!o)return t;let i=r.annotations;return[{...r,annotations:{...o,...i}},...n]}function qq(e,t,r){return new Proxy(e,{get(n,o,i){if(o==="registerTool")return(a,...c)=>{if(!j4(a,t))return;let d=hpe(a,c);if(r&&F4(a))d=mpe(d);return n.registerTool(a,...d)};let s=Reflect.get(n,o,i);return typeof s==="function"?s.bind(n):s}})}function Hq(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},n=qq(e,r,!1);if(dq(n),xj(n),Rj(n),wj(n),pq(n),Lj(n),aq(n),t.authenticated){let o=qq(e,r,!0);Nq(o),Qj(o),iq(o),Gj(o),pj(o),rj(o),jq(o),XF(o,{network:t.network}),Dj(o)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=gpe;if(!globalThis.fetch)globalThis.fetch=xh,globalThis.Headers=Zr,globalThis.Request=Ti,globalThis.Response=Ar;if(!globalThis.WebSocket)globalThis.WebSocket=x1.default;async function ype(){let e=lc(),t=e.privateKey!==null,r=new Pv({name:"monaco-mcp-server",version:w0.version});Hq(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let n=new Iv;await r.connect(n),console.error(t?`Monaco MCP server running on stdio (network=${e.network}, capability=${e.capability}). Fund-movement and privilege tools require MONACO_CAPABILITY=full or an explicit MONACO_TOOL_ALLOWLIST entry.`:"Monaco MCP server running on stdio (public read-only mode — set MONACO_PRIVATE_KEY, MONACO_CLIENT_ID and MONACO_NETWORK to enable authenticated tools).")}ype().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});
|