keyring-agent-core 0.3.23 → 0.3.24
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/index.js +2 -2
- package/dist/index.native.js +356 -417
- package/package.json +10 -3
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var Fz=Object.create;var Eg=Object.defineProperty;var qz=Object.getOwnPropertyDescriptor;var Hz=Object.getOwnPropertyNames;var $z=Object.getPrototypeOf,Vz=Object.prototype.hasOwnProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var jz=(e,t)=>()=>
|
|
1
|
+
"use strict";var Fz=Object.create;var Eg=Object.defineProperty;var qz=Object.getOwnPropertyDescriptor;var Hz=Object.getOwnPropertyNames;var $z=Object.getPrototypeOf,Vz=Object.prototype.hasOwnProperty;var L=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var jz=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},fr=(e,t)=>{for(var n in t)Eg(e,n,{get:t[n],enumerable:!0})},BL=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Hz(t))!Vz.call(e,o)&&o!==n&&Eg(e,o,{get:()=>t[o],enumerable:!(r=qz(t,o))||r.enumerable});return e};var ML=(e,t,n)=>(n=e!=null?Fz($z(e)):{},BL(t||!e||!e.__esModule?Eg(n,"default",{value:e,enumerable:!0}):n,e)),zz=e=>BL(Eg({},"__esModule",{value:!0}),e);var tU,nU=L(()=>{"use strict";tU="1.3.0"});var Ht,Uu=L(()=>{"use strict";nU();Ht=class e extends Error{constructor(t,n={}){let r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,o=n.cause instanceof e&&n.cause.docsPath||n.docsPath,s=[t||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...o?[`Docs: https://abitype.dev${o}`]:[],...r?[`Details: ${r}`]:[],`Version: abitype@${tU}`].join(`
|
|
2
2
|
`);super(s),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),n.cause&&(this.cause=n.cause),this.details=r,this.docsPath=o,this.metaMessages=n.metaMessages,this.shortMessage=t}}});function br(e,t){return e.exec(t)?.groups}var QP,XP,qy,Gm=L(()=>{"use strict";QP=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,XP=/^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)?$/,qy=/^\(.+?\).*?$/});function Hy(e){let t=e.type;if(rU.test(e.type)&&"components"in e){t="(";let n=e.components.length;for(let o=0;o<n;o++){let s=e.components[o];t+=Hy(s),o<n-1&&(t+=", ")}let r=br(rU,e.type);return t+=`)${r?.array||""}`,Hy({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}var rU,oU=L(()=>{"use strict";Gm();rU=/^tuple(?<array>(\[(\d*)\])*)$/});function Wo(e){let t="",n=e.length;for(let r=0;r<n;r++){let o=e[r];t+=Hy(o),r!==n-1&&(t+=", ")}return t}var JP=L(()=>{"use strict";oU()});function tl(e){return e.type==="function"?`function ${e.name}(${Wo(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${Wo(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${Wo(e.inputs)})`:e.type==="error"?`error ${e.name}(${Wo(e.inputs)})`:e.type==="constructor"?`constructor(${Wo(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}var sU=L(()=>{"use strict";JP()});function aU(e){return iU.test(e)}function lU(e){return br(iU,e)}function uU(e){return cU.test(e)}function dU(e){return br(cU,e)}function mU(e){return pU.test(e)}function hU(e){return br(pU,e)}function Bu(e){return fU.test(e)}function gU(e){return br(fU,e)}function bU(e){return yU.test(e)}function wU(e){return br(yU,e)}function kU(e){return vU.test(e)}function xU(e){return br(vU,e)}function AU(e){return BY.test(e)}var iU,cU,pU,fU,yU,vU,BY,ZP,TU,$y,Km=L(()=>{"use strict";Gm();iU=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;cU=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;pU=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;fU=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;yU=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;vU=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;BY=/^receive\(\) external payable$/;ZP=new Set(["memory","indexed","storage","calldata"]),TU=new Set(["indexed"]),$y=new Set(["calldata","memory","storage"])});var Vy,jy,zy,Wy=L(()=>{"use strict";Uu();Vy=class extends Ht{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}},jy=class extends Ht{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},zy=class extends Ht{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}});var Gy,Ky,Yy,Qy,Xy,Jy,Zy=L(()=>{"use strict";Uu();Gy=class extends Ht{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}},Ky=class extends Ht{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},Yy=class extends Ht{constructor({param:t,name:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${n}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},Qy=class extends Ht{constructor({param:t,type:n,modifier:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${r}" not allowed${n?` in "${n}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},Xy=class extends Ht{constructor({param:t,type:n,modifier:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${r}" not allowed${n?` in "${n}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${r}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},Jy=class extends Ht{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}});var Go,eb,tb,eE=L(()=>{"use strict";Uu();Go=class extends Ht{constructor({signature:t,type:n}){super(`Invalid ${n} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},eb=class extends Ht{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},tb=class extends Ht{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}});var nb,SU=L(()=>{"use strict";Uu();nb=class extends Ht{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}});var rb,PU=L(()=>{"use strict";Uu();rb=class extends Ht{constructor({current:t,depth:n}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${n>0?"opening":"closing"} parentheses.`],details:`Depth "${n}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}});function EU(e,t,n){let r="";if(n)for(let o of Object.entries(n)){if(!o)continue;let s="";for(let i of o[1])s+=`[${i.type}${i.name?`:${i.name}`:""}]`;r+=`(${o[0]}{${s}})`}return t?`${t}:${e}${r}`:`${e}${r}`}var ob,RU=L(()=>{"use strict";ob=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});function tE(e,t={}){if(mU(e))return MY(e,t);if(uU(e))return FY(e,t);if(aU(e))return qY(e,t);if(bU(e))return HY(e,t);if(kU(e))return $Y(e);if(AU(e))return{type:"receive",stateMutability:"payable"};throw new eb({signature:e})}function MY(e,t={}){let n=hU(e);if(!n)throw new Go({signature:e,type:"function"});let r=rr(n.parameters),o=[],s=r.length;for(let a=0;a<s;a++)o.push(lo(r[a],{modifiers:$y,structs:t,type:"function"}));let i=[];if(n.returns){let a=rr(n.returns),l=a.length;for(let c=0;c<l;c++)i.push(lo(a[c],{modifiers:$y,structs:t,type:"function"}))}return{name:n.name,type:"function",stateMutability:n.stateMutability??"nonpayable",inputs:o,outputs:i}}function FY(e,t={}){let n=dU(e);if(!n)throw new Go({signature:e,type:"event"});let r=rr(n.parameters),o=[],s=r.length;for(let i=0;i<s;i++)o.push(lo(r[i],{modifiers:TU,structs:t,type:"event"}));return{name:n.name,type:"event",inputs:o}}function qY(e,t={}){let n=lU(e);if(!n)throw new Go({signature:e,type:"error"});let r=rr(n.parameters),o=[],s=r.length;for(let i=0;i<s;i++)o.push(lo(r[i],{structs:t,type:"error"}));return{name:n.name,type:"error",inputs:o}}function HY(e,t={}){let n=wU(e);if(!n)throw new Go({signature:e,type:"constructor"});let r=rr(n.parameters),o=[],s=r.length;for(let i=0;i<s;i++)o.push(lo(r[i],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:n.stateMutability??"nonpayable",inputs:o}}function $Y(e){let t=xU(e);if(!t)throw new Go({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}function lo(e,t){let n=EU(e,t?.type,t?.structs);if(ob.has(n))return ob.get(n);let r=qy.test(e),o=br(r?jY:VY,e);if(!o)throw new Ky({param:e});if(o.name&&GY(o.name))throw new Yy({param:e,name:o.name});let s=o.name?{name:o.name}:{},i=o.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},l,c={};if(r){l="tuple";let d=rr(o.type),p=[],m=d.length;for(let g=0;g<m;g++)p.push(lo(d[g],{structs:a}));c={components:p}}else if(o.type in a)l="tuple",c={components:a[o.type]};else if(zY.test(o.type))l=`${o.type}256`;else if(o.type==="address payable")l="address";else if(l=o.type,t?.type!=="struct"&&!nE(l))throw new zy({type:l});if(o.modifier){if(!t?.modifiers?.has?.(o.modifier))throw new Qy({param:e,type:t?.type,modifier:o.modifier});if($y.has(o.modifier)&&!KY(l,!!o.array))throw new Xy({param:e,type:t?.type,modifier:o.modifier})}let u={type:`${l}${o.array??""}`,...s,...i,...c};return ob.set(n,u),u}function rr(e,t=[],n="",r=0){let o=e.trim().length;for(let s=0;s<o;s++){let i=e[s],a=e.slice(s+1);switch(i){case",":return r===0?rr(a,[...t,n.trim()]):rr(a,t,`${n}${i}`,r);case"(":return rr(a,t,`${n}${i}`,r+1);case")":return rr(a,t,`${n}${i}`,r-1);default:return rr(a,t,`${n}${i}`,r)}}if(n==="")return t;if(r!==0)throw new rb({current:n,depth:r});return t.push(n.trim()),t}function nE(e){return e==="address"||e==="bool"||e==="function"||e==="string"||QP.test(e)||XP.test(e)}function GY(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||QP.test(e)||XP.test(e)||WY.test(e)}function KY(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}var VY,jY,zY,WY,Ym=L(()=>{"use strict";Gm();Wy();Zy();eE();PU();RU();Km();VY=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,jY=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,zY=/^u?int$/;WY=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/});function sb(e){let t={},n=e.length;for(let i=0;i<n;i++){let a=e[i];if(!Bu(a))continue;let l=gU(a);if(!l)throw new Go({signature:a,type:"struct"});let c=l.properties.split(";"),u=[],d=c.length;for(let p=0;p<d;p++){let g=c[p].trim();if(!g)continue;let f=lo(g,{type:"struct"});u.push(f)}if(!u.length)throw new tb({signature:a});t[l.name]=u}let r={},o=Object.entries(t),s=o.length;for(let i=0;i<s;i++){let[a,l]=o[i];r[a]=IU(l,t)}return r}function IU(e=[],t={},n=new Set){let r=[],o=e.length;for(let s=0;s<o;s++){let i=e[s];if(qy.test(i.type))r.push(i);else{let l=br(YY,i.type);if(!l?.type)throw new Jy({abiParameter:i});let{array:c,type:u}=l;if(u in t){if(n.has(u))throw new nb({type:u});r.push({...i,type:`tuple${c??""}`,components:IU(t[u],t,new Set([...n,u]))})}else if(nE(u))r.push(i);else throw new jy({type:u})}}return r}var YY,rE=L(()=>{"use strict";Gm();Wy();Zy();eE();SU();Km();Ym();YY=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/});function ib(e){let t;if(typeof e=="string")t=tE(e);else{let n=sb(e),r=e.length;for(let o=0;o<r;o++){let s=e[o];if(!Bu(s)){t=tE(s,n);break}}}if(!t)throw new Vy({signature:e});return t}var _U=L(()=>{"use strict";Wy();Km();rE();Ym()});function ab(e){let t=[];if(typeof e=="string"){let n=rr(e),r=n.length;for(let o=0;o<r;o++)t.push(lo(n[o],{modifiers:ZP}))}else{let n=sb(e),r=e.length;for(let o=0;o<r;o++){let s=e[o];if(Bu(s))continue;let i=rr(s),a=i.length;for(let l=0;l<a;l++)t.push(lo(i[l],{modifiers:ZP,structs:n}))}}if(t.length===0)throw new Gy({params:e});return t}var CU=L(()=>{"use strict";Zy();Km();rE();Ym();Ym()});var lb=L(()=>{"use strict";sU();JP();_U();CU()});var NU=L(()=>{"use strict"});var OU,LU=L(()=>{"use strict";OU="0.1.1"});function DU(){return OU}var UU=L(()=>{"use strict";LU()});function BU(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?BU(e.cause,t):t?null:e}var le,An=L(()=>{"use strict";UU();le=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,n={}){let r=(()=>{if(n.cause instanceof e){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&"details"in n.cause&&typeof n.cause.details=="string"?n.cause.details:n.cause?.message?n.cause.message:n.details})(),o=n.cause instanceof e&&n.cause.docsPath||n.docsPath,s=n.docsOrigin??e.prototype.docsOrigin,i=`${s}${o??""}`,a=!!(n.version??e.prototype.showVersion),l=n.version??e.prototype.version,c=[t||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||o||a?["",r?`Details: ${r}`:void 0,o?`See: ${i}`:void 0,a?`Version: ${l}`:void 0]:[]].filter(u=>typeof u=="string").join(`
|
|
3
3
|
`);super(c,n.cause?{cause:n.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=n.cause,this.details=r,this.docs=i,this.docsOrigin=s,this.docsPath=o,this.shortMessage=t,this.showVersion=a,this.version=l}walk(t){return BU(this,t)}};Object.defineProperty(le,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${DU()}`}});le.setStaticOptions(le.defaultStaticOptions)});function Mu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function cE(e){if(!Mu(e))throw new Error("Uint8Array expected")}function Fu(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function Qm(e){let t=e.toString(16);return t.length&1?"0"+t:t}function qU(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?lE:BigInt("0x"+e)}function qu(e){if(cE(e),HU)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=XY[e[n]];return t}function MU(e){if(e>=Fs._0&&e<=Fs._9)return e-Fs._0;if(e>=Fs.A&&e<=Fs.F)return e-(Fs.A-10);if(e>=Fs.a&&e<=Fs.f)return e-(Fs.a-10)}function Xm(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(HU)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){let i=MU(e.charCodeAt(s)),a=MU(e.charCodeAt(s+1));if(i===void 0||a===void 0){let l=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+s)}r[o]=i*16+a}return r}function qs(e){return qU(qu(e))}function uE(e){return cE(e),qU(qu(Uint8Array.from(e).reverse()))}function nl(e,t){return Xm(e.toString(16).padStart(t*2,"0"))}function dE(e,t){return nl(e,t).reverse()}function or(e,t,n){let r;if(typeof t=="string")try{r=Xm(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Mu(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=r.length;if(typeof n=="number"&&o!==n)throw new Error(e+" of length "+n+" expected, got "+o);return r}function Jm(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];cE(o),t+=o.length}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let s=e[r];n.set(s,o),o+=s.length}return n}function cb(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function ub(e,t,n){return sE(e)&&sE(t)&&sE(n)&&t<=e&&e<n}function rl(e,t,n,r){if(!ub(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function $U(e){let t;for(t=0;e>lE;e>>=aE,t+=1);return t}function VU(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=iE(e),o=iE(e),s=0,i=()=>{r.fill(1),o.fill(0),s=0},a=(...d)=>n(o,r,...d),l=(d=iE(0))=>{o=a(FU([0]),d),r=a(),d.length!==0&&(o=a(FU([1]),d),r=a())},c=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,p=[];for(;d<t;){r=a();let m=r.slice();p.push(m),d+=r.length}return Jm(...p)};return(d,p)=>{i(),l(d);let m;for(;!(m=p(c()));)l();return i(),m}}function sl(e,t,n={}){let r=(o,s,i)=>{let a=JY[s];if(typeof a!="function")throw new Error("invalid validator function");let l=e[o];if(!(i&&l===void 0)&&!a(l,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+l)};for(let[o,s]of Object.entries(t))r(o,s,!1);for(let[o,s]of Object.entries(n))r(o,s,!0);return e}function pE(e){let t=new WeakMap;return(n,...r)=>{let o=t.get(n);if(o!==void 0)return o;let s=e(n,...r);return t.set(n,s),s}}var lE,aE,HU,XY,Fs,sE,ol,iE,FU,JY,Hu=L(()=>{"use strict";lE=BigInt(0),aE=BigInt(1);HU=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",XY=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Fs={_0:48,_9:57,A:65,F:70,a:97,f:102};sE=e=>typeof e=="bigint"&&lE<=e;ol=e=>(aE<<BigInt(e))-aE,iE=e=>new Uint8Array(e),FU=e=>Uint8Array.from(e);JY={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"||Mu(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 $s(e,t){if(wr(e)>t)throw new Zm({givenSize:wr(e),maxSize:t})}function jU(e,t){if(typeof t=="number"&&t>0&&t>wr(e)-1)throw new $u({offset:t,position:"start",size:wr(e)})}function zU(e,t,n){if(typeof t=="number"&&typeof n=="number"&&wr(e)!==n-t)throw new $u({offset:n,position:"end",size:wr(e)})}function mE(e){if(e>=Hs.zero&&e<=Hs.nine)return e-Hs.zero;if(e>=Hs.A&&e<=Hs.F)return e-(Hs.A-10);if(e>=Hs.a&&e<=Hs.f)return e-(Hs.a-10)}function hE(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new eh({size:e.length,targetSize:r,type:"Bytes"});let o=new Uint8Array(r);for(let s=0;s<r;s++){let i=n==="right";o[i?s:r-s-1]=e[i?s:e.length-s-1]}return o}function fE(e,t={}){let{dir:n="left"}=t,r=e,o=0;for(let s=0;s<r.length-1&&r[n==="left"?s:r.length-s-1].toString()==="0";s++)o++;return r=n==="left"?r.slice(o):r.slice(0,r.length-o),r}var Hs,gE=L(()=>{"use strict";Xt();Hs={zero:48,nine:57,A:65,F:70,a:97,f:102}});function il(e,t){if(nt(e)>t)throw new th({givenSize:nt(e),maxSize:t})}function GU(e,t){if(typeof t=="number"&&t>0&&t>nt(e)-1)throw new Vu({offset:t,position:"start",size:nt(e)})}function KU(e,t,n){if(typeof t=="number"&&typeof n=="number"&&nt(e)!==n-t)throw new Vu({offset:n,position:"end",size:nt(e)})}function yE(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;let o=e.replace("0x","");if(o.length>r*2)throw new nh({size:Math.ceil(o.length/2),targetSize:r,type:"Hex"});return`0x${o[n==="right"?"padEnd":"padStart"](r*2,"0")}`}function bE(e,t={}){let{dir:n="left"}=t,r=e.replace("0x",""),o=0;for(let s=0;s<r.length-1&&r[n==="left"?s:r.length-s-1].toString()==="0";s++)o++;return r=n==="left"?r.slice(o):r.slice(0,r.length-o),r==="0"?"0x":n==="right"&&r.length%2===1?`0x${r}0`:`0x${r}`}var wE=L(()=>{"use strict";Tn()});function co(e,t,n){return JSON.stringify(e,(r,o)=>typeof t=="function"?t(r,o):typeof o=="bigint"?o.toString()+ZY:o,n)}var ZY,al=L(()=>{"use strict";ZY="#__bigint"});var It={};fr(It,{IntegerOutOfRangeError:()=>zu,InvalidHexBooleanError:()=>db,InvalidHexTypeError:()=>rh,InvalidHexValueError:()=>oh,InvalidLengthError:()=>pb,SizeExceedsPaddingSizeError:()=>nh,SizeOverflowError:()=>th,SliceOffsetOutOfBoundsError:()=>Vu,assert:()=>QU,concat:()=>Jt,from:()=>uo,fromBoolean:()=>sh,fromBytes:()=>Ke,fromNumber:()=>pt,fromString:()=>Vs,isEqual:()=>n9,padLeft:()=>Ko,padRight:()=>po,random:()=>r9,size:()=>nt,slice:()=>$t,toBigInt:()=>mb,toBoolean:()=>s9,toBytes:()=>i9,toNumber:()=>vE,toString:()=>a9,trimLeft:()=>ih,trimRight:()=>o9,validate:()=>ll});function QU(e,t={}){let{strict:n=!1}=t;if(!e)throw new rh(e);if(typeof e!="string")throw new rh(e);if(n&&!/^0x[0-9a-fA-F]*$/.test(e))throw new oh(e);if(!e.startsWith("0x"))throw new oh(e)}function Jt(...e){return`0x${e.reduce((t,n)=>t+n.replace("0x",""),"")}`}function uo(e){return e instanceof Uint8Array?Ke(e):Array.isArray(e)?Ke(new Uint8Array(e)):e}function sh(e,t={}){let n=`0x${Number(e)}`;return typeof t.size=="number"?(il(n,t.size),Ko(n,t.size)):n}function Ke(e,t={}){let n="";for(let o=0;o<e.length;o++)n+=t9[e[o]];let r=`0x${n}`;return typeof t.size=="number"?(il(r,t.size),po(r,t.size)):r}function pt(e,t={}){let{signed:n,size:r}=t,o=BigInt(e),s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));let i=typeof s=="bigint"&&n?-s-1n:0;if(s&&o>s||o<i){let c=typeof e=="bigint"?"n":"";throw new zu({max:s?`${s}${c}`:void 0,min:`${i}${c}`,signed:n,size:r,value:`${e}${c}`})}let l=`0x${(n&&o<0?BigInt.asUintN(r*8,BigInt(o)):o).toString(16)}`;return r?Ko(l,r):l}function Vs(e,t={}){return Ke(e9.encode(e),t)}function n9(e,t){return cb(yt(e),yt(t))}function Ko(e,t){return yE(e,{dir:"left",size:t})}function po(e,t){return yE(e,{dir:"right",size:t})}function r9(e){return Ke(hb(e))}function $t(e,t,n,r={}){let{strict:o}=r;GU(e,t);let s=`0x${e.replace("0x","").slice((t??0)*2,(n??e.length)*2)}`;return o&&KU(s,t,n),s}function nt(e){return Math.ceil((e.length-2)/2)}function ih(e){return bE(e,{dir:"left"})}function o9(e){return bE(e,{dir:"right"})}function mb(e,t={}){let{signed:n}=t;t.size&&il(e,t.size);let r=BigInt(e);if(!n)return r;let o=(e.length-2)/2,s=(1n<<BigInt(o)*8n)-1n,i=s>>1n;return r<=i?r:r-s-1n}function s9(e,t={}){t.size&&il(e,t.size);let n=ih(e);if(n==="0x")return!1;if(n==="0x1")return!0;throw new db(e)}function i9(e,t={}){return yt(e,t)}function vE(e,t={}){let{signed:n,size:r}=t;return Number(!n&&!r?e:mb(e,t))}function a9(e,t={}){let{size:n}=t,r=yt(e);return n&&($s(r,n),r=fb(r)),new TextDecoder().decode(r)}function ll(e,t={}){let{strict:n=!1}=t;try{return QU(e,{strict:n}),!0}catch{return!1}}var e9,t9,zu,db,rh,oh,pb,th,Vu,nh,Tn=L(()=>{"use strict";Hu();Xt();An();gE();wE();al();e9=new TextEncoder,t9=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));zu=class extends le{constructor({max:t,min:n,signed:r,size:o,value:s}){super(`Number \`${s}\` is not in safe${o?` ${o*8}-bit`:""}${r?" signed":" unsigned"} integer range ${t?`(\`${n}\` to \`${t}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},db=class extends le{constructor(t){super(`Hex value \`"${t}"\` is not a valid boolean.`,{metaMessages:['The hex value must be `"0x0"` (false) or `"0x1"` (true).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexBooleanError"})}},rh=class extends le{constructor(t){super(`Value \`${typeof t=="object"?co(t):t}\` of type \`${typeof t}\` 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"})}},oh=class extends le{constructor(t){super(`Value \`${t}\` 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"})}},pb=class extends le{constructor(t){super(`Hex value \`"${t}"\` is an odd length (${t.length-2} nibbles).`,{metaMessages:["It must be an even length."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidLengthError"})}},th=class extends le{constructor({givenSize:t,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},Vu=class extends le{constructor({offset:t,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}},nh=class extends le{constructor({size:t,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});var we={};fr(we,{InvalidBytesBooleanError:()=>gb,InvalidBytesTypeError:()=>cl,SizeExceedsPaddingSizeError:()=>eh,SizeOverflowError:()=>Zm,SliceOffsetOutOfBoundsError:()=>$u,assert:()=>XU,concat:()=>Wu,from:()=>Fn,fromArray:()=>JU,fromBoolean:()=>u9,fromHex:()=>yt,fromNumber:()=>Gu,fromString:()=>qn,isEqual:()=>d9,padLeft:()=>yb,padRight:()=>ZU,random:()=>hb,size:()=>wr,slice:()=>kE,toBigInt:()=>xE,toBoolean:()=>AE,toHex:()=>p9,toNumber:()=>mo,toString:()=>ah,trimLeft:()=>bb,trimRight:()=>fb,validate:()=>Ku});function XU(e){if(!(e instanceof Uint8Array)){if(!e)throw new cl(e);if(typeof e!="object")throw new cl(e);if(!("BYTES_PER_ELEMENT"in e))throw new cl(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new cl(e)}}function Wu(...e){let t=0;for(let r of e)t+=r.length;let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let s=e[r];n.set(s,o),o+=s.length}return n}function Fn(e){return e instanceof Uint8Array?e:typeof e=="string"?yt(e):JU(e)}function JU(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function u9(e,t={}){let{size:n}=t,r=new Uint8Array(1);return r[0]=Number(e),typeof n=="number"?($s(r,n),yb(r,n)):r}function yt(e,t={}){let{size:n}=t,r=e;n&&(il(e,n),r=po(e,n));let o=r.slice(2);o.length%2&&(o=`0${o}`);let s=o.length/2,i=new Uint8Array(s);for(let a=0,l=0;a<s;a++){let c=mE(o.charCodeAt(l++)),u=mE(o.charCodeAt(l++));if(c===void 0||u===void 0)throw new le(`Invalid byte sequence ("${o[l-2]}${o[l-1]}" in "${o}").`);i[a]=c<<4|u}return i}function Gu(e,t){let n=pt(e,t);return yt(n)}function qn(e,t={}){let{size:n}=t,r=c9.encode(e);return typeof n=="number"?($s(r,n),ZU(r,n)):r}function d9(e,t){return cb(e,t)}function yb(e,t){return hE(e,{dir:"left",size:t})}function ZU(e,t){return hE(e,{dir:"right",size:t})}function hb(e){return crypto.getRandomValues(new Uint8Array(e))}function wr(e){return e.length}function kE(e,t,n,r={}){let{strict:o}=r;jU(e,t);let s=e.slice(t,n);return o&&zU(s,t,n),s}function xE(e,t={}){let{size:n}=t;typeof n<"u"&&$s(e,n);let r=Ke(e,t);return mb(r,t)}function AE(e,t={}){let{size:n}=t,r=e;if(typeof n<"u"&&($s(r,n),r=bb(r)),r.length>1||r[0]>1)throw new gb(r);return!!r[0]}function p9(e,t={}){return Ke(e,t)}function mo(e,t={}){let{size:n}=t;typeof n<"u"&&$s(e,n);let r=Ke(e,t);return vE(r,t)}function ah(e,t={}){let{size:n}=t,r=e;return typeof n<"u"&&($s(r,n),r=fb(r)),l9.decode(r)}function bb(e){return fE(e,{dir:"left"})}function fb(e){return fE(e,{dir:"right"})}function Ku(e){try{return XU(e),!0}catch{return!1}}var l9,c9,gb,cl,Zm,$u,eh,Xt=L(()=>{"use strict";Hu();An();Tn();gE();wE();al();l9=new TextDecoder,c9=new TextEncoder;gb=class extends le{constructor(t){super(`Bytes value \`${t}\` 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"})}},cl=class extends le{constructor(t){super(`Value \`${typeof t=="object"?co(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}},Zm=class extends le{constructor({givenSize:t,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},$u=class extends le{constructor({offset:t,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"})}},eh=class extends le{constructor({size:t,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});var Je={};fr(Je,{hmac256:()=>SE,keccak256:()=>sn,ripemd160:()=>m9,sha256:()=>h9,validate:()=>f9});function sn(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,nB.keccak_256)(Fn(e));return n==="Bytes"?r:Ke(r)}function SE(e,t,n={}){let{as:r=typeof t=="string"?"Hex":"Bytes"}=n,o=(0,eB.hmac)(TE.sha256,Fn(e),Fn(t));return r==="Bytes"?o:Ke(o)}function m9(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,tB.ripemd160)(Fn(e));return n==="Bytes"?r:Ke(r)}function h9(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,TE.sha256)(Fn(e));return n==="Bytes"?r:Ke(r)}function f9(e){return e.length===66&&ll(e,{strict:!0})}var eB,tB,nB,TE,ul=L(()=>{"use strict";eB=require("@noble/hashes/hmac"),tB=require("@noble/hashes/ripemd160"),nB=require("@noble/hashes/sha3"),TE=require("@noble/hashes/sha256");Xt();Tn()});var wb,rB=L(()=>{"use strict";wb=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let n=super.get(t);return super.has(t)&&n!==void 0&&(this.delete(t),super.set(t,n)),n}set(t,n){if(super.set(t,n),this.maxSize&&this.size>this.maxSize){let r=this.keys().next().value;r&&this.delete(r)}return this}}});var g9,vb,PE=L(()=>{"use strict";rB();g9={checksum:new wb(8192)},vb=g9.checksum});function sB(e,t={}){let{compressed:n}=t,{prefix:r,x:o,y:s}=e;if(n===!1||typeof o=="bigint"&&typeof s=="bigint"){if(r!==4)throw new kb({prefix:r,cause:new IE});return}if(n===!0||typeof o=="bigint"&&typeof s>"u"){if(r!==3&&r!==2)throw new kb({prefix:r,cause:new RE});return}throw new EE({publicKey:e})}function CE(e){let t=(()=>{if(ll(e))return iB(e);if(Ku(e))return y9(e);let{prefix:n,x:r,y:o}=e;return typeof r=="bigint"&&typeof o=="bigint"?{prefix:n??4,x:r,y:o}:{prefix:n,x:r}})();return sB(t),t}function y9(e){return iB(Ke(e))}function iB(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new _E({publicKey:e});if(e.length===130){let r=BigInt($t(e,0,32)),o=BigInt($t(e,32,64));return{prefix:4,x:r,y:o}}if(e.length===132){let r=Number($t(e,0,1)),o=BigInt($t(e,1,33)),s=BigInt($t(e,33,65));return{prefix:r,x:o,y:s}}let t=Number($t(e,0,1)),n=BigInt($t(e,1,33));return{prefix:t,x:n}}function aB(e,t={}){return yt(lh(e,t))}function lh(e,t={}){sB(e);let{prefix:n,x:r,y:o}=e,{includePrefix:s=!0}=t;return Jt(s?pt(n,{size:1}):"0x",pt(r,{size:32}),typeof o=="bigint"?pt(o,{size:32}):"0x")}var EE,kb,RE,IE,_E,xb=L(()=>{"use strict";Xt();An();Tn();al();EE=class extends le{constructor({publicKey:t}){super(`Value \`${co(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},kb=class extends le{constructor({prefix:t,cause:n}){super(`Prefix "${t}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},RE=class extends le{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},IE=class extends le{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},_E=class extends le{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${nt(uo(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});var Qo={};fr(Qo,{InvalidAddressError:()=>dl,InvalidChecksumError:()=>Ab,InvalidInputError:()=>Yu,assert:()=>Yo,checksum:()=>ch,from:()=>pl,fromPublicKey:()=>OE,isEqual:()=>LE,validate:()=>ml});function Yo(e,t={}){let{strict:n=!0}=t;if(!b9.test(e))throw new dl({address:e,cause:new Yu});if(n){if(e.toLowerCase()===e)return;if(ch(e)!==e)throw new dl({address:e,cause:new Ab})}}function ch(e){if(vb.has(e))return vb.get(e);Yo(e,{strict:!1});let t=e.substring(2).toLowerCase(),n=sn(qn(t),{as:"Bytes"}),r=t.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&r[s]&&(r[s]=r[s].toUpperCase()),(n[s>>1]&15)>=8&&r[s+1]&&(r[s+1]=r[s+1].toUpperCase());let o=`0x${r.join("")}`;return vb.set(e,o),o}function pl(e,t={}){let{checksum:n=!1}=t;return Yo(e),n?ch(e):e}function OE(e,t={}){let n=sn(`0x${lh(e).slice(4)}`).substring(26);return pl(`0x${n}`,t)}function LE(e,t){return Yo(e,{strict:!1}),Yo(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}function ml(e,t={}){let{strict:n=!0}=t??{};try{return Yo(e,{strict:n}),!0}catch{return!1}}var b9,dl,Yu,Ab,Wi=L(()=>{"use strict";Xt();PE();An();ul();xb();b9=/^0x[a-fA-F0-9]{40}$/;dl=class extends le{constructor({address:t,cause:n}){super(`Address "${t}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},Yu=class extends le{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"})}},Ab=class extends le{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}});function Sb(e){let t=!0,n="",r=0,o="",s=!1;for(let i=0;i<e.length;i++){let a=e[i];if(["(",")",","].includes(a)&&(t=!0),a==="("&&r++,a===")"&&r--,!!t){if(r===0){if(a===" "&&["event","function","error",""].includes(o))o="";else if(o+=a,a===")"){s=!0;break}continue}if(a===" "){e[i-1]!==","&&n!==","&&n!==",("&&(n="",t=!1);continue}o+=a,n+=a}}if(!s)throw new le("Unable to normalize signature.");return o}function Tb(e,t){let n=typeof e,r=t.type;switch(r){case"address":return ml(e,{strict:!1});case"bool":return n==="boolean";case"function":return n==="string";case"string":return n==="string";default:return r==="tuple"&&"components"in t?Object.values(t.components).every((o,s)=>Tb(Object.values(e)[s],o)):/^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(r)?n==="number"||n==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(r)?n==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(r)?Array.isArray(e)&&e.every(o=>Tb(o,{...t,type:r.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function DE(e,t,n){for(let r in e){let o=e[r],s=t[r];if(o.type==="tuple"&&s.type==="tuple"&&"components"in o&&"components"in s)return DE(o.components,s.components,n[r]);let i=[o.type,s.type];if(i.includes("address")&&i.includes("bytes20")?!0:i.includes("address")&&i.includes("string")?ml(n[r],{strict:!1}):i.includes("address")&&i.includes("bytes")?ml(n[r],{strict:!1}):!1)return i}}var lB=L(()=>{"use strict";Wi();An()});function cB(e,t={}){let{prepare:n=!0}=t,r=Array.isArray(e)?ib(e):typeof e=="string"?ib(e):e;return{...r,...n?{hash:Qu(r)}:{}}}function uh(e,t,n){let{args:r=[],prepare:o=!0}=n??{},s=ll(t,{strict:!1}),i=e.filter(c=>s?c.type==="function"||c.type==="error"?BE(c)===$t(t,0,4):c.type==="event"?Qu(c)===t:!1:"name"in c&&c.name===t);if(i.length===0)throw new Xu({name:t});if(i.length===1)return{...i[0],...o?{hash:Qu(i[0])}:{}};let a;for(let c of i){if(!("inputs"in c))continue;if(!r||r.length===0){if(!c.inputs||c.inputs.length===0)return{...c,...o?{hash:Qu(c)}:{}};continue}if(!c.inputs||c.inputs.length===0||c.inputs.length!==r.length)continue;if(r.every((d,p)=>{let m="inputs"in c&&c.inputs[p];return m?Tb(d,m):!1})){if(a&&"inputs"in a&&a.inputs){let d=DE(c.inputs,a.inputs,r);if(d)throw new UE({abiItem:c,type:d[0]},{abiItem:a,type:d[1]})}a=c}}let l=(()=>{if(a)return a;let[c,...u]=i;return{...c,overloads:u}})();if(!l)throw new Xu({name:t});return{...l,...o?{hash:Qu(l)}:{}}}function BE(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,r]=e;return uh(n,r)}return e[0]})();return $t(Qu(t),0,4)}function v9(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,o]=e;return uh(r,o)}return e[0]})(),n=typeof t=="string"?t:tl(t);return Sb(n)}function Qu(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,r]=e;return uh(n,r)}return e[0]})();return typeof t!="string"&&"hash"in t&&t.hash?t.hash:sn(Vs(v9(t)))}var UE,Xu,Pb,ME=L(()=>{"use strict";lb();An();ul();Tn();lB();UE=class extends le{constructor(t,n){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${Sb(tl(t.abiItem))}\`, and`,`\`${n.type}\` in \`${Sb(tl(n.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"})}},Xu=class extends le{constructor({name:t,data:n,type:r="item"}){let o=t?` with name "${t}"`:n?` with data "${n}"`:"";super(`ABI ${r}${o} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}},Pb=class extends le{constructor({data:t}){super(`Selector size is invalid. Expected 4 bytes. Received ${nt(t)} bytes ("${t}").`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.InvalidSelectorSizeError"})}}});var dB,Eb,Ju,JPe,ZPe,eEe,tEe,nEe,rEe,oEe,sEe,iEe,aEe,lEe,cEe,uEe,dEe,pEe,mEe,hEe,fEe,gEe,yEe,bEe,wEe,vEe,kEe,xEe,AEe,TEe,SEe,PEe,EEe,REe,IEe,_Ee,CEe,NEe,OEe,LEe,DEe,UEe,BEe,MEe,FEe,qEe,HEe,$Ee,VEe,jEe,zEe,WEe,GEe,KEe,YEe,QEe,XEe,JEe,ZEe,eRe,tRe,nRe,rRe,oRe,sRe,iRe,aRe,lRe,cRe,uRe,dRe,pRe,mRe,hRe,fRe,gRe,yRe,bRe,wRe,vRe,kRe,xRe,ARe,TRe,SRe,PRe,ERe,RRe,IRe,_Re,CRe,NRe,ORe,LRe,DRe,URe,BRe,MRe,FE,Zu=L(()=>{"use strict";dB=/^(.*)\[([0-9]*)\]$/,Eb=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Ju=/^(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)?$/,JPe=2n**(8n-1n)-1n,ZPe=2n**(16n-1n)-1n,eEe=2n**(24n-1n)-1n,tEe=2n**(32n-1n)-1n,nEe=2n**(40n-1n)-1n,rEe=2n**(48n-1n)-1n,oEe=2n**(56n-1n)-1n,sEe=2n**(64n-1n)-1n,iEe=2n**(72n-1n)-1n,aEe=2n**(80n-1n)-1n,lEe=2n**(88n-1n)-1n,cEe=2n**(96n-1n)-1n,uEe=2n**(104n-1n)-1n,dEe=2n**(112n-1n)-1n,pEe=2n**(120n-1n)-1n,mEe=2n**(128n-1n)-1n,hEe=2n**(136n-1n)-1n,fEe=2n**(144n-1n)-1n,gEe=2n**(152n-1n)-1n,yEe=2n**(160n-1n)-1n,bEe=2n**(168n-1n)-1n,wEe=2n**(176n-1n)-1n,vEe=2n**(184n-1n)-1n,kEe=2n**(192n-1n)-1n,xEe=2n**(200n-1n)-1n,AEe=2n**(208n-1n)-1n,TEe=2n**(216n-1n)-1n,SEe=2n**(224n-1n)-1n,PEe=2n**(232n-1n)-1n,EEe=2n**(240n-1n)-1n,REe=2n**(248n-1n)-1n,IEe=2n**(256n-1n)-1n,_Ee=-(2n**(8n-1n)),CEe=-(2n**(16n-1n)),NEe=-(2n**(24n-1n)),OEe=-(2n**(32n-1n)),LEe=-(2n**(40n-1n)),DEe=-(2n**(48n-1n)),UEe=-(2n**(56n-1n)),BEe=-(2n**(64n-1n)),MEe=-(2n**(72n-1n)),FEe=-(2n**(80n-1n)),qEe=-(2n**(88n-1n)),HEe=-(2n**(96n-1n)),$Ee=-(2n**(104n-1n)),VEe=-(2n**(112n-1n)),jEe=-(2n**(120n-1n)),zEe=-(2n**(128n-1n)),WEe=-(2n**(136n-1n)),GEe=-(2n**(144n-1n)),KEe=-(2n**(152n-1n)),YEe=-(2n**(160n-1n)),QEe=-(2n**(168n-1n)),XEe=-(2n**(176n-1n)),JEe=-(2n**(184n-1n)),ZEe=-(2n**(192n-1n)),eRe=-(2n**(200n-1n)),tRe=-(2n**(208n-1n)),nRe=-(2n**(216n-1n)),rRe=-(2n**(224n-1n)),oRe=-(2n**(232n-1n)),sRe=-(2n**(240n-1n)),iRe=-(2n**(248n-1n)),aRe=-(2n**(256n-1n)),lRe=2n**8n-1n,cRe=2n**16n-1n,uRe=2n**24n-1n,dRe=2n**32n-1n,pRe=2n**40n-1n,mRe=2n**48n-1n,hRe=2n**56n-1n,fRe=2n**64n-1n,gRe=2n**72n-1n,yRe=2n**80n-1n,bRe=2n**88n-1n,wRe=2n**96n-1n,vRe=2n**104n-1n,kRe=2n**112n-1n,xRe=2n**120n-1n,ARe=2n**128n-1n,TRe=2n**136n-1n,SRe=2n**144n-1n,PRe=2n**152n-1n,ERe=2n**160n-1n,RRe=2n**168n-1n,IRe=2n**176n-1n,_Re=2n**184n-1n,CRe=2n**192n-1n,NRe=2n**200n-1n,ORe=2n**208n-1n,LRe=2n**216n-1n,DRe=2n**224n-1n,URe=2n**232n-1n,BRe=2n**240n-1n,MRe=2n**248n-1n,FE=2n**256n-1n});function hl(e,t,n){let{checksumAddress:r,staticPosition:o}=n,s=$E(t.type);if(s){let[i,a]=s;return x9(e,{...t,type:a},{checksumAddress:r,length:i,staticPosition:o})}if(t.type==="tuple")return P9(e,t,{checksumAddress:r,staticPosition:o});if(t.type==="address")return k9(e,{checksum:r});if(t.type==="bool")return A9(e);if(t.type.startsWith("bytes"))return T9(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return S9(e,t);if(t.type==="string")return E9(e,{staticPosition:o});throw new fl(t.type)}function k9(e,t={}){let{checksum:n=!1}=t,r=e.readBytes(32);return[(s=>n?ch(s):s)(Ke(kE(r,-20))),32]}function x9(e,t,n){let{checksumAddress:r,length:o,staticPosition:s}=n;if(o===null){let l=mo(e.readBytes(qE)),c=s+l,u=c+pB;e.setPosition(c);let d=mo(e.readBytes(pB)),p=ed(t),m=0,g=[];for(let f=0;f<d;++f){e.setPosition(u+(p?f*32:m));let[y,w]=hl(e,t,{checksumAddress:r,staticPosition:u});m+=w,g.push(y),w===0&&(e.assertReadLimit(),e._touch())}return e.setPosition(s+32),[g,32]}if(ed(t)){let l=mo(e.readBytes(qE)),c=s+l,u=[];for(let d=0;d<o;++d){e.setPosition(c+d*32);let[p]=hl(e,t,{checksumAddress:r,staticPosition:c});u.push(p)}return e.setPosition(s+32),[u,32]}let i=0,a=[];for(let l=0;l<o;++l){let[c,u]=hl(e,t,{checksumAddress:r,staticPosition:s+i});i+=u,a.push(c),u===0&&(e.assertReadLimit(),e._touch())}return[a,i]}function A9(e){return[AE(e.readBytes(32),{size:32}),32]}function T9(e,t,{staticPosition:n}){let[r,o]=t.type.split("bytes");if(!o){let i=mo(e.readBytes(32));e.setPosition(n+i);let a=mo(e.readBytes(32));if(a===0)return e.setPosition(n+32),["0x",32];let l=e.readBytes(a);return e.setPosition(n+32),[Ke(l),32]}return[Ke(e.readBytes(Number.parseInt(o,10),32)),32]}function S9(e,t){let n=t.type.startsWith("int"),r=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[r>48?xE(o,{signed:n}):mo(o,{signed:n}),32]}function P9(e,t,n){let{checksumAddress:r,staticPosition:o}=n,s=t.components.length===0||t.components.some(({name:l})=>!l),i=s?[]:{},a=0;if(ed(t)){let l=mo(e.readBytes(qE)),c=o+l;for(let u=0;u<t.components.length;++u){let d=t.components[u];e.setPosition(c+a);let[p,m]=hl(e,d,{checksumAddress:r,staticPosition:c});a+=m,i[s?u:d?.name]=p}return e.setPosition(o+32),[i,32]}for(let l=0;l<t.components.length;++l){let c=t.components[l],[u,d]=hl(e,c,{checksumAddress:r,staticPosition:o});i[s?l:c?.name]=u,a+=d}return[i,a]}function E9(e,{staticPosition:t}){let n=mo(e.readBytes(32)),r=t+n;e.setPosition(r);let o=mo(e.readBytes(32));if(o===0)return e.setPosition(t+32),["",32];let s=e.readBytes(o,32),i=ah(bb(s));return e.setPosition(t+32),[i,32]}function mB({checksumAddress:e,parameters:t,values:n}){let r=[];for(let o=0;o<t.length;o++)r.push(HE({checksumAddress:e,parameter:t[o],value:n[o]}));return r}function HE({checksumAddress:e=!1,parameter:t,value:n}){let r=t,o=$E(r.type);if(o){let[s,i]=o;return I9(n,{checksumAddress:e,length:s,parameter:{...r,type:i}})}if(r.type==="tuple")return L9(n,{checksumAddress:e,parameter:r});if(r.type==="address")return R9(n,{checksum:e});if(r.type==="bool")return C9(n);if(r.type.startsWith("uint")||r.type.startsWith("int")){let s=r.type.startsWith("int"),[,,i="256"]=Ju.exec(r.type)??[];return N9(n,{signed:s,size:Number(i)})}if(r.type.startsWith("bytes"))return _9(n,{type:r.type});if(r.type==="string")return O9(n);throw new fl(r.type)}function Ib(e){let t=0;for(let s=0;s<e.length;s++){let{dynamic:i,encoded:a}=e[s];i?t+=32:t+=nt(a)}let n=[],r=[],o=0;for(let s=0;s<e.length;s++){let{dynamic:i,encoded:a}=e[s];i?(n.push(pt(t+o,{size:32})),r.push(a),o+=nt(a)):n.push(a)}return Jt(...n,...r)}function R9(e,t){let{checksum:n=!1}=t;return Yo(e,{strict:n}),{dynamic:!1,encoded:Ko(e.toLowerCase())}}function I9(e,t){let{checksumAddress:n,length:r,parameter:o}=t,s=r===null;if(!Array.isArray(e))throw new ph(e);if(!s&&e.length!==r)throw new dh({expectedLength:r,givenLength:e.length,type:`${o.type}[${r}]`});let i=e.length===0&&ed(o),a=[];for(let l=0;l<e.length;l++){let c=HE({checksumAddress:n,parameter:o,value:e[l]});c.dynamic&&(i=!0),a.push(c)}if(s||i){let l=Ib(a);if(s){let c=pt(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Jt(c,l):c}}if(i)return{dynamic:!0,encoded:l}}return{dynamic:!1,encoded:Jt(...a.map(({encoded:l})=>l))}}function _9(e,{type:t}){let[,n]=t.split("bytes"),r=nt(e);if(!n){let o=e;return r%32!==0&&(o=po(o,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:Jt(Ko(pt(r,{size:32})),o)}}if(r!==Number.parseInt(n,10))throw new td({expectedSize:Number.parseInt(n,10),value:e});return{dynamic:!1,encoded:po(e)}}function C9(e){if(typeof e!="boolean")throw new le(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Ko(sh(e))}}function N9(e,{signed:t,size:n}){if(typeof n=="number"){let r=2n**(BigInt(n)-(t?1n:0n))-1n,o=t?-r-1n:0n;if(e>r||e<o)throw new zu({max:r.toString(),min:o.toString(),signed:t,size:n/8,value:e.toString()})}return{dynamic:!1,encoded:pt(e,{size:32,signed:t})}}function O9(e){let t=Vs(e),n=Math.ceil(nt(t)/32),r=[];for(let o=0;o<n;o++)r.push(po($t(t,o*32,(o+1)*32)));return{dynamic:!0,encoded:Jt(po(pt(nt(t),{size:32})),...r)}}function L9(e,t){let{checksumAddress:n,parameter:r}=t,o=!1,s=[];for(let i=0;i<r.components.length;i++){let a=r.components[i],l=Array.isArray(e)?i:a.name,c=HE({checksumAddress:n,parameter:a,value:e[l]});s.push(c),c.dynamic&&(o=!0)}return{dynamic:o,encoded:o?Ib(s):Jt(...s.map(({encoded:i})=>i))}}function $E(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function ed(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(ed);let n=$E(e.type);return!!(n&&ed({...e,type:n[1]}))}var pB,qE,hB=L(()=>{"use strict";mh();Wi();Xt();An();Tn();Zu();pB=32,qE=32});function Cb(e,{recursiveReadLimit:t=8192}={}){let n=Object.create(U9);return n.bytes=e,n.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}var U9,_b,VE,jE,zE=L(()=>{"use strict";An();U9={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 jE({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new VE({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new _b({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 _b({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 n=t??this.position;return this.assertPosition(n+e-1),this.bytes.subarray(n,n+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 n=this.inspectBytes(e);return this.position+=t??e,n},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();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};_b=class extends le{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}},VE=class extends le{constructor({length:t,position:n}){super(`Position \`${n}\` is out of bounds (\`0 < position < ${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}},jE=class extends le{constructor({count:t,limit:n}){super(`Recursive read limit of \`${n}\` exceeded (recursive read count: \`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}});var zt={};fr(zt,{ArrayLengthMismatchError:()=>dh,BytesSizeMismatchError:()=>td,DataSizeTooSmallError:()=>Ob,InvalidArrayError:()=>ph,InvalidTypeError:()=>fl,LengthMismatchError:()=>hh,ZeroDataError:()=>Lb,decode:()=>Db,encode:()=>gl,encodePacked:()=>Nb,format:()=>B9,from:()=>M9});function Db(e,t,n={}){let{as:r="Array",checksumAddress:o=!1}=n,s=typeof t=="string"?yt(t):t,i=Cb(s);if(wr(s)===0&&e.length>0)throw new Lb;if(wr(s)&&wr(s)<32)throw new Ob({data:typeof t=="string"?t:Ke(t),parameters:e,size:wr(s)});let a=0,l=r==="Array"?[]:{};for(let c=0;c<e.length;++c){let u=e[c];a<s.length&&i.setPosition(a);let[d,p]=hl(i,u,{checksumAddress:o,staticPosition:0});a+=p,r==="Array"?l.push(d):l[u.name??c]=d}return l}function gl(e,t,n){let{checksumAddress:r=!1}=n??{};if(e.length!==t.length)throw new hh({expectedLength:e.length,givenLength:t.length});let o=mB({checksumAddress:r,parameters:e,values:t}),s=Ib(o);return s.length===0?"0x":s}function Nb(e,t){if(e.length!==t.length)throw new hh({expectedLength:e.length,givenLength:t.length});let n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t[r];n.push(Nb.encode(o,s))}return Jt(...n)}function B9(e){return Wo(e)}function M9(e){return Array.isArray(e)&&typeof e[0]=="string"?ab(e):typeof e=="string"?ab(e):e}var Ob,Lb,dh,td,hh,ph,fl,mh=L(()=>{"use strict";lb();Wi();Xt();An();Tn();hB();zE();Zu();(function(e){function t(n,r,o=!1){if(n==="address"){let l=r;return Yo(l),Ko(l.toLowerCase(),o?32:0)}if(n==="string")return Vs(r);if(n==="bytes")return r;if(n==="bool")return Ko(sh(r),o?32:1);let s=n.match(Ju);if(s){let[l,c,u="256"]=s,d=Number.parseInt(u,10)/8;return pt(r,{size:o?32:d,signed:c==="int"})}let i=n.match(Eb);if(i){let[l,c]=i;if(Number.parseInt(c,10)!==(r.length-2)/2)throw new td({expectedSize:Number.parseInt(c,10),value:r});return po(r,o?32:0)}let a=n.match(dB);if(a&&Array.isArray(r)){let[l,c]=a,u=[];for(let d=0;d<r.length;d++)u.push(t(c,r[d],!0));return u.length===0?"0x":Jt(...u)}throw new fl(n)}e.encode=t})(Nb||(Nb={}));Ob=class extends le{constructor({data:t,parameters:n,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${Wo(n)})`,`Data: ${t} (${r} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}},Lb=class extends le{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}},dh=class extends le{constructor({expectedLength:t,givenLength:n,type:r}){super(`Array length mismatch for type \`${r}\`. Expected: \`${t}\`. Given: \`${n}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}},td=class extends le{constructor({expectedSize:t,value:n}){super(`Size of bytes "${n}" (bytes${nt(n)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}},hh=class extends le{constructor({expectedLength:t,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${n}`].join(`
|
|
4
4
|
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}},ph=class extends le{constructor(t){super(`Value \`${t}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}},fl=class extends le{constructor(t){super(`Type \`${t}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}});var gB=L(()=>{"use strict"});var yB=L(()=>{"use strict"});var bB=L(()=>{"use strict"});var _e={};fr(_e,{decodeData:()=>$9,decodeResult:()=>V9,encodeData:()=>j9,encodeResult:()=>z9,format:()=>W9,from:()=>G9,fromAbi:()=>yl,getSelector:()=>wB});function $9(...e){let[t,n]=(()=>{if(Array.isArray(e[0])){let[s,i,a]=e;return[yl(s,i),a]}return e})(),{overloads:r}=t;if(nt(n)<4)throw new Pb({data:n});if(t.inputs?.length===0)return;let o=r?yl([t,...r],n):t;if(!(nt(n)<=4))return Db(o.inputs,$t(n,4))}function V9(...e){let[t,n,r={}]=(()=>{if(Array.isArray(e[0])){let[s,i,a,l]=e;return[yl(s,i),a,l]}return e})(),o=Db(t.outputs,n,r);if(!(o&&Object.keys(o).length===0))return o&&Object.keys(o).length===1?Array.isArray(o)?o[0]:Object.values(o)[0]:o}function j9(...e){let[t,n=[]]=(()=>{if(Array.isArray(e[0])){let[c,u,d]=e;return[yl(c,u,{args:d}),d]}let[a,l]=e;return[a,l]})(),{overloads:r}=t,o=r?yl([t,...r],t.name,{args:n}):t,s=wB(o),i=n.length>0?gl(o.inputs,n):void 0;return i?Jt(s,i):s}function z9(...e){let[t,n,r={}]=(()=>{if(Array.isArray(e[0])){let[i,a,l,c]=e;return[yl(i,a),l,c]}return e})(),{as:o="Array"}=r,s=t.outputs.length===1?[n]:Array.isArray(n)?n:o==="Object"?Object.values(n):[n];return gl(t.outputs,s)}function W9(e){return tl(e)}function G9(e,t={}){return cB(e,t)}function yl(e,t,n){let r=uh(e,t,n);if(r.type!=="function")throw new Xu({name:t,type:"function"});return r}function wB(e){return BE(e)}var vB=L(()=>{"use strict";lb();ME();mh();Tn()});var kB=L(()=>{"use strict"});var xB=L(()=>{"use strict"});function WE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function TB(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(n=>typeof n=="string"):t.every(n=>Number.isSafeInteger(n)):!1}function Y9(e){if(typeof e!="function")throw new Error("function expected");return!0}function GE(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function YE(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function KE(e){if(!Array.isArray(e))throw new Error("array expected")}function SB(e,t){if(!TB(!0,t))throw new Error(`${e}: array of strings expected`)}function Q9(e,t){if(!TB(!1,t))throw new Error(`${e}: array of numbers expected`)}function PB(...e){let t=s=>s,n=(s,i)=>a=>s(i(a)),r=e.map(s=>s.encode).reduceRight(n,t),o=e.map(s=>s.decode).reduce(n,t);return{encode:r,decode:o}}function X9(e){let t=typeof e=="string"?e.split(""):e,n=t.length;SB("alphabet",t);let r=new Map(t.map((o,s)=>[o,s]));return{encode:o=>(KE(o),o.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]})),decode:o=>(KE(o),o.map(s=>{GE("alphabet.decode",s);let i=r.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return i}))}}function J9(e=""){return GE("join",e),{encode:t=>(SB("join.decode",t),t.join(e)),decode:t=>(GE("join.decode",t),t.split(e))}}function AB(e,t,n){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(KE(e),!e.length)return[];let r=0,o=[],s=Array.from(e,a=>{if(YE(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),i=s.length;for(;;){let a=0,l=!0;for(let c=r;c<i;c++){let u=s[c],d=t*a,p=d+u;if(!Number.isSafeInteger(p)||d/t!==a||p-u!==d)throw new Error("convertRadix: carry overflow");let m=p/n;a=p%n;let g=Math.floor(m);if(s[c]=g,!Number.isSafeInteger(g)||g*n+a!==p)throw new Error("convertRadix: carry overflow");if(l)g?l=!1:r=c;else continue}if(o.push(a),l)break}for(let a=0;a<e.length-1&&e[a]===0;a++)o.push(0);return o.reverse()}function Z9(e){YE(e);let t=2**8;return{encode:n=>{if(!WE(n))throw new Error("radix.encode input should be Uint8Array");return AB(Array.from(n),t,e)},decode:n=>(Q9("radix.decode",n),Uint8Array.from(AB(n,e,t)))}}function e7(e,t){return YE(e),Y9(t),{encode(n){if(!WE(n))throw new Error("checksum.encode: input should be Uint8Array");let r=t(n).slice(0,e),o=new Uint8Array(n.length+e);return o.set(n),o.set(r,n.length),o},decode(n){if(!WE(n))throw new Error("checksum.decode: input should be Uint8Array");let r=n.slice(0,-e),o=n.slice(-e),s=t(r).slice(0,e);for(let i=0;i<e;i++)if(s[i]!==o[i])throw new Error("Invalid checksum");return r}}}var t7,n7,EB,RB=L(()=>{"use strict";t7=e=>PB(Z9(58),X9(e),J9("")),n7=t7("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),EB=e=>PB(e7(4,t=>e(e(t))),n7)});function IB(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function r7(e){let t=IB(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function ZE(e,t=""){return(0,QE.pbkdf2)(XE.sha512,r7(e).nfkd,o7(t),{c:2048,dkLen:64})}var QE,XE,JE,o7,eR=L(()=>{"use strict";QE=require("@noble/hashes/pbkdf2"),XE=require("@noble/hashes/sha2"),JE=require("@noble/hashes/utils");o7=e=>IB("mnemonic"+e)});function fh(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function Gi(e,t,n=""){let r=(0,vr.isBytes)(e),o=e?.length,s=t!==void 0;if(!r||s&&o!==t){let i=n&&`"${n}" `,a=s?` of length ${t}`:"",l=r?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+l)}return e}function gh(e){let t=e.toString(16);return t.length&1?"0"+t:t}function _B(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?rR:BigInt("0x"+e)}function nd(e){return _B((0,vr.bytesToHex)(e))}function oR(e){return(0,vr.abytes)(e),_B((0,vr.bytesToHex)(Uint8Array.from(e).reverse()))}function Ub(e,t){return(0,vr.hexToBytes)(e.toString(16).padStart(t*2,"0"))}function sR(e,t){return Ub(e,t).reverse()}function Sn(e,t,n){let r;if(typeof t=="string")try{r=(0,vr.hexToBytes)(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if((0,vr.isBytes)(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=r.length;if(typeof n=="number"&&o!==n)throw new Error(e+" of length "+n+" expected, got "+o);return r}function CB(e,t,n){return tR(e)&&tR(t)&&tR(n)&&t<=e&&e<n}function NB(e,t,n,r){if(!CB(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Bb(e){let t;for(t=0;e>rR;e>>=nR,t+=1);return t}function OB(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=m=>new Uint8Array(m),o=m=>Uint8Array.of(m),s=r(e),i=r(e),a=0,l=()=>{s.fill(1),i.fill(0),a=0},c=(...m)=>n(i,s,...m),u=(m=r(0))=>{i=c(o(0),m),s=c(),m.length!==0&&(i=c(o(1),m),s=c())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let m=0,g=[];for(;m<t;){s=c();let f=s.slice();g.push(f),m+=s.length}return(0,vr.concatBytes)(...g)};return(m,g)=>{l(),u(m);let f;for(;!(f=g(d()));)u();return l(),f}}function yh(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(o,s,i){let a=e[o];if(i&&a===void 0)return;let l=typeof a;if(l!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${l}`)}Object.entries(t).forEach(([o,s])=>r(o,s,!1)),Object.entries(n).forEach(([o,s])=>r(o,s,!0))}function iR(e){let t=new WeakMap;return(n,...r)=>{let o=t.get(n);if(o!==void 0)return o;let s=e(n,...r);return t.set(n,s),s}}var vr,Qe,rR,nR,tR,Ki,Mb=L(()=>{"use strict";vr=require("@noble/hashes/utils.js"),Qe=require("@noble/hashes/utils.js");rR=BigInt(0),nR=BigInt(1);tR=e=>typeof e=="bigint"&&rR<=e;Ki=e=>(nR<<BigInt(e))-nR});function sr(e,t){let n=e%t;return n>=Hn?n:t+n}function kr(e,t,n){let r=e;for(;t-- >Hn;)r*=r,r%=n;return r}function LB(e,t){if(e===Hn)throw new Error("invert: expected non-zero number");if(t<=Hn)throw new Error("invert: expected positive modulus, got "+t);let n=sr(e,t),r=t,o=Hn,s=Pn,i=Pn,a=Hn;for(;n!==Hn;){let c=r/n,u=r%n,d=o-i*c,p=s-a*c;r=n,n=u,o=i,s=a,i=d,a=p}if(r!==Pn)throw new Error("invert: does not exist");return sr(o,t)}function aR(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function HB(e,t){let n=(e.ORDER+Pn)/BB,r=e.pow(t,n);return aR(e,r,t),r}function a7(e,t){let n=(e.ORDER-MB)/FB,r=e.mul(t,bl),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,bl),o),a=e.mul(s,e.sub(i,e.ONE));return aR(e,a,t),a}function l7(e){let t=Yi(e),n=$B(e),r=n(t,t.neg(t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+s7)/qB;return(a,l)=>{let c=a.pow(l,i),u=a.mul(c,r),d=a.mul(c,o),p=a.mul(c,s),m=a.eql(a.sqr(u),l),g=a.eql(a.sqr(d),l);c=a.cmov(c,u,m),u=a.cmov(p,d,g);let f=a.eql(a.sqr(u),l),y=a.cmov(c,u,f);return aR(a,y,l),y}}function $B(e){if(e<UB)throw new Error("sqrt is not defined for small field");let t=e-Pn,n=0;for(;t%bl===Hn;)t/=bl,n++;let r=bl,o=Yi(e);for(;DB(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return HB;let s=o.pow(r,t),i=(t+Pn)/bl;return function(l,c){if(l.is0(c))return c;if(DB(l,c)!==1)throw new Error("Cannot find square root");let u=n,d=l.mul(l.ONE,s),p=l.pow(c,t),m=l.pow(c,i);for(;!l.eql(p,l.ONE);){if(l.is0(p))return l.ZERO;let g=1,f=l.sqr(p);for(;!l.eql(f,l.ONE);)if(g++,f=l.sqr(f),g===u)throw new Error("Cannot find square root");let y=Pn<<BigInt(u-g-1),w=l.pow(d,y);u=g,d=l.sqr(w),p=l.mul(p,d),m=l.mul(m,w)}return m}}function c7(e){return e%BB===UB?HB:e%FB===MB?a7:e%qB===i7?l7(e):$B(e)}function lR(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=u7.reduce((r,o)=>(r[o]="function",r),t);return yh(e,n),e}function d7(e,t,n){if(n<Hn)throw new Error("invalid exponent, negatives unsupported");if(n===Hn)return e.ONE;if(n===Pn)return t;let r=e.ONE,o=t;for(;n>Hn;)n&Pn&&(r=e.mul(r,o)),o=e.sqr(o),n>>=Pn;return r}function Fb(e,t,n=!1){let r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((i,a,l)=>e.is0(a)?i:(r[l]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,l)=>e.is0(a)?i:(r[l]=e.mul(i,r[l]),e.mul(i,a)),s),r}function DB(e,t){let n=(e.ORDER-Pn)/bl,r=e.pow(t,n),o=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),i=e.eql(r,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function qb(e,t){t!==void 0&&(0,Qe.anumber)(t);let n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Yi(e,t,n=!1,r={}){if(e<=Hn)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");let p=t;p.BITS&&(o=p.BITS),p.sqrt&&(s=p.sqrt),typeof p.isLE=="boolean"&&(n=p.isLE),typeof p.modFromBytes=="boolean"&&(i=p.modFromBytes),a=p.allowedLengths}else typeof t=="number"&&(o=t),r.sqrt&&(s=r.sqrt);let{nBitLength:l,nByteLength:c}=qb(e,o);if(c>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,d=Object.freeze({ORDER:e,isLE:n,BITS:l,BYTES:c,MASK:Ki(l),ZERO:Hn,ONE:Pn,allowedLengths:a,create:p=>sr(p,e),isValid:p=>{if(typeof p!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof p);return Hn<=p&&p<e},is0:p=>p===Hn,isValidNot0:p=>!d.is0(p)&&d.isValid(p),isOdd:p=>(p&Pn)===Pn,neg:p=>sr(-p,e),eql:(p,m)=>p===m,sqr:p=>sr(p*p,e),add:(p,m)=>sr(p+m,e),sub:(p,m)=>sr(p-m,e),mul:(p,m)=>sr(p*m,e),pow:(p,m)=>d7(d,p,m),div:(p,m)=>sr(p*LB(m,e),e),sqrN:p=>p*p,addN:(p,m)=>p+m,subN:(p,m)=>p-m,mulN:(p,m)=>p*m,inv:p=>LB(p,e),sqrt:s||(p=>(u||(u=c7(e)),u(d,p))),toBytes:p=>n?sR(p,c):Ub(p,c),fromBytes:(p,m=!0)=>{if(a){if(!a.includes(p.length)||p.length>c)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+p.length);let f=new Uint8Array(c);f.set(p,n?0:f.length-p.length),p=f}if(p.length!==c)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+p.length);let g=n?oR(p):nd(p);if(i&&(g=sr(g,e)),!m&&!d.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:p=>Fb(d,p),cmov:(p,m,g)=>g?m:p});return Object.freeze(d)}function VB(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function cR(e){let t=VB(e);return t+Math.ceil(t/2)}function uR(e,t,n=!1){let r=e.length,o=VB(t),s=cR(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);let i=n?oR(e):nd(e),a=sr(i,t-Pn)+Pn;return n?sR(a,o):Ub(a,o)}var Hn,Pn,bl,UB,BB,MB,s7,FB,i7,qB,u7,bh=L(()=>{"use strict";Mb();Hn=BigInt(0),Pn=BigInt(1),bl=BigInt(2),UB=BigInt(3),BB=BigInt(4),MB=BigInt(5),s7=BigInt(7),FB=BigInt(8),i7=BigInt(9),qB=BigInt(16);u7=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function wh(e,t){let n=t.negate();return e?n:t}function $b(e,t){let n=Fb(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function GB(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function dR(e,t){GB(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=Ki(e),i=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function jB(e,t,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,a=Number(e&o),l=e>>i;a>r&&(a-=s,l+=wl);let c=t*r,u=c+Math.abs(a)-1,d=a===0,p=a<0,m=t%2!==0;return{nextN:l,offset:u,isZero:d,isNeg:p,isNegF:m,offsetF:c}}function p7(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function m7(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}function mR(e){return KB.get(e)||1}function zB(e){if(e!==rd)throw new Error("invalid wNAF")}function YB(e,t,n,r){let o=t,s=e.ZERO,i=e.ZERO;for(;n>rd||r>rd;)n&wl&&(s=s.add(o)),r&wl&&(i=i.add(o)),o=o.double(),n>>=wl,r>>=wl;return{p1:s,p2:i}}function QB(e,t,n,r){p7(n,e),m7(r,t);let o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=Bb(BigInt(o)),l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);let c=Ki(l),u=new Array(Number(c)+1).fill(i),d=Math.floor((t.BITS-1)/l)*l,p=i;for(let m=d;m>=0;m-=l){u.fill(i);for(let f=0;f<s;f++){let y=r[f],w=Number(y>>BigInt(m)&c);u[w]=u[w].add(n[f])}let g=i;for(let f=u.length-1,y=i;f>0;f--)y=y.add(u[f]),g=g.add(y);if(p=p.add(g),m!==0)for(let f=0;f<l;f++)p=p.double()}return p}function WB(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return lR(t),t}else return Yi(e,{isLE:n})}function XB(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let c=t[l];if(!(typeof c=="bigint"&&c>rd))throw new Error(`CURVE.${l} must be positive bigint`)}let o=WB(t.p,n.Fp,r),s=WB(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!o.isValid(t[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}var rd,wl,pR,KB,Hb,JB=L(()=>{"use strict";Mb();bh();rd=BigInt(0),wl=BigInt(1);pR=new WeakMap,KB=new WeakMap;Hb=class{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>rd;)n&wl&&(r=r.add(o)),o=o.double(),n>>=wl;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=dR(n,this.bits),s=[],i=t,a=i;for(let l=0;l<r;l++){a=i,s.push(a);for(let c=1;c<o;c++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=dR(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:c,isZero:u,isNeg:d,isNegF:p,offsetF:m}=jB(r,a,i);r=l,u?s=s.add(wh(p,n[m])):o=o.add(wh(d,n[c]))}return zB(r),{p:o,f:s}}wNAFUnsafe(t,n,r,o=this.ZERO){let s=dR(t,this.bits);for(let i=0;i<s.windows&&r!==rd;i++){let{nextN:a,offset:l,isZero:c,isNeg:u}=jB(r,i,s);if(r=a,!c){let d=n[l];o=o.add(u?d.negate():d)}}return zB(r),o}getPrecomputes(t,n,r){let o=pR.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),pR.set(n,o))),o}cached(t,n,r){let o=mR(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let s=mR(t);return s===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,o)}createCache(t,n){GB(n,this.bits),KB.set(t,n),pR.delete(t)}hasCache(t){return mR(t)!==1}}});function h7(e,t,n){let[[r,o],[s,i]]=t,a=ZB(i*e,n),l=ZB(-o*e,n),c=e-a*r-l*s,u=-a*o-l*i,d=c<zs,p=u<zs;d&&(c=-c),p&&(u=-u);let m=Ki(Math.ceil(Bb(n)/2))+sd;if(c<zs||c>=m||u<zs||u>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:c,k2neg:p,k2:u}}function fR(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function hR(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return fh(n.lowS,"lowS"),fh(n.prehash,"prehash"),n.format!==void 0&&fR(n.format),n}function od(e,t){let{BYTES:n}=e,r;if(typeof t=="bigint")r=t;else{let o=Sn("private key",t);try{r=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function g7(e,t={}){let n=XB("weierstrass",e,t),{Fp:r,Fn:o}=n,s=n.CURVE,{h:i,n:a}=s;yh(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:l}=t;if(l&&(!r.is0(s.a)||typeof l.beta!="bigint"||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let c=oM(r,o);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(ne,M,W){let{x:I,y:N}=M.toAffine(),G=r.toBytes(I);if(fh(W,"isCompressed"),W){u();let re=!r.isOdd(N);return(0,Qe.concatBytes)(rM(re),G)}else return(0,Qe.concatBytes)(Uint8Array.of(4),G,r.toBytes(N))}function p(ne){Gi(ne,void 0,"Point");let{publicKey:M,publicKeyUncompressed:W}=c,I=ne.length,N=ne[0],G=ne.subarray(1);if(I===M&&(N===2||N===3)){let re=r.fromBytes(G);if(!r.isValid(re))throw new Error("bad point: is not on curve, wrong x");let Z=f(re),Q;try{Q=r.sqrt(Z)}catch(Ne){let ke=Ne instanceof Error?": "+Ne.message:"";throw new Error("bad point: is not on curve, sqrt error"+ke)}u();let ie=r.isOdd(Q);return(N&1)===1!==ie&&(Q=r.neg(Q)),{x:re,y:Q}}else if(I===W&&N===4){let re=r.BYTES,Z=r.fromBytes(G.subarray(0,re)),Q=r.fromBytes(G.subarray(re,re*2));if(!y(Z,Q))throw new Error("bad point: is not on curve");return{x:Z,y:Q}}else throw new Error(`bad point: got length ${I}, expected compressed=${M} or uncompressed=${W}`)}let m=t.toBytes||d,g=t.fromBytes||p;function f(ne){let M=r.sqr(ne),W=r.mul(M,ne);return r.add(r.add(W,r.mul(ne,s.a)),s.b)}function y(ne,M){let W=r.sqr(M),I=f(ne);return r.eql(W,I)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=r.mul(r.pow(s.a,Vb),f7),v=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,v)))throw new Error("bad curve params: a or b");function x(ne,M,W=!1){if(!r.isValid(M)||W&&r.is0(M))throw new Error(`bad point coordinate ${ne}`);return M}function k(ne){if(!(ne instanceof Y))throw new Error("ProjectivePoint expected")}function S(ne){if(!l||!l.basises)throw new Error("no endo");return h7(ne,l.basises,o.ORDER)}let D=iR((ne,M)=>{let{X:W,Y:I,Z:N}=ne;if(r.eql(N,r.ONE))return{x:W,y:I};let G=ne.is0();M==null&&(M=G?r.ONE:r.inv(N));let re=r.mul(W,M),Z=r.mul(I,M),Q=r.mul(N,M);if(G)return{x:r.ZERO,y:r.ZERO};if(!r.eql(Q,r.ONE))throw new Error("invZ was invalid");return{x:re,y:Z}}),q=iR(ne=>{if(ne.is0()){if(t.allowInfinityPoint&&!r.is0(ne.Y))return;throw new Error("bad point: ZERO")}let{x:M,y:W}=ne.toAffine();if(!r.isValid(M)||!r.isValid(W))throw new Error("bad point: x or y not field elements");if(!y(M,W))throw new Error("bad point: equation left != right");if(!ne.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function V(ne,M,W,I,N){return W=new Y(r.mul(W.X,ne),W.Y,W.Z),M=wh(I,M),W=wh(N,W),M.add(W)}class Y{constructor(M,W,I){this.X=x("x",M),this.Y=x("y",W,!0),this.Z=x("z",I),Object.freeze(this)}static CURVE(){return s}static fromAffine(M){let{x:W,y:I}=M||{};if(!M||!r.isValid(W)||!r.isValid(I))throw new Error("invalid affine point");if(M instanceof Y)throw new Error("projective point not allowed");return r.is0(W)&&r.is0(I)?Y.ZERO:new Y(W,I,r.ONE)}static fromBytes(M){let W=Y.fromAffine(g(Gi(M,void 0,"point")));return W.assertValidity(),W}static fromHex(M){return Y.fromBytes(Sn("pointHex",M))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(M=8,W=!0){return ce.createCache(this,M),W||this.multiply(Vb),this}assertValidity(){q(this)}hasEvenY(){let{y:M}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(M)}equals(M){k(M);let{X:W,Y:I,Z:N}=this,{X:G,Y:re,Z}=M,Q=r.eql(r.mul(W,Z),r.mul(G,N)),ie=r.eql(r.mul(I,Z),r.mul(re,N));return Q&&ie}negate(){return new Y(this.X,r.neg(this.Y),this.Z)}double(){let{a:M,b:W}=s,I=r.mul(W,Vb),{X:N,Y:G,Z:re}=this,Z=r.ZERO,Q=r.ZERO,ie=r.ZERO,me=r.mul(N,N),Ne=r.mul(G,G),ke=r.mul(re,re),be=r.mul(N,G);return be=r.add(be,be),ie=r.mul(N,re),ie=r.add(ie,ie),Z=r.mul(M,ie),Q=r.mul(I,ke),Q=r.add(Z,Q),Z=r.sub(Ne,Q),Q=r.add(Ne,Q),Q=r.mul(Z,Q),Z=r.mul(be,Z),ie=r.mul(I,ie),ke=r.mul(M,ke),be=r.sub(me,ke),be=r.mul(M,be),be=r.add(be,ie),ie=r.add(me,me),me=r.add(ie,me),me=r.add(me,ke),me=r.mul(me,be),Q=r.add(Q,me),ke=r.mul(G,re),ke=r.add(ke,ke),me=r.mul(ke,be),Z=r.sub(Z,me),ie=r.mul(ke,Ne),ie=r.add(ie,ie),ie=r.add(ie,ie),new Y(Z,Q,ie)}add(M){k(M);let{X:W,Y:I,Z:N}=this,{X:G,Y:re,Z}=M,Q=r.ZERO,ie=r.ZERO,me=r.ZERO,Ne=s.a,ke=r.mul(s.b,Vb),be=r.mul(W,G),qe=r.mul(I,re),ze=r.mul(N,Z),ut=r.add(W,I),He=r.add(G,re);ut=r.mul(ut,He),He=r.add(be,qe),ut=r.sub(ut,He),He=r.add(W,N);let it=r.add(G,Z);return He=r.mul(He,it),it=r.add(be,ze),He=r.sub(He,it),it=r.add(I,N),Q=r.add(re,Z),it=r.mul(it,Q),Q=r.add(qe,ze),it=r.sub(it,Q),me=r.mul(Ne,He),Q=r.mul(ke,ze),me=r.add(Q,me),Q=r.sub(qe,me),me=r.add(qe,me),ie=r.mul(Q,me),qe=r.add(be,be),qe=r.add(qe,be),ze=r.mul(Ne,ze),He=r.mul(ke,He),qe=r.add(qe,ze),ze=r.sub(be,ze),ze=r.mul(Ne,ze),He=r.add(He,ze),be=r.mul(qe,He),ie=r.add(ie,be),be=r.mul(it,He),Q=r.mul(ut,Q),Q=r.sub(Q,be),be=r.mul(ut,qe),me=r.mul(it,me),me=r.add(me,be),new Y(Q,ie,me)}subtract(M){return this.add(M.negate())}is0(){return this.equals(Y.ZERO)}multiply(M){let{endo:W}=t;if(!o.isValidNot0(M))throw new Error("invalid scalar: out of range");let I,N,G=re=>ce.cached(this,re,Z=>$b(Y,Z));if(W){let{k1neg:re,k1:Z,k2neg:Q,k2:ie}=S(M),{p:me,f:Ne}=G(Z),{p:ke,f:be}=G(ie);N=Ne.add(be),I=V(W.beta,me,ke,re,Q)}else{let{p:re,f:Z}=G(M);I=re,N=Z}return $b(Y,[I,N])[0]}multiplyUnsafe(M){let{endo:W}=t,I=this;if(!o.isValid(M))throw new Error("invalid scalar: out of range");if(M===zs||I.is0())return Y.ZERO;if(M===sd)return I;if(ce.hasCache(this))return this.multiply(M);if(W){let{k1neg:N,k1:G,k2neg:re,k2:Z}=S(M),{p1:Q,p2:ie}=YB(Y,I,G,Z);return V(W.beta,Q,ie,N,re)}else return ce.unsafe(I,M)}multiplyAndAddUnsafe(M,W,I){let N=this.multiplyUnsafe(W).add(M.multiplyUnsafe(I));return N.is0()?void 0:N}toAffine(M){return D(this,M)}isTorsionFree(){let{isTorsionFree:M}=t;return i===sd?!0:M?M(Y,this):ce.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:M}=t;return i===sd?this:M?M(Y,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(M=!0){return fh(M,"isCompressed"),this.assertValidity(),m(Y,this,M)}toHex(M=!0){return(0,Qe.bytesToHex)(this.toBytes(M))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(M=!0){return this.toBytes(M)}_setWindowSize(M){this.precompute(M)}static normalizeZ(M){return $b(Y,M)}static msm(M,W){return QB(Y,o,M,W)}static fromPrivateKey(M){return Y.BASE.multiply(od(o,M))}}Y.BASE=new Y(s.Gx,s.Gy,r.ONE),Y.ZERO=new Y(r.ZERO,r.ONE,r.ZERO),Y.Fp=r,Y.Fn=o;let ee=o.BITS,ce=new Hb(Y,t.endo?Math.ceil(ee/2):ee);return Y.BASE.precompute(8),Y}function rM(e){return Uint8Array.of(e?2:3)}function oM(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function y7(e,t={}){let{Fn:n}=e,r=t.randomBytes||Qe.randomBytes,o=Object.assign(oM(e.Fp,n),{seed:cR(n.ORDER)});function s(m){try{return!!od(n,m)}catch{return!1}}function i(m,g){let{publicKey:f,publicKeyUncompressed:y}=o;try{let w=m.length;return g===!0&&w!==f||g===!1&&w!==y?!1:!!e.fromBytes(m)}catch{return!1}}function a(m=r(o.seed)){return uR(Gi(m,o.seed,"seed"),n.ORDER)}function l(m,g=!0){return e.BASE.multiply(od(n,m)).toBytes(g)}function c(m){let g=a(m);return{secretKey:g,publicKey:l(g)}}function u(m){if(typeof m=="bigint")return!1;if(m instanceof e)return!0;let{secretKey:g,publicKey:f,publicKeyUncompressed:y}=o;if(n.allowedLengths||g===f)return;let w=Sn("key",m).length;return w===f||w===y}function d(m,g,f=!0){if(u(m)===!0)throw new Error("first arg must be private key");if(u(g)===!1)throw new Error("second arg must be public key");let y=od(n,m);return e.fromHex(g).multiply(y).toBytes(f)}return Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:c,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:m=>od(n,m),precompute(m=8,g=e.BASE){return g.precompute(m,!1)}},lengths:o})}function b7(e,t,n={}){(0,tM.ahash)(t),yh(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=n.randomBytes||Qe.randomBytes,o=n.hmac||((W,...I)=>(0,eM.hmac)(t,W,(0,Qe.concatBytes)(...I))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:l}=i,{keygen:c,getPublicKey:u,getSharedSecret:d,utils:p,lengths:m}=y7(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},f="compact";function y(W){let I=a>>sd;return W>I}function w(W,I){if(!i.isValidNot0(I))throw new Error(`invalid signature ${W}: out of range 1..Point.Fn.ORDER`);return I}function v(W,I){fR(I);let N=m.signature,G=I==="compact"?N:I==="recovered"?N+1:void 0;return Gi(W,G,`${I} signature`)}class x{constructor(I,N,G){this.r=w("r",I),this.s=w("s",N),G!=null&&(this.recovery=G),Object.freeze(this)}static fromBytes(I,N=f){v(I,N);let G;if(N==="der"){let{r:ie,s:me}=js.toSig(Gi(I));return new x(ie,me)}N==="recovered"&&(G=I[0],N="compact",I=I.subarray(1));let re=i.BYTES,Z=I.subarray(0,re),Q=I.subarray(re,re*2);return new x(i.fromBytes(Z),i.fromBytes(Q),G)}static fromHex(I,N){return this.fromBytes((0,Qe.hexToBytes)(I),N)}addRecoveryBit(I){return new x(this.r,this.s,I)}recoverPublicKey(I){let N=s.ORDER,{r:G,s:re,recovery:Z}=this;if(Z==null||![0,1,2,3].includes(Z))throw new Error("recovery id invalid");if(a*nM<N&&Z>1)throw new Error("recovery id is ambiguous for h>1 curve");let ie=Z===2||Z===3?G+a:G;if(!s.isValid(ie))throw new Error("recovery id 2 or 3 invalid");let me=s.toBytes(ie),Ne=e.fromBytes((0,Qe.concatBytes)(rM((Z&1)===0),me)),ke=i.inv(ie),be=S(Sn("msgHash",I)),qe=i.create(-be*ke),ze=i.create(re*ke),ut=e.BASE.multiplyUnsafe(qe).add(Ne.multiplyUnsafe(ze));if(ut.is0())throw new Error("point at infinify");return ut.assertValidity(),ut}hasHighS(){return y(this.s)}toBytes(I=f){if(fR(I),I==="der")return(0,Qe.hexToBytes)(js.hexFromSig(this));let N=i.toBytes(this.r),G=i.toBytes(this.s);if(I==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return(0,Qe.concatBytes)(Uint8Array.of(this.recovery),N,G)}return(0,Qe.concatBytes)(N,G)}toHex(I){return(0,Qe.bytesToHex)(this.toBytes(I))}assertValidity(){}static fromCompact(I){return x.fromBytes(Sn("sig",I),"compact")}static fromDER(I){return x.fromBytes(Sn("sig",I),"der")}normalizeS(){return this.hasHighS()?new x(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return(0,Qe.bytesToHex)(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return(0,Qe.bytesToHex)(this.toBytes("compact"))}}let k=n.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let N=nd(I),G=I.length*8-l;return G>0?N>>BigInt(G):N},S=n.bits2int_modN||function(I){return i.create(k(I))},D=Ki(l);function q(W){return NB("num < 2^"+l,W,zs,D),i.toBytes(W)}function V(W,I){return Gi(W,void 0,"message"),I?Gi(t(W),void 0,"prehashed message"):W}function Y(W,I,N){if(["recovered","canonical"].some(qe=>qe in N))throw new Error("sign() legacy options not supported");let{lowS:G,prehash:re,extraEntropy:Z}=hR(N,g);W=V(W,re);let Q=S(W),ie=od(i,I),me=[q(ie),q(Q)];if(Z!=null&&Z!==!1){let qe=Z===!0?r(m.secretKey):Z;me.push(Sn("extraEntropy",qe))}let Ne=(0,Qe.concatBytes)(...me),ke=Q;function be(qe){let ze=k(qe);if(!i.isValidNot0(ze))return;let ut=i.inv(ze),He=e.BASE.multiply(ze).toAffine(),it=i.create(He.x);if(it===zs)return;let je=i.create(ut*i.create(ke+it*ie));if(je===zs)return;let Ss=(He.x===it?0:2)|Number(He.y&sd),Br=je;return G&&y(je)&&(Br=i.neg(je),Ss^=1),new x(it,Br,Ss)}return{seed:Ne,k2sig:be}}function ee(W,I,N={}){W=Sn("message",W);let{seed:G,k2sig:re}=Y(W,I,N);return OB(t.outputLen,i.BYTES,o)(G,re)}function ce(W){let I,N=typeof W=="string"||(0,Qe.isBytes)(W),G=!N&&W!==null&&typeof W=="object"&&typeof W.r=="bigint"&&typeof W.s=="bigint";if(!N&&!G)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(G)I=new x(W.r,W.s);else if(N){try{I=x.fromBytes(Sn("sig",W),"der")}catch(re){if(!(re instanceof js.Err))throw re}if(!I)try{I=x.fromBytes(Sn("sig",W),"compact")}catch{return!1}}return I||!1}function ne(W,I,N,G={}){let{lowS:re,prehash:Z,format:Q}=hR(G,g);if(N=Sn("publicKey",N),I=V(Sn("message",I),Z),"strict"in G)throw new Error("options.strict was renamed to lowS");let ie=Q===void 0?ce(W):x.fromBytes(Sn("sig",W),Q);if(ie===!1)return!1;try{let me=e.fromBytes(N);if(re&&ie.hasHighS())return!1;let{r:Ne,s:ke}=ie,be=S(I),qe=i.inv(ke),ze=i.create(be*qe),ut=i.create(Ne*qe),He=e.BASE.multiplyUnsafe(ze).add(me.multiplyUnsafe(ut));return He.is0()?!1:i.create(He.x)===Ne}catch{return!1}}function M(W,I,N={}){let{prehash:G}=hR(N,g);return I=V(I,G),x.fromBytes(W,"recovered").recoverPublicKey(I).toBytes()}return Object.freeze({keygen:c,getPublicKey:u,getSharedSecret:d,utils:p,lengths:m,Point:e,sign:ee,verify:ne,recoverPublicKey:M,Signature:x,hash:t})}function w7(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=Yi(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),s={Fp:n,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function v7(e){let{CURVE:t,curveOpts:n}=w7(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function k7(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,qb(n.Fn.ORDER,n.Fn.BITS))})}function sM(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=v7(e),s=g7(t,n),i=b7(s,r,o);return k7(e,i)}var eM,tM,ZB,gR,js,zs,sd,nM,Vb,f7,iM=L(()=>{"use strict";eM=require("@noble/hashes/hmac.js"),tM=require("@noble/hashes/utils");Mb();JB();bh();ZB=(e,t)=>(e+(e>=0?t:-t)/nM)/t;gR=class extends Error{constructor(t=""){super(t)}},js={Err:gR,_tlv:{encode:(e,t)=>{let{Err:n}=js;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");let r=t.length/2,o=gh(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let s=r>127?gh(o.length/2|128):"";return gh(e)+s+o+t},decode(e,t){let{Err:n}=js,r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");let o=t[r++],s=!!(o&128),i=0;if(!s)i=o;else{let l=o&127;if(!l)throw new n("tlv.decode(long): indefinite length not supported");if(l>4)throw new n("tlv.decode(long): byte length is too big");let c=t.subarray(r,r+l);if(c.length!==l)throw new n("tlv.decode: length bytes not complete");if(c[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let u of c)i=i<<8|u;if(r+=l,i<128)throw new n("tlv.decode(long): not minimal encoding")}let a=t.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+i)}}},_int:{encode(e){let{Err:t}=js;if(e<zs)throw new t("integer: negative integers are not allowed");let n=gh(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){let{Err:t}=js;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 nd(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=js,o=Sn("signature",e),{v:s,l:i}=r.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,s),{v:c,l:u}=r.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(c)}},hexFromSig(e){let{_tlv:t,_int:n}=js,r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),s=r+o;return t.encode(48,s)}},zs=BigInt(0),sd=BigInt(1),nM=BigInt(2),Vb=BigInt(3),f7=BigInt(4)});function aM(e,t){let n=r=>sM({...e,hash:r});return{...n(t),create:n}}var lM=L(()=>{"use strict";iM();});function T7(e){let t=bR.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),l=BigInt(88),c=e*e*e%t,u=c*c*e%t,d=kr(u,n,t)*u%t,p=kr(d,n,t)*u%t,m=kr(p,cM,t)*c%t,g=kr(m,o,t)*m%t,f=kr(g,s,t)*g%t,y=kr(f,a,t)*f%t,w=kr(y,l,t)*y%t,v=kr(w,a,t)*f%t,x=kr(v,n,t)*u%t,k=kr(x,i,t)*g%t,S=kr(k,r,t)*c%t,D=kr(S,cM,t);if(!yR.eql(yR.sqr(D),e))throw new Error("Cannot find square root");return D}var uM,x7,bR,A7,cM,yR,Xo,dM=L(()=>{"use strict";uM=require("@noble/hashes/sha2.js"),x7=require("@noble/hashes/utils.js");lM();bh();bR={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},A7={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},cM=BigInt(2);yR=Yi(bR.p,{sqrt:T7}),Xo=aM({...bR,Fp:yR,lowS:!0,endo:A7},uM.sha256)});function pM(e){(0,_t.abytes)(e);let t=e.length===0?"0":(0,_t.bytesToHex)(e);return BigInt("0x"+t)}function S7(e){if(typeof e!="bigint")throw new Error("bigint expected");return(0,_t.hexToBytes)(e.toString(16).padStart(64,"0"))}var xR,mM,id,_t,jb,wR,P7,vR,kR,E7,R7,zb,Wb,hM=L(()=>{"use strict";bh();dM();xR=require("@noble/hashes/hmac"),mM=require("@noble/hashes/legacy"),id=require("@noble/hashes/sha2"),_t=require("@noble/hashes/utils");RB();jb=Xo.ProjectivePoint,wR=EB(id.sha256);P7=(0,_t.utf8ToBytes)("Bitcoin seed"),vR={private:76066276,public:76067358},kR=2147483648,E7=e=>(0,mM.ripemd160)((0,id.sha256)(e)),R7=e=>(0,_t.createView)(e).getUint32(0,!1),zb=e=>{if(!Number.isSafeInteger(e)||e<0||e>2**32-1)throw new Error("invalid number, should be from 0 to 2**32-1, got "+e);let t=new Uint8Array(4);return(0,_t.createView)(t).setUint32(0,e,!1),t},Wb=class e{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return R7(this.pubHash)}get identifier(){return this.pubHash}get pubKeyHash(){return this.pubHash}get privateKey(){return this.privKeyBytes||null}get publicKey(){return this.pubKey||null}get privateExtendedKey(){let t=this.privateKey;if(!t)throw new Error("No private key");return wR.encode(this.serialize(this.versions.private,(0,_t.concatBytes)(new Uint8Array([0]),t)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return wR.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(t,n=vR){if((0,_t.abytes)(t),8*t.length<128||8*t.length>512)throw new Error("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+t.length);let r=(0,xR.hmac)(id.sha512,P7,t);return new e({versions:n,chainCode:r.slice(32),privateKey:r.slice(0,32)})}static fromExtendedKey(t,n=vR){let r=wR.decode(t),o=(0,_t.createView)(r),s=o.getUint32(0,!1),i={versions:n,depth:r[4],parentFingerprint:o.getUint32(5,!1),index:o.getUint32(9,!1),chainCode:r.slice(13,45)},a=r.slice(45),l=a[0]===0;if(s!==n[l?"private":"public"])throw new Error("Version mismatch");return l?new e({...i,privateKey:a.slice(1)}):new e({...i,publicKey:a})}static fromJSON(t){return e.fromExtendedKey(t.xpriv)}constructor(t){if(this.depth=0,this.index=0,this.chainCode=null,this.parentFingerprint=0,!t||typeof t!="object")throw new Error("HDKey.constructor must not be called directly");if(this.versions=t.versions||vR,this.depth=t.depth||0,this.chainCode=t.chainCode||null,this.index=t.index||0,this.parentFingerprint=t.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(t.publicKey&&t.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(t.privateKey){if(!Xo.utils.isValidPrivateKey(t.privateKey))throw new Error("Invalid private key");this.privKey=typeof t.privateKey=="bigint"?t.privateKey:pM(t.privateKey),this.privKeyBytes=S7(this.privKey),this.pubKey=Xo.getPublicKey(t.privateKey,!0)}else if(t.publicKey)this.pubKey=jb.fromHex(t.publicKey).toRawBytes(!0);else throw new Error("HDKey: no public or private key provided");this.pubHash=E7(this.pubKey)}derive(t){if(!/^[mM]'?/.test(t))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(t))return this;let n=t.replace(/^[mM]'?\//,"").split("/"),r=this;for(let o of n){let s=/^(\d+)('?)$/.exec(o),i=s&&s[1];if(!s||s.length!==3||typeof i!="string")throw new Error("invalid child index: "+o);let a=+i;if(!Number.isSafeInteger(a)||a>=kR)throw new Error("Invalid index");s[2]==="'"&&(a+=kR),r=r.deriveChild(a)}return r}deriveChild(t){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let n=zb(t);if(t>=kR){let a=this.privateKey;if(!a)throw new Error("Could not derive hardened child key");n=(0,_t.concatBytes)(new Uint8Array([0]),a,n)}else n=(0,_t.concatBytes)(this.pubKey,n);let r=(0,xR.hmac)(id.sha512,this.chainCode,n),o=pM(r.slice(0,32)),s=r.slice(32);if(!Xo.utils.isValidPrivateKey(o))throw new Error("Tweak bigger than curve order");let i={versions:this.versions,chainCode:s,depth:this.depth+1,parentFingerprint:this.fingerprint,index:t};try{if(this.privateKey){let a=sr(this.privKey+o,Xo.CURVE.n);if(!Xo.utils.isValidPrivateKey(a))throw new Error("The tweak was out of range or the resulted private key is invalid");i.privateKey=a}else{let a=jb.fromHex(this.pubKey).add(jb.fromPrivateKey(o));if(a.equals(jb.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=a.toRawBytes(!0)}return new e(i)}catch{return this.deriveChild(t+1)}}sign(t){if(!this.privateKey)throw new Error("No privateKey set!");return(0,_t.abytes)(t,32),Xo.sign(t,this.privKey).toCompactRawBytes()}verify(t,n){if((0,_t.abytes)(t,32),(0,_t.abytes)(n,64),!this.publicKey)throw new Error("No publicKey set!");let r;try{r=Xo.Signature.fromCompact(n)}catch{return!1}return Xo.verify(r,t,this.publicKey)}wipePrivateData(){return this.privKey=void 0,this.privKeyBytes&&(this.privKeyBytes.fill(0),this.privKeyBytes=void 0),this}toJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(t,n){if(!this.chainCode)throw new Error("No chainCode set");return(0,_t.abytes)(n,33),(0,_t.concatBytes)(zb(t),new Uint8Array([this.depth]),zb(this.parentFingerprint),zb(this.index),this.chainCode,n)}}});function En(e,t){let n=e%t;return n>=$n?n:t+n}function xr(e,t,n){let r=e;for(;t-- >$n;)r*=r,r%=n;return r}function Gb(e,t){if(e===$n)throw new Error("invert: expected non-zero number");if(t<=$n)throw new Error("invert: expected positive modulus, got "+t);let n=En(e,t),r=t,o=$n,s=Rn,i=Rn,a=$n;for(;n!==$n;){let c=r/n,u=r%n,d=o-i*c,p=s-a*c;r=n,n=u,o=i,s=a,i=d,a=p}if(r!==Rn)throw new Error("invert: does not exist");return En(o,t)}function vM(e,t){let n=(e.ORDER+Rn)/yM,r=e.pow(t,n);if(!e.eql(e.sqr(r),t))throw new Error("Cannot find square root");return r}function _7(e,t){let n=(e.ORDER-bM)/wM,r=e.mul(t,vl),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,vl),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function C7(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-Rn,n=0;for(;t%vl===$n;)t/=vl,n++;let r=vl,o=vh(e);for(;fM(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return vM;let s=o.pow(r,t),i=(t+Rn)/vl;return function(l,c){if(l.is0(c))return c;if(fM(l,c)!==1)throw new Error("Cannot find square root");let u=n,d=l.mul(l.ONE,s),p=l.pow(c,t),m=l.pow(c,i);for(;!l.eql(p,l.ONE);){if(l.is0(p))return l.ZERO;let g=1,f=l.sqr(p);for(;!l.eql(f,l.ONE);)if(g++,f=l.sqr(f),g===u)throw new Error("Cannot find square root");let y=Rn<<BigInt(u-g-1),w=l.pow(d,y);u=g,d=l.sqr(w),p=l.mul(p,d),m=l.mul(m,w)}return m}}function N7(e){return e%yM===I7?vM:e%wM===bM?_7:C7(e)}function AR(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=O7.reduce((r,o)=>(r[o]="function",r),t);return sl(e,n)}function L7(e,t,n){if(n<$n)throw new Error("invalid exponent, negatives unsupported");if(n===$n)return e.ONE;if(n===Rn)return t;let r=e.ONE,o=t;for(;n>$n;)n&Rn&&(r=e.mul(r,o)),o=e.sqr(o),n>>=Rn;return r}function TR(e,t,n=!1){let r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((i,a,l)=>e.is0(a)?i:(r[l]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,l)=>e.is0(a)?i:(r[l]=e.mul(i,r[l]),e.mul(i,a)),s),r}function fM(e,t){let n=(e.ORDER-Rn)/vl,r=e.pow(t,n),o=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),i=e.eql(r,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function SR(e,t){t!==void 0&&(0,gM.anumber)(t);let n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function vh(e,t,n=!1,r={}){if(e<=$n)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=SR(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:n,BITS:o,BYTES:s,MASK:ol(o),ZERO:$n,ONE:Rn,create:l=>En(l,e),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return $n<=l&&l<e},is0:l=>l===$n,isOdd:l=>(l&Rn)===Rn,neg:l=>En(-l,e),eql:(l,c)=>l===c,sqr:l=>En(l*l,e),add:(l,c)=>En(l+c,e),sub:(l,c)=>En(l-c,e),mul:(l,c)=>En(l*c,e),pow:(l,c)=>L7(a,l,c),div:(l,c)=>En(l*Gb(c,e),e),sqrN:l=>l*l,addN:(l,c)=>l+c,subN:(l,c)=>l-c,mulN:(l,c)=>l*c,inv:l=>Gb(l,e),sqrt:r.sqrt||(l=>(i||(i=N7(e)),i(a,l))),toBytes:l=>n?dE(l,s):nl(l,s),fromBytes:l=>{if(l.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+l.length);return n?uE(l):qs(l)},invertBatch:l=>TR(a,l),cmov:(l,c,u)=>u?c:l});return Object.freeze(a)}function kM(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function PR(e){let t=kM(e);return t+Math.ceil(t/2)}function xM(e,t,n=!1){let r=e.length,o=kM(t),s=PR(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);let i=n?uE(e):qs(e),a=En(i,t-Rn)+Rn;return n?dE(a,o):nl(a,o)}var gM,$n,Rn,vl,I7,yM,bM,wM,O7,Kb=L(()=>{"use strict";gM=require("@noble/hashes/utils");Hu();$n=BigInt(0),Rn=BigInt(1),vl=BigInt(2),I7=BigInt(3),yM=BigInt(4),bM=BigInt(5),wM=BigInt(8);O7=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function ER(e,t){let n=t.negate();return e?n:t}function SM(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function RR(e,t){SM(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=ol(e),i=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function TM(e,t,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,a=Number(e&o),l=e>>i;a>r&&(a-=s,l+=CR);let c=t*r,u=c+Math.abs(a)-1,d=a===0,p=a<0,m=t%2!==0;return{nextN:l,offset:u,isZero:d,isNeg:p,isNegF:m,offsetF:c}}function D7(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function U7(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}function _R(e){return PM.get(e)||1}function EM(e,t){return{constTimeNegate:ER,hasPrecomputes(n){return _R(n)!==1},unsafeLadder(n,r,o=e.ZERO){let s=n;for(;r>AM;)r&CR&&(o=o.add(s)),s=s.double(),r>>=CR;return o},precomputeWindow(n,r){let{windows:o,windowSize:s}=RR(r,t),i=[],a=n,l=a;for(let c=0;c<o;c++){l=a,i.push(l);for(let u=1;u<s;u++)l=l.add(a),i.push(l);a=l.double()}return i},wNAF(n,r,o){let s=e.ZERO,i=e.BASE,a=RR(n,t);for(let l=0;l<a.windows;l++){let{nextN:c,offset:u,isZero:d,isNeg:p,isNegF:m,offsetF:g}=TM(o,l,a);o=c,d?i=i.add(ER(m,r[g])):s=s.add(ER(p,r[u]))}return{p:s,f:i}},wNAFUnsafe(n,r,o,s=e.ZERO){let i=RR(n,t);for(let a=0;a<i.windows&&o!==AM;a++){let{nextN:l,offset:c,isZero:u,isNeg:d}=TM(o,a,i);if(o=l,!u){let p=r[c];s=s.add(d?p.negate():p)}}return s},getPrecomputes(n,r,o){let s=IR.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&IR.set(r,o(s))),s},wNAFCached(n,r,o){let s=_R(n);return this.wNAF(s,this.getPrecomputes(s,n,o),r)},wNAFCachedUnsafe(n,r,o,s){let i=_R(n);return i===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(i,this.getPrecomputes(i,n,o),r,s)},setWindowSize(n,r){SM(r,t),PM.set(n,r),IR.delete(n)}}}function RM(e,t,n,r){D7(n,e),U7(r,t);let o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=$U(BigInt(o)),l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);let c=ol(l),u=new Array(Number(c)+1).fill(i),d=Math.floor((t.BITS-1)/l)*l,p=i;for(let m=d;m>=0;m-=l){u.fill(i);for(let f=0;f<s;f++){let y=r[f],w=Number(y>>BigInt(m)&c);u[w]=u[w].add(n[f])}let g=i;for(let f=u.length-1,y=i;f>0;f--)y=y.add(u[f]),g=g.add(y);if(p=p.add(g),m!==0)for(let f=0;f<l;f++)p=p.double()}return p}function NR(e){return AR(e.Fp),sl(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...SR(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}var AM,CR,IR,PM,IM=L(()=>{"use strict";Kb();Hu();AM=BigInt(0),CR=BigInt(1);IR=new WeakMap,PM=new WeakMap});function _M(e){e.lowS!==void 0&&Fu("lowS",e.lowS),e.prehash!==void 0&&Fu("prehash",e.prehash)}function B7(e){let t=NR(e);sl(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:n,Fp:r,a:o}=t;if(n){if(!r.eql(o,r.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function OR(e,t){return qu(nl(e,t))}function F7(e){let t=B7(e),{Fp:n}=t,r=vh(t.n,t.nBitLength),o=t.toBytes||((x,k,S)=>{let D=k.toAffine();return Jm(Uint8Array.from([4]),n.toBytes(D.x),n.toBytes(D.y))}),s=t.fromBytes||(x=>{let k=x.subarray(1),S=n.fromBytes(k.subarray(0,n.BYTES)),D=n.fromBytes(k.subarray(n.BYTES,2*n.BYTES));return{x:S,y:D}});function i(x){let{a:k,b:S}=t,D=n.sqr(x),q=n.mul(D,x);return n.add(n.add(q,n.mul(x,k)),S)}function a(x,k){let S=n.sqr(k),D=i(x);return n.eql(S,D)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let l=n.mul(n.pow(t.a,LR),M7),c=n.mul(n.sqr(t.b),BigInt(27));if(n.is0(n.add(l,c)))throw new Error("bad curve params: a or b");function u(x){return ub(x,an,t.n)}function d(x){let{allowedPrivateKeyLengths:k,nByteLength:S,wrapPrivateKey:D,n:q}=t;if(k&&typeof x!="bigint"){if(Mu(x)&&(x=qu(x)),typeof x!="string"||!k.includes(x.length))throw new Error("invalid private key");x=x.padStart(S*2,"0")}let V;try{V=typeof x=="bigint"?x:qs(or("private key",x,S))}catch{throw new Error("invalid private key, expected hex or "+S+" bytes, got "+typeof x)}return D&&(V=En(V,q)),rl("private key",V,an,q),V}function p(x){if(!(x instanceof f))throw new Error("ProjectivePoint expected")}let m=pE((x,k)=>{let{px:S,py:D,pz:q}=x;if(n.eql(q,n.ONE))return{x:S,y:D};let V=x.is0();k==null&&(k=V?n.ONE:n.inv(q));let Y=n.mul(S,k),ee=n.mul(D,k),ce=n.mul(q,k);if(V)return{x:n.ZERO,y:n.ZERO};if(!n.eql(ce,n.ONE))throw new Error("invZ was invalid");return{x:Y,y:ee}}),g=pE(x=>{if(x.is0()){if(t.allowInfinityPoint&&!n.is0(x.py))return;throw new Error("bad point: ZERO")}let{x:k,y:S}=x.toAffine();if(!n.isValid(k)||!n.isValid(S))throw new Error("bad point: x or y not FE");if(!a(k,S))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(k,S,D){if(k==null||!n.isValid(k))throw new Error("x required");if(S==null||!n.isValid(S)||n.is0(S))throw new Error("y required");if(D==null||!n.isValid(D))throw new Error("z required");this.px=k,this.py=S,this.pz=D,Object.freeze(this)}static fromAffine(k){let{x:S,y:D}=k||{};if(!k||!n.isValid(S)||!n.isValid(D))throw new Error("invalid affine point");if(k instanceof f)throw new Error("projective point not allowed");let q=V=>n.eql(V,n.ZERO);return q(S)&&q(D)?f.ZERO:new f(S,D,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(k){let S=TR(n,k.map(D=>D.pz));return k.map((D,q)=>D.toAffine(S[q])).map(f.fromAffine)}static fromHex(k){let S=f.fromAffine(s(or("pointHex",k)));return S.assertValidity(),S}static fromPrivateKey(k){return f.BASE.multiply(d(k))}static msm(k,S){return RM(f,r,k,S)}_setWindowSize(k){v.setWindowSize(this,k)}assertValidity(){g(this)}hasEvenY(){let{y:k}=this.toAffine();if(n.isOdd)return!n.isOdd(k);throw new Error("Field doesn't support isOdd")}equals(k){p(k);let{px:S,py:D,pz:q}=this,{px:V,py:Y,pz:ee}=k,ce=n.eql(n.mul(S,ee),n.mul(V,q)),ne=n.eql(n.mul(D,ee),n.mul(Y,q));return ce&&ne}negate(){return new f(this.px,n.neg(this.py),this.pz)}double(){let{a:k,b:S}=t,D=n.mul(S,LR),{px:q,py:V,pz:Y}=this,ee=n.ZERO,ce=n.ZERO,ne=n.ZERO,M=n.mul(q,q),W=n.mul(V,V),I=n.mul(Y,Y),N=n.mul(q,V);return N=n.add(N,N),ne=n.mul(q,Y),ne=n.add(ne,ne),ee=n.mul(k,ne),ce=n.mul(D,I),ce=n.add(ee,ce),ee=n.sub(W,ce),ce=n.add(W,ce),ce=n.mul(ee,ce),ee=n.mul(N,ee),ne=n.mul(D,ne),I=n.mul(k,I),N=n.sub(M,I),N=n.mul(k,N),N=n.add(N,ne),ne=n.add(M,M),M=n.add(ne,M),M=n.add(M,I),M=n.mul(M,N),ce=n.add(ce,M),I=n.mul(V,Y),I=n.add(I,I),M=n.mul(I,N),ee=n.sub(ee,M),ne=n.mul(I,W),ne=n.add(ne,ne),ne=n.add(ne,ne),new f(ee,ce,ne)}add(k){p(k);let{px:S,py:D,pz:q}=this,{px:V,py:Y,pz:ee}=k,ce=n.ZERO,ne=n.ZERO,M=n.ZERO,W=t.a,I=n.mul(t.b,LR),N=n.mul(S,V),G=n.mul(D,Y),re=n.mul(q,ee),Z=n.add(S,D),Q=n.add(V,Y);Z=n.mul(Z,Q),Q=n.add(N,G),Z=n.sub(Z,Q),Q=n.add(S,q);let ie=n.add(V,ee);return Q=n.mul(Q,ie),ie=n.add(N,re),Q=n.sub(Q,ie),ie=n.add(D,q),ce=n.add(Y,ee),ie=n.mul(ie,ce),ce=n.add(G,re),ie=n.sub(ie,ce),M=n.mul(W,Q),ce=n.mul(I,re),M=n.add(ce,M),ce=n.sub(G,M),M=n.add(G,M),ne=n.mul(ce,M),G=n.add(N,N),G=n.add(G,N),re=n.mul(W,re),Q=n.mul(I,Q),G=n.add(G,re),re=n.sub(N,re),re=n.mul(W,re),Q=n.add(Q,re),N=n.mul(G,Q),ne=n.add(ne,N),N=n.mul(ie,Q),ce=n.mul(Z,ce),ce=n.sub(ce,N),N=n.mul(Z,G),M=n.mul(ie,M),M=n.add(M,N),new f(ce,ne,M)}subtract(k){return this.add(k.negate())}is0(){return this.equals(f.ZERO)}wNAF(k){return v.wNAFCached(this,k,f.normalizeZ)}multiplyUnsafe(k){let{endo:S,n:D}=t;rl("scalar",k,Gs,D);let q=f.ZERO;if(k===Gs)return q;if(this.is0()||k===an)return this;if(!S||v.hasPrecomputes(this))return v.wNAFCachedUnsafe(this,k,f.normalizeZ);let{k1neg:V,k1:Y,k2neg:ee,k2:ce}=S.splitScalar(k),ne=q,M=q,W=this;for(;Y>Gs||ce>Gs;)Y&an&&(ne=ne.add(W)),ce&an&&(M=M.add(W)),W=W.double(),Y>>=an,ce>>=an;return V&&(ne=ne.negate()),ee&&(M=M.negate()),M=new f(n.mul(M.px,S.beta),M.py,M.pz),ne.add(M)}multiply(k){let{endo:S,n:D}=t;rl("scalar",k,an,D);let q,V;if(S){let{k1neg:Y,k1:ee,k2neg:ce,k2:ne}=S.splitScalar(k),{p:M,f:W}=this.wNAF(ee),{p:I,f:N}=this.wNAF(ne);M=v.constTimeNegate(Y,M),I=v.constTimeNegate(ce,I),I=new f(n.mul(I.px,S.beta),I.py,I.pz),q=M.add(I),V=W.add(N)}else{let{p:Y,f:ee}=this.wNAF(k);q=Y,V=ee}return f.normalizeZ([q,V])[0]}multiplyAndAddUnsafe(k,S,D){let q=f.BASE,V=(ee,ce)=>ce===Gs||ce===an||!ee.equals(q)?ee.multiplyUnsafe(ce):ee.multiply(ce),Y=V(this,S).add(V(k,D));return Y.is0()?void 0:Y}toAffine(k){return m(this,k)}isTorsionFree(){let{h:k,isTorsionFree:S}=t;if(k===an)return!0;if(S)return S(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:k,clearCofactor:S}=t;return k===an?this:S?S(f,this):this.multiplyUnsafe(t.h)}toRawBytes(k=!0){return Fu("isCompressed",k),this.assertValidity(),o(f,this,k)}toHex(k=!0){return Fu("isCompressed",k),qu(this.toRawBytes(k))}}f.BASE=new f(t.Gx,t.Gy,n.ONE),f.ZERO=new f(n.ZERO,n.ONE,n.ZERO);let{endo:y,nBitLength:w}=t,v=EM(f,y?Math.ceil(w/2):w);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:d,weierstrassEquation:i,isWithinCurveOrder:u}}function q7(e){let t=NR(e);return sl(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function CM(e){let t=q7(e),{Fp:n,n:r,nByteLength:o,nBitLength:s}=t,i=n.BYTES+1,a=2*n.BYTES+1;function l(I){return En(I,r)}function c(I){return Gb(I,r)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:p,isWithinCurveOrder:m}=F7({...t,toBytes(I,N,G){let re=N.toAffine(),Z=n.toBytes(re.x),Q=Jm;return Fu("isCompressed",G),G?Q(Uint8Array.from([N.hasEvenY()?2:3]),Z):Q(Uint8Array.from([4]),Z,n.toBytes(re.y))},fromBytes(I){let N=I.length,G=I[0],re=I.subarray(1);if(N===i&&(G===2||G===3)){let Z=qs(re);if(!ub(Z,an,n.ORDER))throw new Error("Point is not on curve");let Q=p(Z),ie;try{ie=n.sqrt(Q)}catch(ke){let be=ke instanceof Error?": "+ke.message:"";throw new Error("Point is not on curve"+be)}let me=(ie&an)===an;return(G&1)===1!==me&&(ie=n.neg(ie)),{x:Z,y:ie}}else if(N===a&&G===4){let Z=n.fromBytes(re.subarray(0,n.BYTES)),Q=n.fromBytes(re.subarray(n.BYTES,2*n.BYTES));return{x:Z,y:Q}}else{let Z=i,Q=a;throw new Error("invalid Point, expected length of "+Z+", or uncompressed "+Q+", got "+N)}}});function g(I){let N=r>>an;return I>N}function f(I){return g(I)?l(-I):I}let y=(I,N,G)=>qs(I.slice(N,G));class w{constructor(N,G,re){rl("r",N,an,r),rl("s",G,an,r),this.r=N,this.s=G,re!=null&&(this.recovery=re),Object.freeze(this)}static fromCompact(N){let G=o;return N=or("compactSignature",N,G*2),new w(y(N,0,G),y(N,G,2*G))}static fromDER(N){let{r:G,s:re}=Ws.toSig(or("DER",N));return new w(G,re)}assertValidity(){}addRecoveryBit(N){return new w(this.r,this.s,N)}recoverPublicKey(N){let{r:G,s:re,recovery:Z}=this,Q=q(or("msgHash",N));if(Z==null||![0,1,2,3].includes(Z))throw new Error("recovery id invalid");let ie=Z===2||Z===3?G+t.n:G;if(ie>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");let me=(Z&1)===0?"02":"03",Ne=u.fromHex(me+OR(ie,n.BYTES)),ke=c(ie),be=l(-Q*ke),qe=l(re*ke),ze=u.BASE.multiplyAndAddUnsafe(Ne,be,qe);if(!ze)throw new Error("point at infinify");return ze.assertValidity(),ze}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,l(-this.s),this.recovery):this}toDERRawBytes(){return Xm(this.toDERHex())}toDERHex(){return Ws.hexFromSig(this)}toCompactRawBytes(){return Xm(this.toCompactHex())}toCompactHex(){let N=o;return OR(this.r,N)+OR(this.s,N)}}let v={isValidPrivateKey(I){try{return d(I),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let I=PR(t.n);return xM(t.randomBytes(I),t.n)},precompute(I=8,N=u.BASE){return N._setWindowSize(I),N.multiply(BigInt(3)),N}};function x(I,N=!0){return u.fromPrivateKey(I).toRawBytes(N)}function k(I){if(typeof I=="bigint")return!1;if(I instanceof u)return!0;let G=or("key",I).length,re=n.BYTES,Z=re+1,Q=2*re+1;if(!(t.allowedPrivateKeyLengths||o===Z))return G===Z||G===Q}function S(I,N,G=!0){if(k(I)===!0)throw new Error("first arg must be private key");if(k(N)===!1)throw new Error("second arg must be public key");return u.fromHex(N).multiply(d(I)).toRawBytes(G)}let D=t.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let N=qs(I),G=I.length*8-s;return G>0?N>>BigInt(G):N},q=t.bits2int_modN||function(I){return l(D(I))},V=ol(s);function Y(I){return rl("num < 2^"+s,I,Gs,V),nl(I,o)}function ee(I,N,G=ce){if(["recovered","canonical"].some(He=>He in G))throw new Error("sign() legacy options not supported");let{hash:re,randomBytes:Z}=t,{lowS:Q,prehash:ie,extraEntropy:me}=G;Q==null&&(Q=!0),I=or("msgHash",I),_M(G),ie&&(I=or("prehashed msgHash",re(I)));let Ne=q(I),ke=d(N),be=[Y(ke),Y(Ne)];if(me!=null&&me!==!1){let He=me===!0?Z(n.BYTES):me;be.push(or("extraEntropy",He))}let qe=Jm(...be),ze=Ne;function ut(He){let it=D(He);if(!m(it))return;let je=c(it),Ss=u.BASE.multiply(it).toAffine(),Br=l(Ss.x);if(Br===Gs)return;let _a=l(je*l(ze+Br*ke));if(_a===Gs)return;let We=(Ss.x===Br?0:2)|Number(Ss.y&an),vc=_a;return Q&&g(_a)&&(vc=f(_a),We^=1),new w(Br,vc,We)}return{seed:qe,k2sig:ut}}let ce={lowS:t.lowS,prehash:!1},ne={lowS:t.lowS,prehash:!1};function M(I,N,G=ce){let{seed:re,k2sig:Z}=ee(I,N,G),Q=t;return VU(Q.hash.outputLen,Q.nByteLength,Q.hmac)(re,Z)}u.BASE._setWindowSize(8);function W(I,N,G,re=ne){let Z=I;N=or("msgHash",N),G=or("publicKey",G);let{lowS:Q,prehash:ie,format:me}=re;if(_M(re),"strict"in re)throw new Error("options.strict was renamed to lowS");if(me!==void 0&&me!=="compact"&&me!=="der")throw new Error("format must be compact or der");let Ne=typeof Z=="string"||Mu(Z),ke=!Ne&&!me&&typeof Z=="object"&&Z!==null&&typeof Z.r=="bigint"&&typeof Z.s=="bigint";if(!Ne&&!ke)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let be,qe;try{if(ke&&(be=new w(Z.r,Z.s)),Ne){try{me!=="compact"&&(be=w.fromDER(Z))}catch(We){if(!(We instanceof Ws.Err))throw We}!be&&me!=="der"&&(be=w.fromCompact(Z))}qe=u.fromHex(G)}catch{return!1}if(!be||Q&&be.hasHighS())return!1;ie&&(N=t.hash(N));let{r:ze,s:ut}=be,He=q(N),it=c(ut),je=l(He*it),Ss=l(ze*it),Br=u.BASE.multiplyAndAddUnsafe(qe,je,Ss)?.toAffine();return Br?l(Br.x)===ze:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:S,sign:M,verify:W,ProjectivePoint:u,Signature:w,utils:v}}var DR,Ws,Gs,an,gIe,LR,M7,NM=L(()=>{"use strict";IM();Kb();Hu();DR=class extends Error{constructor(t=""){super(t)}},Ws={Err:DR,_tlv:{encode:(e,t)=>{let{Err:n}=Ws;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");let r=t.length/2,o=Qm(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let s=r>127?Qm(o.length/2|128):"";return Qm(e)+s+o+t},decode(e,t){let{Err:n}=Ws,r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");let o=t[r++],s=!!(o&128),i=0;if(!s)i=o;else{let l=o&127;if(!l)throw new n("tlv.decode(long): indefinite length not supported");if(l>4)throw new n("tlv.decode(long): byte length is too big");let c=t.subarray(r,r+l);if(c.length!==l)throw new n("tlv.decode: length bytes not complete");if(c[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let u of c)i=i<<8|u;if(r+=l,i<128)throw new n("tlv.decode(long): not minimal encoding")}let a=t.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+i)}}},_int:{encode(e){let{Err:t}=Ws;if(e<Gs)throw new t("integer: negative integers are not allowed");let n=Qm(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){let{Err:t}=Ws;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 qs(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=Ws,o=or("signature",e),{v:s,l:i}=r.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,s),{v:c,l:u}=r.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(c)}},hexFromSig(e){let{_tlv:t,_int:n}=Ws,r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),s=r+o;return t.encode(48,s)}};Gs=BigInt(0),an=BigInt(1),gIe=BigInt(2),LR=BigInt(3),M7=BigInt(4)});function H7(e){return{hash:e,hmac:(t,...n)=>(0,OM.hmac)(e,t,(0,Yb.concatBytes)(...n)),randomBytes:Yb.randomBytes}}function LM(e,t){let n=r=>CM({...e,...H7(r)});return{...n(t),create:n}}var OM,Yb,DM=L(()=>{"use strict";OM=require("@noble/hashes/hmac"),Yb=require("@noble/hashes/utils");NM();});function z7(e){let t=FM,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),l=BigInt(88),c=e*e*e%t,u=c*c*e%t,d=xr(u,n,t)*u%t,p=xr(d,n,t)*u%t,m=xr(p,UR,t)*c%t,g=xr(m,o,t)*m%t,f=xr(g,s,t)*g%t,y=xr(f,a,t)*f%t,w=xr(y,l,t)*y%t,v=xr(w,a,t)*f%t,x=xr(v,n,t)*u%t,k=xr(x,i,t)*g%t,S=xr(k,r,t)*c%t,D=xr(S,UR,t);if(!BR.eql(BR.sqr(D),e))throw new Error("Cannot find square root");return D}var MM,$7,FM,UM,V7,j7,UR,BM,BR,Ar,MR=L(()=>{"use strict";MM=require("@noble/hashes/sha2"),$7=require("@noble/hashes/utils");DM();Kb();FM=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),UM=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),V7=BigInt(0),j7=BigInt(1),UR=BigInt(2),BM=(e,t)=>(e+t/UR)/t;BR=vh(FM,void 0,void 0,{sqrt:z7}),Ar=LM({a:V7,b:BigInt(7),Fp:BR,n:UM,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=UM,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-j7*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,i=BigInt("0x100000000000000000000000000000000"),a=BM(s*e,t),l=BM(-r*e,t),c=En(e-a*n-l*o,t),u=En(-a*r-l*s,t),d=c>i,p=u>i;if(d&&(c=t-c),p&&(u=t-u),c>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:c,k2neg:p,k2:u}}}},MM.sha256)});var qM,HM=L(()=>{"use strict";qM=!1});function $M(e,t,n={}){let{validate:r}=n;for(let o=0;;o++){let s=SE(e,Wu(t,Gu(o,{size:4})),{as:"Bytes"});if(!r||r(s))return s;s.fill(0)}}var VM=L(()=>{"use strict";Xt();ul()});function jM(e,t={}){let{path:n="m/44'/60'/0'/0/0",passphrase:r}=t,o=Wb.fromMasterSeed(K7(e,{passphrase:r})).derive(n).privateKey;return t.as==="Bytes"?o:Ke(o)}function K7(e,t={}){return ZE(e,t.passphrase)}var zM=L(()=>{"use strict";hM();eR();Tn()});var ad={};fr(ad,{InvalidSeedSizeError:()=>Qb,createKeyPair:()=>Q7,fromMnemonic:()=>X7,fromSeed:()=>J7,getPublicKey:()=>GM,getSharedSecret:()=>Z7,noble:()=>WM,randomPrivateKey:()=>KM,recoverAddress:()=>YM,recoverPublicKey:()=>QM,sign:()=>eQ,verify:()=>tQ});function Q7(e={}){let{as:t="Hex"}=e,n=KM({as:t}),r=GM({privateKey:n});return{privateKey:n,publicKey:r}}function X7(e,t={}){let{as:n="Hex",passphrase:r,path:o}=t;return jM(e,{as:n,passphrase:r,path:o})}function J7(e,t={}){let{as:n="Hex"}=t,r=Fn(e);if(r.length<32)throw new Qb({size:r.length});let o=$M(r,nQ,{validate:WM.utils.isValidPrivateKey});if(n==="Hex"){let s=Ke(o);return o.fill(0),s}return o}function GM(e){let{privateKey:t}=e,n=Ar.ProjectivePoint.fromPrivateKey(uo(t).slice(2));return CE(n)}function Z7(e){let{as:t="Hex",privateKey:n,publicKey:r}=e,i=Ar.ProjectivePoint.fromHex(lh(r).slice(2)).multiply(Ar.utils.normPrivateKeyToScalar(uo(n).slice(2))).toRawBytes(!0);return t==="Hex"?Ke(i):i}function KM(e={}){let{as:t="Hex"}=e,n=Ar.utils.randomPrivateKey();return t==="Hex"?Ke(n):n}function YM(e){return OE(QM(e))}function QM(e){let{payload:t,signature:n}=e,{r,s:o,yParity:s}=n,a=new Ar.Signature(BigInt(r),BigInt(o)).addRecoveryBit(s).recoverPublicKey(uo(t).substring(2));return CE(a)}function eQ(e){let{extraEntropy:t=qM,hash:n,payload:r,privateKey:o}=e,{r:s,s:i,recovery:a}=Ar.sign(Fn(r),Fn(o),{extraEntropy:typeof t=="boolean"?t:uo(t).slice(2),lowS:!0,...n?{prehash:!0}:{}});return{r:s,s:i,yParity:a}}function tQ(e){let{hash:t,payload:n}=e;return e.address?LE(e.address,YM({payload:n,signature:e.signature})):Ar.verify(e.signature,Fn(n),aB(e.publicKey),...t?[{prehash:!0,lowS:!0}]:[])}var WM,Qb,nQ,XM=L(()=>{"use strict";MR();Wi();Xt();An();Tn();HM();VM();zM();xb();WM=Ar;Qb=class extends le{constructor(t){super(`Seed must contain at least 32 bytes. Received ${t.size} bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Secp256k1.InvalidSeedSizeError"})}},nQ=qn("ox.secp256k1.fromSeed.v1")});var JM=L(()=>{"use strict"});var ZM=L(()=>{"use strict";eR()});var IIe,e2=L(()=>{"use strict";Xt();IIe=qn("ox.aesGcm.fromSeed.v1")});function iQ(e,t){let{as:n}=t,r=n2(e),o=Cb(new Uint8Array(r.length));return r.encode(o),n==="Hex"?Ke(o.bytes):o.bytes}function t2(e,t={}){let{as:n="Bytes"}=t;return iQ(e,{as:n})}function n2(e){return Array.isArray(e)?aQ(e.map(t=>n2(t))):lQ(e)}function aQ(e){let t=e.reduce((o,s)=>o+s.length,0),n=r2(t);return{length:t<=55?1+t:1+n+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+n),n===1?o.pushUint8(t):n===2?o.pushUint16(t):n===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:s}of e)s(o)}}}function lQ(e){let t=typeof e=="string"?yt(e):e,n=r2(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+n+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+n),n===1?o.pushUint8(t.length):n===2?o.pushUint16(t.length):n===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function r2(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;throw new le("Length is too large.")}var FR=L(()=>{"use strict";Xt();An();Tn();zE()});var rw={};fr(rw,{InvalidRError:()=>Jb,InvalidSError:()=>Zb,InvalidSerializedSizeError:()=>Xb,InvalidVError:()=>ew,InvalidYParityError:()=>kl,MissingPropertiesError:()=>ld,assert:()=>tw,extract:()=>cQ,from:()=>HR,fromBytes:()=>s2,fromDerBytes:()=>uQ,fromDerHex:()=>i2,fromHex:()=>qR,fromLegacy:()=>a2,fromRpc:()=>l2,fromTuple:()=>dQ,toBytes:()=>pQ,toDerBytes:()=>mQ,toDerHex:()=>hQ,toHex:()=>c2,toLegacy:()=>fQ,toRpc:()=>gQ,toTuple:()=>yQ,vToYParity:()=>nw,validate:()=>bQ,yParityToV:()=>$R});function tw(e,t={}){let{recovered:n}=t;if(typeof e.r>"u")throw new ld({signature:e});if(typeof e.s>"u")throw new ld({signature:e});if(n&&typeof e.yParity>"u")throw new ld({signature:e});if(e.r<0n||e.r>FE)throw new Jb({value:e.r});if(e.s<0n||e.s>FE)throw new Zb({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new kl({value:e.yParity})}function s2(e){return qR(Ke(e))}function qR(e){if(e.length!==130&&e.length!==132)throw new Xb({signature:e});let t=BigInt($t(e,0,32)),n=BigInt($t(e,32,64)),r=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return nw(o)}catch{throw new kl({value:o})}})();return typeof r>"u"?{r:t,s:n}:{r:t,s:n,yParity:r}}function cQ(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return HR(e)}function HR(e){let t=typeof e=="string"?qR(e):e instanceof Uint8Array?s2(e):typeof e.r=="string"?l2(e):e.v?a2(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return tw(t),t}function uQ(e){return i2(Ke(e))}function i2(e){let{r:t,s:n}=Ar.Signature.fromDER(uo(e).slice(2));return{r:t,s:n}}function a2(e){return{r:e.r,s:e.s,yParity:nw(e.v)}}function l2(e){let t=(()=>{let n=e.v?Number(e.v):void 0,r=e.yParity?Number(e.yParity):void 0;if(typeof n=="number"&&typeof r!="number"&&(r=nw(n)),typeof r!="number")throw new kl({value:e.yParity});return r})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function dQ(e){let[t,n,r]=e;return HR({r:n==="0x"?0n:BigInt(n),s:r==="0x"?0n:BigInt(r),yParity:t==="0x"?0:Number(t)})}function pQ(e){return yt(c2(e))}function c2(e){tw(e);let t=e.r,n=e.s;return Jt(pt(t,{size:32}),pt(n,{size:32}),typeof e.yParity=="number"?pt($R(e.yParity),{size:1}):"0x")}function mQ(e){return new Ar.Signature(e.r,e.s).toDERRawBytes()}function hQ(e){return`0x${new Ar.Signature(e.r,e.s).toDERHex()}`}function fQ(e){return{r:e.r,s:e.s,v:$R(e.yParity)}}function gQ(e){let{r:t,s:n,yParity:r}=e;return{r:pt(t,{size:32}),s:pt(n,{size:32}),yParity:r===0?"0x0":"0x1"}}function yQ(e){let{r:t,s:n,yParity:r}=e;return[r?"0x01":"0x",t===0n?"0x":ih(pt(t)),n===0n?"0x":ih(pt(n))]}function bQ(e,t={}){try{return tw(e,t),!0}catch{return!1}}function nw(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 ew({value:e})}function $R(e){if(e===0)return 27;if(e===1)return 28;throw new kl({value:e})}var Xb,ld,Jb,Zb,kl,ew,u2=L(()=>{"use strict";MR();Xt();An();Tn();al();Zu();Xb=class extends le{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${nt(uo(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},ld=class extends le{constructor({signature:t}){super(`Signature \`${co(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},Jb=class extends le{constructor({value:t}){super(`Value \`${t}\` 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"})}},Zb=class extends le{constructor({value:t}){super(`Value \`${t}\` 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"})}},kl=class extends le{constructor({value:t}){super(`Value \`${t}\` 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"})}},ew=class extends le{constructor({value:t}){super(`Value \`${t}\` 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"})}}});var d2=L(()=>{"use strict"});var p2=L(()=>{"use strict"});var m2=L(()=>{"use strict"});var CIe,NIe,h2=L(()=>{"use strict";CIe=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),NIe={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var f2=L(()=>{"use strict"});var TQ,g2=L(()=>{"use strict";TQ=require("@noble/hashes/blake3")});var y2=L(()=>{"use strict"});var b2,EQ,w2,RQ,OIe,v2=L(()=>{"use strict";b2=6,EQ=32,w2=4096,RQ=EQ*w2,OIe=RQ*b2-1-1*w2*b2});var k2=L(()=>{"use strict"});var x2=L(()=>{"use strict"});var A2=L(()=>{"use strict"});var T2=L(()=>{"use strict"});var S2=L(()=>{"use strict"});var P2=L(()=>{"use strict"});var E2=L(()=>{"use strict"});var R2=L(()=>{"use strict"});var I2=L(()=>{"use strict"});function Jo(e){if(typeof e>"u")return{length:1,encode:t=>t.pushUint8(247)};if(e===null)return{length:1,encode:t=>t.pushUint8(246)};if(typeof e=="boolean")return{length:1,encode:t=>t.pushUint8(e?245:244)};if(typeof e=="number")return Jo.number(e);if(typeof e=="bigint")throw new GR;if(typeof e=="string")return Jo.string(e);if(Array.isArray(e))return Jo.array(e);if(e instanceof Uint8Array)return Jo.byteString(e);if(e instanceof ArrayBuffer)return Jo.byteString(new Uint8Array(e));if(ArrayBuffer.isView(e))return Jo.byteString(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(e instanceof Map)return Jo.map(e);if(typeof e=="object")return Jo.object(e);throw new KR({token:String(e)})}function Ks(e){let t=e.readUint8(),n=t>>5,r=t&31;switch(n){case 0:return Ks.readUnsignedInteger(e,r);case 1:return Ks.readNegativeInteger(e,r);case 2:return Ks.readByteString(e,r);case 3:return Ks.readTextString(e,r);case 4:return Ks.readArray(e,r);case 5:return Ks.readMap(e,r);case 6:throw new zR({tag:r});case 7:return Ks.readSimpleOrFloat(e,r);default:throw new VR({majorType:n})}}var VR,ow,jR,zR,sw,WR,GR,KR,iw,YR,QR,aw,XR,_2=L(()=>{"use strict";Xt();An();VR=class extends le{constructor({majorType:t}){super(`Invalid CBOR major type: ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.InvalidMajorTypeError"})}},ow=class extends le{constructor({additionalInfo:t}){super(`Invalid CBOR additional info: ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.InvalidAdditionalInfoError"})}},jR=class extends le{constructor(){super("64-bit integers are not supported in CBOR decoding."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.Unsupported64BitIntegerError"})}},zR=class extends le{constructor({tag:t}){super(`CBOR tagged data (tag ${t}) is not yet supported.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.UnsupportedTagError"})}},sw=class extends le{constructor({type:t}){super(`Invalid chunk type in indefinite-length ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.InvalidIndefiniteLengthChunkError"})}},WR=class extends le{constructor({value:t}){super(`Invalid CBOR simple value: ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.InvalidSimpleValueError"})}},GR=class extends le{constructor(){super("BigInt values are not supported in CBOR encoding."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.UnsupportedBigIntError"})}},KR=class extends le{constructor({token:t}){super(`Unexpected token: ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.UnexpectedTokenError"})}},iw=class extends le{constructor({number:t}){super(`Number exceeds maximum safe integer (${Number.MAX_SAFE_INTEGER}): ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.NumberTooLargeError"})}},YR=class extends le{constructor({size:t}){super(`String length exceeds maximum (4294967295): ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.StringTooLargeError"})}},QR=class extends le{constructor({size:t}){super(`Array length exceeds maximum (4294967295): ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.ArrayTooLargeError"})}},aw=class extends le{constructor({size:t}){super(`Object size exceeds maximum (4294967295): ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.ObjectTooLargeError"})}},XR=class extends le{constructor({size:t}){super(`Byte string length exceeds maximum (4294967295): ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.ByteStringTooLargeError"})}};(function(e){function t(a){if(!Number.isSafeInteger(a)){let c=Math.fround(a);return Number.isNaN(a)||a===c?{length:5,encode(u){u.pushUint8(250),u.dataView.setFloat32(u.position,a,!1),u.position+=4}}:{length:9,encode(u){u.pushUint8(251),u.dataView.setFloat64(u.position,a,!1),u.position+=8}}}if(a>=0){if(a<=23)return{length:1,encode:c=>c.pushUint8(a)};if(a<=255)return{length:2,encode:c=>{c.pushUint8(24),c.pushUint8(a)}};if(a<=65535)return{length:3,encode:c=>{c.pushUint8(25),c.pushUint16(a)}};if(a<=4294967295)return{length:5,encode:c=>{c.pushUint8(26),c.pushUint32(a)}};throw new iw({number:a.toString(10)})}let l=-1-a;if(a>=-24)return{length:1,encode:c=>c.pushUint8(32+l)};if(l<=255)return{length:2,encode:c=>{c.pushUint8(56),c.pushUint8(l)}};if(l<=65535)return{length:3,encode:c=>{c.pushUint8(57),c.pushUint16(l)}};if(l<=4294967295)return{length:5,encode:c=>{c.pushUint8(58),c.pushUint32(l)}};throw new iw({number:a.toString(10)})}e.number=t;function n(a){let l=qn(a),c=l.length;if(c<=23)return{length:1+c,encode(u){u.pushUint8(96+c),c>0&&u.pushBytes(l)}};if(c<=255)return{length:2+c,encode(u){u.pushUint8(120),u.pushUint8(c),u.pushBytes(l)}};if(c<=65535)return{length:3+c,encode(u){u.pushUint8(121),u.pushUint16(c),u.pushBytes(l)}};if(c<=4294967295)return{length:5+c,encode(u){u.pushUint8(122),u.pushUint32(c),u.pushBytes(l)}};throw new YR({size:c})}e.string=n;function r(a){let l=a.map(d=>e(d)),c=l.reduce((d,p)=>d+p.length,0),u=a.length;if(u<=23)return{length:1+c,encode(d){d.pushUint8(128+u);for(let p of l)p.encode(d)}};if(u<=255)return{length:2+c,encode(d){d.pushUint8(152),d.pushUint8(u);for(let p of l)p.encode(d)}};if(u<=65535)return{length:3+c,encode(d){d.pushUint8(153),d.pushUint16(u);for(let p of l)p.encode(d)}};if(u<=4294967295)return{length:5+c,encode(d){d.pushUint8(154),d.pushUint32(u);for(let p of l)p.encode(d)}};throw new QR({size:u})}e.array=r;function o(a){let l=a.byteLength;if(l<=23)return{length:1+l,encode(c){c.pushUint8(64+l),c.pushBytes(a)}};if(l<=255)return{length:2+l,encode(c){c.pushUint8(88),c.pushUint8(l),c.pushBytes(a)}};if(l<=65535)return{length:3+l,encode(c){c.pushUint8(89),c.pushUint16(l),c.pushBytes(a)}};if(l<=4294967295)return{length:5+l,encode(c){c.pushUint8(90),c.pushUint32(l),c.pushBytes(a)}};throw new XR({size:l})}e.byteString=o;function s(a){let l=Object.keys(a),c=l.map(p=>({key:e(p),value:e(a[p])})),u=c.reduce((p,m)=>p+m.key.length+m.value.length,0),d=l.length;if(d<=23)return{length:1+u,encode(p){p.pushUint8(160+d);for(let m of c)m.key.encode(p),m.value.encode(p)}};if(d<=255)return{length:2+u,encode(p){p.pushUint8(184),p.pushUint8(d);for(let m of c)m.key.encode(p),m.value.encode(p)}};if(d<=65535)return{length:3+u,encode(p){p.pushUint8(185),p.pushUint16(d);for(let m of c)m.key.encode(p),m.value.encode(p)}};if(d<=4294967295)return{length:5+u,encode(p){p.pushUint8(186),p.pushUint32(d);for(let m of c)m.key.encode(p),m.value.encode(p)}};throw new aw({size:d})}e.object=s;function i(a){let l=[];for(let[d,p]of a)l.push({key:e(d),value:e(p)});let c=l.reduce((d,p)=>d+p.key.length+p.value.length,0),u=a.size;if(u<=23)return{length:1+c,encode(d){d.pushUint8(160+u);for(let p of l)p.key.encode(d),p.value.encode(d)}};if(u<=255)return{length:2+c,encode(d){d.pushUint8(184),d.pushUint8(u);for(let p of l)p.key.encode(d),p.value.encode(d)}};if(u<=65535)return{length:3+c,encode(d){d.pushUint8(185),d.pushUint16(u);for(let p of l)p.key.encode(d),p.value.encode(d)}};if(u<=4294967295)return{length:5+c,encode(d){d.pushUint8(186),d.pushUint32(u);for(let p of l)p.key.encode(d),p.value.encode(d)}};throw new aw({size:u})}e.map=i})(Jo||(Jo={}));(function(e){function t(u,d){if(d<24)return d;if(d===24)return u.readUint8();if(d===25)return u.readUint16();if(d===26)return u.readUint32();throw d===27?new jR:new ow({additionalInfo:d})}function n(u,d){return t(u,d)}e.readUnsignedInteger=n;function r(u,d){return-1-t(u,d)}e.readNegativeInteger=r;function o(u,d){if(d===31){let m=[],g=0;for(;;){if(u.inspectUint8()===255){u.readUint8();break}let v=e(u);if(!(v instanceof Uint8Array))throw new sw({type:"byte string"});m.push(v),g+=v.length}let f=new Uint8Array(g),y=0;for(let w of m)f.set(w,y),y+=w.length;return f}let p=t(u,d);return u.readBytes(p)}e.readByteString=o;function s(u,d){if(d===31){let g=[];for(;;){if(u.inspectUint8()===255){u.readUint8();break}let y=e(u);if(typeof y!="string")throw new sw({type:"text string"});g.push(y)}return g.join("")}let p=t(u,d),m=u.readBytes(p);return ah(m)}e.readTextString=s;function i(u,d){if(d===31){let g=[];for(;;){if(u.inspectUint8()===255){u.readUint8();break}g.push(e(u))}return g}let p=t(u,d),m=[];for(let g=0;g<p;g++)m.push(e(u));return m}e.readArray=i;function a(u,d){if(d===31){let g={};for(;;){if(u.inspectUint8()===255){u.readUint8();break}let y=e(u),w=typeof y=="string"?y:String(y),v=e(u);g[w]=v}return g}let p=t(u,d),m={};for(let g=0;g<p;g++){let f=e(u),y=typeof f=="string"?f:String(f),w=e(u);m[y]=w}return m}e.readMap=a;function l(u,d){if(d===20)return!1;if(d===21)return!0;if(d===22)return null;if(d!==23){if(d===25){let p=u.readUint16();return c(p)}if(d===26){let p=u.dataView.getFloat32(u.position,!1);return u.position+=4,p}if(d===27){let p=u.dataView.getFloat64(u.position,!1);return u.position+=8,p}if(d===24){let p=u.readUint8();if(p<32)throw new WR({value:p});return}throw new ow({additionalInfo:d})}}e.readSimpleOrFloat=l;function c(u){let d=u>>15&1,p=u>>10&31,m=u&1023;if(p===0){if(m===0)return d?-0:0;let f=2**-14*(m/1024);return d?-f:f}if(p===31)return m===0?d?-1/0:1/0:NaN;let g=2**(p-15)*(1+m/1024);return d?-g:g}})(Ks||(Ks={}))});var C2=L(()=>{"use strict"});var ho={};fr(ho,{from:()=>HQ,fromCreate:()=>N2,fromCreate2:()=>O2});function HQ(e){return e.salt?O2(e):N2(e)}function N2(e){let t=yt(pl(e.from)),n=Gu(e.nonce);return n[0]===0&&(n=new Uint8Array([])),pl(`0x${sn(t2([t,n],{as:"Hex"})).slice(26)}`)}function O2(e){let t=yt(pl(e.from)),n=yb(Ku(e.salt)?e.salt:yt(e.salt),32),r="bytecodeHash"in e?Ku(e.bytecodeHash)?e.bytecodeHash:yt(e.bytecodeHash):sn(e.bytecode,{as:"Bytes"});return pl($t(sn(Wu(yt("0xff"),t,n,r),{as:"Hex"}),12))}var L2=L(()=>{"use strict";Wi();Xt();ul();Tn();FR()});var D2=L(()=>{"use strict"});var LIe,U2=L(()=>{"use strict";Xt();LIe=qn("ox.ed25519.fromSeed.v1")});var jQ,zQ,WQ,GQ,B2,M2,F2,KQ,YQ,DIe,UIe,BIe,MIe,q2=L(()=>{"use strict";jQ=44032,zQ=4352,WQ=4449,GQ=4519,B2=19,M2=21,F2=28,KQ=M2*F2,YQ=B2*KQ,DIe=jQ+YQ,UIe=zQ+B2,BIe=WQ+M2,MIe=GQ+F2});var H2=L(()=>{"use strict";q2()});var $2=L(()=>{"use strict"});var V2=L(()=>{"use strict"});var j2=L(()=>{"use strict"});var z2=L(()=>{"use strict"});var W2,G2,eX,K2=L(()=>{"use strict";W2=require("@noble/hashes/pbkdf2"),G2=require("@noble/hashes/scrypt"),eX=require("@noble/hashes/sha2")});var Y2=L(()=>{"use strict"});var $Ie,Q2=L(()=>{"use strict";Xt();$Ie=qn("ox.p256.fromSeed.v1")});var X2=L(()=>{"use strict"});var Z2=jz((VIe,JR)=>{"use strict";var sX=Object.prototype.hasOwnProperty,Vn="~";function kh(){}Object.create&&(kh.prototype=Object.create(null),new kh().__proto__||(Vn=!1));function iX(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function J2(e,t,n,r,o){if(typeof n!="function")throw new TypeError("The listener must be a function");var s=new iX(n,r||e,o),i=Vn?Vn+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],s]:e._events[i].push(s):(e._events[i]=s,e._eventsCount++),e}function lw(e,t){--e._eventsCount===0?e._events=new kh:delete e._events[t]}function In(){this._events=new kh,this._eventsCount=0}In.prototype.eventNames=function(){var t=[],n,r;if(this._eventsCount===0)return t;for(r in n=this._events)sX.call(n,r)&&t.push(Vn?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(n)):t};In.prototype.listeners=function(t){var n=Vn?Vn+t:t,r=this._events[n];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,i=new Array(s);o<s;o++)i[o]=r[o].fn;return i};In.prototype.listenerCount=function(t){var n=Vn?Vn+t:t,r=this._events[n];return r?r.fn?1:r.length:0};In.prototype.emit=function(t,n,r,o,s,i){var a=Vn?Vn+t:t;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,u,d;if(l.fn){switch(l.once&&this.removeListener(t,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,n),!0;case 3:return l.fn.call(l.context,n,r),!0;case 4:return l.fn.call(l.context,n,r,o),!0;case 5:return l.fn.call(l.context,n,r,o,s),!0;case 6:return l.fn.call(l.context,n,r,o,s,i),!0}for(d=1,u=new Array(c-1);d<c;d++)u[d-1]=arguments[d];l.fn.apply(l.context,u)}else{var p=l.length,m;for(d=0;d<p;d++)switch(l[d].once&&this.removeListener(t,l[d].fn,void 0,!0),c){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,n);break;case 3:l[d].fn.call(l[d].context,n,r);break;case 4:l[d].fn.call(l[d].context,n,r,o);break;default:if(!u)for(m=1,u=new Array(c-1);m<c;m++)u[m-1]=arguments[m];l[d].fn.apply(l[d].context,u)}}return!0};In.prototype.on=function(t,n,r){return J2(this,t,n,r,!1)};In.prototype.once=function(t,n,r){return J2(this,t,n,r,!0)};In.prototype.removeListener=function(t,n,r,o){var s=Vn?Vn+t:t;if(!this._events[s])return this;if(!n)return lw(this,s),this;var i=this._events[s];if(i.fn)i.fn===n&&(!o||i.once)&&(!r||i.context===r)&&lw(this,s);else{for(var a=0,l=[],c=i.length;a<c;a++)(i[a].fn!==n||o&&!i[a].once||r&&i[a].context!==r)&&l.push(i[a]);l.length?this._events[s]=l.length===1?l[0]:l:lw(this,s)}return this};In.prototype.removeAllListeners=function(t){var n;return t?(n=Vn?Vn+t:t,this._events[n]&&lw(this,n)):(this._events=new kh,this._eventsCount=0),this};In.prototype.off=In.prototype.removeListener;In.prototype.addListener=In.prototype.on;In.prefixed=Vn;In.EventEmitter=In;typeof JR<"u"&&(JR.exports=In)});var eF,tF=L(()=>{"use strict";eF=ML(Z2(),1)});var ir,ZR,eI,tI,nI,rI,oI,sI,iI,aI,lI,cI,uI,nF=L(()=>{"use strict";ir=class extends Error{constructor(t){let{cause:n,code:r,message:o,data:s,stack:i}=t;super(o,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.BaseError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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}),this.cause=n,this.code=r,this.data=s,this.stack=i??""}},ZR=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Missing or invalid parameters."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidInputError"})}};Object.defineProperty(ZR,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});eI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Requested resource not found."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ResourceNotFoundError"})}};Object.defineProperty(eI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});tI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Requested resource not available."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ResourceUnavailableError"})}};Object.defineProperty(tI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});nI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Transaction creation failed."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.TransactionRejectedError"})}};Object.defineProperty(nI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});rI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Method is not implemented."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.MethodNotSupportedError"})}};Object.defineProperty(rI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});oI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Rate limit exceeded."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.LimitExceededError"})}};Object.defineProperty(oI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});sI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"JSON-RPC version not supported."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.VersionNotSupportedError"})}};Object.defineProperty(sI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});iI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Input is not a valid JSON-RPC request."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidRequestError"})}};Object.defineProperty(iI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});aI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Method does not exist."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.MethodNotFoundError"})}};Object.defineProperty(aI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});lI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Invalid method parameters."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidParamsError"})}};Object.defineProperty(lI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});cI=class e extends ir{constructor(t={}){super({cause:t.cause,code:e.code,data:t.data,message:t.message??"Internal JSON-RPC error.",stack:t.stack}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InternalError"})}};Object.defineProperty(cI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});uI=class e extends ir{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Failed to parse JSON-RPC response."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ParseError"})}};Object.defineProperty(uI,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700})});var jn,dI,pI,mI,hI,fI,gI,yI,bI,wI,vI,kI,xI,AI,rF=L(()=>{"use strict";tF();jn=class extends Error{constructor(t,n){super(n),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderRpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.details=n}},dI=class extends jn{constructor({message:t="The user rejected the request."}={}){super(4001,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UserRejectedRequestError"})}};Object.defineProperty(dI,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});pI=class extends jn{constructor({message:t="The requested method and/or account has not been authorized by the user."}={}){super(4100,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnauthorizedError"})}};Object.defineProperty(pI,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});mI=class extends jn{constructor({message:t="The provider does not support the requested method."}={}){super(4200,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedMethodError"})}};Object.defineProperty(mI,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});hI=class extends jn{constructor({message:t="The provider is disconnected from all chains."}={}){super(4900,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.DisconnectedError"})}};Object.defineProperty(hI,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});fI=class extends jn{constructor({message:t="The provider is not connected to the requested chain."}={}){super(4901,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.ChainDisconnectedError"})}};Object.defineProperty(fI,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});gI=class extends jn{constructor({message:t="An error occurred when attempting to switch chain."}={}){super(4902,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.SwitchChainError"})}};Object.defineProperty(gI,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});yI=class extends jn{constructor({message:t="This Wallet does not support a capability that was not marked as optional."}={}){super(5700,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedNonOptionalCapabilityError"})}};Object.defineProperty(yI,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});bI=class extends jn{constructor({message:t="This Wallet does not support the requested chain ID."}={}){super(5710,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedChainIdError"})}};Object.defineProperty(bI,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});wI=class extends jn{constructor({message:t="There is already a bundle submitted with this ID."}={}){super(5720,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.DuplicateIdError"})}};Object.defineProperty(wI,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});vI=class extends jn{constructor({message:t="This bundle id is unknown / has not been submitted."}={}){super(5730,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnknownBundleIdError"})}};Object.defineProperty(vI,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});kI=class extends jn{constructor({message:t="The call bundle is too large for the Wallet to process."}={}){super(5740,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.BundleTooLargeError"})}};Object.defineProperty(kI,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});xI=class extends jn{constructor({message:t="The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."}={}){super(5750,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.AtomicReadyWalletRejectedUpgradeError"})}};Object.defineProperty(xI,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});AI=class extends jn{constructor({message:t="The wallet does not support atomic execution but the request requires it."}={}){super(5760,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.AtomicityNotSupportedError"})}};Object.defineProperty(AI,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760})});var oF=L(()=>{"use strict"});var sF=L(()=>{"use strict"});var iF=L(()=>{"use strict"});var aF=L(()=>{"use strict"});var lF=L(()=>{"use strict"});var cF=L(()=>{"use strict"});var uF=L(()=>{"use strict"});var dF=L(()=>{"use strict"});var pF=L(()=>{"use strict"});var mF=L(()=>{"use strict"});var hF=L(()=>{"use strict"});var fF=L(()=>{"use strict"});var gF=L(()=>{"use strict"});var yF=L(()=>{"use strict"});var bF=L(()=>{"use strict"});var fo={};fr(fo,{BytesSizeMismatchError:()=>cw,InvalidDomainError:()=>uw,InvalidPrimaryTypeError:()=>dw,InvalidStructTypeError:()=>pw,assert:()=>TI,domainSeparator:()=>TX,encode:()=>wF,encodeData:()=>EI,encodeField:()=>RI,encodeType:()=>vF,extractEip712DomainTypes:()=>mw,findTypeDependencies:()=>II,getSignPayload:()=>SX,hashDomain:()=>SI,hashStruct:()=>PI,hashType:()=>kF,serialize:()=>PX,validate:()=>EX});function TI(e){let{domain:t,message:n,primaryType:r,types:o}=e,s=(i,a)=>{for(let l of i){let{name:c,type:u}=l,d=a[c],p=u.match(Ju);if(p&&(typeof d=="number"||typeof d=="bigint")){let[,f,y]=p;pt(d,{signed:f==="int",size:Number.parseInt(y??"",10)/8})}if(u==="address"&&typeof d=="string"&&!ml(d))throw new dl({address:d,cause:new Yu});let m=u.match(Eb);if(m){let[,f]=m;if(f&&nt(d)!==Number.parseInt(f,10))throw new cw({expectedSize:Number.parseInt(f,10),givenSize:nt(d)})}let g=o[u];g&&(RX(u),s(g,d))}};if(o.EIP712Domain&&t){if(typeof t!="object")throw new uw({domain:t});s(o.EIP712Domain,t)}if(r!=="EIP712Domain")if(o[r])s(o[r],n);else throw new dw({primaryType:r,types:o})}function TX(e){return SI({domain:e})}function wF(e){let{domain:t={},message:n,primaryType:r}=e,o={EIP712Domain:mw(t),...e.types};TI({domain:t,message:n,primaryType:r,types:o});let s=["0x19","0x01"];return t&&s.push(SI({domain:t,types:o})),r!=="EIP712Domain"&&s.push(PI({data:n,primaryType:r,types:o})),Jt(...s)}function vF(e){let{primaryType:t,types:n}=e,r="",o=II({primaryType:t,types:n});o.delete(t);let s=[t,...Array.from(o).sort()];for(let i of s)r+=`${i}(${(n[i]??[]).map(({name:a,type:l})=>`${l} ${a}`).join(",")})`;return r}function mw(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 SX(e){return sn(wF(e))}function SI(e){let{domain:t,types:n}=e;return PI({data:t,primaryType:"EIP712Domain",types:{...n,EIP712Domain:n?.EIP712Domain||mw(t)}})}function PI(e){let{data:t,primaryType:n,types:r}=e,o=EI({data:t,primaryType:n,types:r});return sn(o)}function PX(e){let{domain:t,message:n,primaryType:r,types:o}=e,s=(l,c)=>{let u={...c};for(let d of l){let{name:p,type:m}=d;m==="address"&&(u[p]=u[p].toLowerCase())}return u},i=(()=>{if(!t)return{};let l=o.EIP712Domain??mw(t);return s(l,t)})(),a=(()=>{if(r!=="EIP712Domain")return o[r]?s(o[r],n):{}})();return co({domain:i,message:a,primaryType:r,types:o},(l,c)=>typeof c=="bigint"?c.toString():c)}function EX(e){try{return TI(e),!0}catch{return!1}}function EI(e){let{data:t,primaryType:n,types:r}=e,o=[{type:"bytes32"}],s=[kF({primaryType:n,types:r})];for(let i of r[n]??[]){let[a,l]=RI({types:r,name:i.name,type:i.type,value:t[i.name]});o.push(a),s.push(l)}return gl(o,s)}function kF(e){let{primaryType:t,types:n}=e,r=Vs(vF({primaryType:t,types:n}));return sn(r)}function RI(e){let{types:t,name:n,type:r,value:o}=e;if(t[r]!==void 0)return[{type:"bytes32"},sn(EI({data:o,primaryType:r,types:t}))];if(r==="bytes")return o=`0x${(o.length%2?"0":"")+o.slice(2)}`,[{type:"bytes32"},sn(o,{as:"Hex"})];if(r==="string")return[{type:"bytes32"},sn(qn(o),{as:"Hex"})];if(r.lastIndexOf("]")===r.length-1){let s=r.slice(0,r.lastIndexOf("[")),i=o.map(a=>RI({name:n,type:s,types:t,value:a}));return[{type:"bytes32"},sn(gl(i.map(([a])=>a),i.map(([,a])=>a)))]}return[{type:r},o]}function II(e,t=new Set){let{primaryType:n,types:r}=e,s=n.match(/^\w*/u)?.[0];if(t.has(s)||r[s]===void 0)return t;t.add(s);for(let i of r[s])II({primaryType:i.type,types:r},t);return t}function RX(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new pw({type:e})}var cw,uw,dw,pw,xF=L(()=>{"use strict";mh();Wi();Xt();An();ul();Tn();al();Zu();cw=class extends le{constructor({expectedSize:t,givenSize:n}){super(`Expected bytes${t}, got bytes${n}.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.BytesSizeMismatchError"})}},uw=class extends le{constructor({domain:t}){super(`Invalid domain "${co(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidDomainError"})}},dw=class extends le{constructor({primaryType:t,types:n}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(n))}\`.`,{metaMessages:["Check that the primary type is a key in `types`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidPrimaryTypeError"})}},pw=class extends le{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidStructTypeError"})}}});var AF=L(()=>{"use strict"});var TF=L(()=>{"use strict"});var SF=L(()=>{"use strict"});var PF=L(()=>{"use strict"});var hw=L(()=>{"use strict";NU();gB();yB();bB();vB();ME();mh();kB();xB();Wi();e2();d2();p2();m2();h2();f2();g2();v2();S2();P2();E2();R2();I2();Xt();PE();_2();C2();L2();D2();U2();H2();An();$2();V2();k2();j2();z2();x2();ul();JM();Tn();al();K2();y2();Y2();ZM();Q2();X2();rF();xb();FR();oF();nF();sF();iF();XM();u2();aF();Zu();lF();A2();cF();uF();pF();mF();hF();fF();gF();yF();bF();xF();AF();dF();TF();SF();T2();PF()});function xl(e,t,n,r){function o(s){return s instanceof n?s:new n(function(i){i(s)})}return new(n||(n=Promise))(function(s,i){function a(u){try{c(r.next(u))}catch(d){i(d)}}function l(u){try{c(r.throw(u))}catch(d){i(d)}}function c(u){u.done?s(u.value):o(u.value).then(a,l)}c((r=r.apply(e,t||[])).next())})}function HF(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function es(e){return this instanceof es?(this.v=e,this):new es(e)}function $F(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(m){return function(g){return Promise.resolve(g).then(m,d)}}function a(m,g){r[m]&&(o[m]=function(f){return new Promise(function(y,w){s.push([m,f,y,w])>1||l(m,f)})},g&&(o[m]=g(o[m])))}function l(m,g){try{c(r[m](g))}catch(f){p(s[0][3],f)}}function c(m){m.value instanceof es?Promise.resolve(m.value.v).then(u,d):p(s[0][2],m)}function u(m){l("next",m)}function d(m){l("throw",m)}function p(m,g){m(g),s.shift(),s.length&&l(s[0][0],s[0][1])}}function lJ(e){var t,n;return t={},r("next"),r("throw",function(o){throw o}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(o,s){t[o]=e[o]?function(i){return(n=!n)?{value:es(e[o](i)),done:!1}:s?s(i):i}:s}}function cJ(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof HF=="function"?HF(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=e[s]&&function(i){return new Promise(function(a,l){i=e[s](i),o(a,l,i.done,i.value)})}}function o(s,i,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a})},i)}}function Al(e){return new _n(Promise.resolve(new Tr(e)))}function go(e){return new Wr(e)}function Sr(e){return new Tr(e)}var aJ,VF,_n,d_e,p_e,m_e,jF,uJ,zF,dJ,BI,Wr,Tr,h_e,MI=L(()=>{"use strict";aJ={withStackTrace:!1},VF=(e,t,n=aJ)=>{let r=t.isOk()?{type:"Ok",value:t.value}:{type:"Err",value:t.error},o=n.withStackTrace?new Error().stack:void 0;return{data:r,message:e,stack:o}};_n=class e{constructor(t){this._promise=t}static fromSafePromise(t){let n=t.then(r=>new Wr(r));return new e(n)}static fromPromise(t,n){let r=t.then(o=>new Wr(o)).catch(o=>new Tr(n(o)));return new e(r)}static fromThrowable(t,n){return(...r)=>new e(xl(this,void 0,void 0,function*(){try{return new Wr(yield t(...r))}catch(o){return new Tr(n?n(o):o)}}))}static combine(t){return uJ(t)}static combineWithAllErrors(t){return dJ(t)}map(t){return new e(this._promise.then(n=>xl(this,void 0,void 0,function*(){return n.isErr()?new Tr(n.error):new Wr(yield t(n.value))})))}andThrough(t){return new e(this._promise.then(n=>xl(this,void 0,void 0,function*(){if(n.isErr())return new Tr(n.error);let r=yield t(n.value);return r.isErr()?new Tr(r.error):new Wr(n.value)})))}andTee(t){return new e(this._promise.then(n=>xl(this,void 0,void 0,function*(){if(n.isErr())return new Tr(n.error);try{yield t(n.value)}catch{}return new Wr(n.value)})))}orTee(t){return new e(this._promise.then(n=>xl(this,void 0,void 0,function*(){if(n.isOk())return new Wr(n.value);try{yield t(n.error)}catch{}return new Tr(n.error)})))}mapErr(t){return new e(this._promise.then(n=>xl(this,void 0,void 0,function*(){return n.isOk()?new Wr(n.value):new Tr(yield t(n.error))})))}andThen(t){return new e(this._promise.then(n=>{if(n.isErr())return new Tr(n.error);let r=t(n.value);return r instanceof e?r._promise:r}))}orElse(t){return new e(this._promise.then(n=>xl(this,void 0,void 0,function*(){return n.isErr()?t(n.error):new Wr(n.value)})))}match(t,n){return this._promise.then(r=>r.match(t,n))}unwrapOr(t){return this._promise.then(n=>n.unwrapOr(t))}safeUnwrap(){return $F(this,arguments,function*(){return yield es(yield es(yield*lJ(cJ(yield es(this._promise.then(n=>n.safeUnwrap()))))))})}then(t,n){return this._promise.then(t,n)}[Symbol.asyncIterator](){return $F(this,arguments,function*(){let n=yield es(this._promise);return n.isErr()&&(yield yield es(Al(n.error))),yield es(n.value)})}};d_e=_n.fromPromise,p_e=_n.fromSafePromise,m_e=_n.fromThrowable,jF=e=>{let t=go([]);for(let n of e)if(n.isErr()){t=Sr(n.error);break}else t.map(r=>r.push(n.value));return t},uJ=e=>_n.fromSafePromise(Promise.all(e)).andThen(jF),zF=e=>{let t=go([]);for(let n of e)n.isErr()&&t.isErr()?t.error.push(n.error):n.isErr()&&t.isOk()?t=Sr([n.error]):n.isOk()&&t.isOk()&&t.value.push(n.value);return t},dJ=e=>_n.fromSafePromise(Promise.all(e)).andThen(zF);(function(e){function t(o,s){return(...i)=>{try{let a=o(...i);return go(a)}catch(a){return Sr(s?s(a):a)}}}e.fromThrowable=t;function n(o){return jF(o)}e.combine=n;function r(o){return zF(o)}e.combineWithAllErrors=r})(BI||(BI={}));Wr=class{constructor(t){this.value=t}isOk(){return!0}isErr(){return!this.isOk()}map(t){return go(t(this.value))}mapErr(t){return go(this.value)}andThen(t){return t(this.value)}andThrough(t){return t(this.value).map(n=>this.value)}andTee(t){try{t(this.value)}catch{}return go(this.value)}orTee(t){return go(this.value)}orElse(t){return go(this.value)}asyncAndThen(t){return t(this.value)}asyncAndThrough(t){return t(this.value).map(()=>this.value)}asyncMap(t){return _n.fromSafePromise(t(this.value))}unwrapOr(t){return this.value}match(t,n){return t(this.value)}safeUnwrap(){let t=this.value;return(function*(){return t})()}_unsafeUnwrap(t){return this.value}_unsafeUnwrapErr(t){throw VF("Called `_unsafeUnwrapErr` on an Ok",this,t)}*[Symbol.iterator](){return this.value}},Tr=class{constructor(t){this.error=t}isOk(){return!1}isErr(){return!this.isOk()}map(t){return Sr(this.error)}mapErr(t){return Sr(t(this.error))}andThrough(t){return Sr(this.error)}andTee(t){return Sr(this.error)}orTee(t){try{t(this.error)}catch{}return Sr(this.error)}andThen(t){return Sr(this.error)}orElse(t){return t(this.error)}asyncAndThen(t){return Al(this.error)}asyncAndThrough(t){return Al(this.error)}asyncMap(t){return Al(this.error)}unwrapOr(t){return t}match(t,n){return n(this.error)}safeUnwrap(){let t=this.error;return(function*(){throw yield Sr(t),new Error("Do not use this generator out of `safeTry`")})()}_unsafeUnwrap(t){throw VF("Called `_unsafeUnwrap` on an Err",this,t)}_unsafeUnwrapErr(t){return this.error}*[Symbol.iterator](){let t=this;return yield t,t}},h_e=BI.fromThrowable});function pJ(e){return e==null}function Gr(e){return!pJ(e)}function ge(e,t){if(!e)throw new KF(t)}function YF(e="Unexpected call to never()"){throw new KF(e)}function ns(e){return new Promise(t=>setTimeout(t,e))}function QF(e){let t=e.unref;typeof t=="function"&&t.call(e)}function ud(e,t){let n=setInterval(e,t);return QF(n),n}function gn(e,t){let n=setTimeout(e,t);return QF(n),n}function ln(e){return typeof e=="string"&&/^0x[a-fA-F0-9]+$/.test(e)}function Wt(e,t){return e.toLowerCase()===t.toLowerCase()}function FI(e){return ln(e)&&e.length===66}function Qs(e,t="Expected value to be present"){return ge(e!=null,t),e}function XF(e,t="Expected a non-empty array"){return ge(e.length>0,t),e}function zn(e,t="Expected a hex string"){return ge(ln(e),t),e}function JF(e,t="Expected a private key"){return ge(FI(e),t),e}function Be(e,t="Expected an EVM address"){return ge(ln(e)&&e.length===42,t),e}function rs(e,t="Expected an EVM signature"){return ge(ln(e)&&e.length===132,t),e}function ZF(e,t="Expected an ERC-1271 signature payload"){return ge(ln(e),t),e}function eq(e,t="Expected a session-signer signature envelope"){return ge(ln(e),t),e}function WF(e){throw e}function X(e){return e instanceof _n?e.match(t=>t,WF):e.match(t=>t,WF)}var ts,Ct,KF,Tl=L(()=>{"use strict";MI();MI();ts="0x0000000000000000000000000000000000000000",Ct=class GF extends Error{static isError(t){return t instanceof GF}},KF=class extends Ct{name="InvariantError"}});function dd(e){if(!Number.isInteger(e))throw new TypeError(`Expected an integer, received: ${e}`);return e}function HI(e){return e}function kw(e){if(!ln(e)||e.length!==66)throw new TypeError(`Expected a 32-byte hex string, received: ${e}`);return e}function tq(e){return e}function nq(e){return e}function $I(e){return e}function rq(e){return e}function oq(e){return e}function sq(e){return e}function _h(e){if(!ln(e)||e.length!==64&&e.length!==66)throw new TypeError(`Expected a 31-byte or 32-byte hex string, received: ${e}`);return e}function qI(e){if(!ln(e))return;let t=e.toLowerCase();if(t.length===64&&t.startsWith("0x03"))return t;if(t.length===66&&t.startsWith("0x03")&&(t.endsWith("00")||t.endsWith("01")))return t.slice(0,-2)}function VI(e){let t=qI(e);if(t!==void 0)return t;throw new TypeError(`Expected a protocol v2 combo condition ID, received: ${e}`)}function jI(e){return e}function zI(e){return e}function WI(e){return dd(e)}function pd(e){return dd(e)}function GI(e){return e}function iq(e){return e}function aq(e){return e}function lq(e){return e}function KI(e){return e}function cq(e){return e}function xw(e){return e}function uq(e){return dd(e)}function dq(e){return e}function YI(e){return dd(e)}function Aw(e){return e}function pq(e){return fJ(e)}function md(e){return e}function Tw(e){return e}function mq(e){return e}function QI(e){return e}function XI(e){return dd(e)}function hq(e){return e}function JI(e){return dd(e)}function ZI(e){return e}function fq(e){return e}function gq(e){return e}function Ch(e){return e}function Sl(e){return e}function Gn(e){return e===""?null:e}function gd(e){return e===""?void 0:e}function hJ(e){return e}function fJ(e){if(!ln(e)||e.length!==66)throw new TypeError(`Expected a 32-byte hex string, received: ${e}`);return e}var de,Rh,Ue,cn,Qi,yo,Ih,e_,os,bo,t_,Xs,n_,Zt,xe,Nh,J,pe,wo,Sw,Pw,Pr,hd,Xi,mJ,r_,un,Gt,Pl,oe,Wn,o_,s_,i_,Ji,a_,Js,fd,Nt,Oh,Lh,ye,Xe,Me,vo,l_,ar,Zi,Ew,Dh,Rw,ea,et,R,yn,H,ko,ss,dn,xo=L(()=>{"use strict";Tl();de=require("zod"),Rh=(e=>(e.Event="Event",e.Series="Series",e))(Rh||{}),Ue=(e=>(e.BUY="BUY",e.SELL="SELL",e))(Ue||{}),cn=(e=>(e.GTC="GTC",e.FOK="FOK",e.GTD="GTD",e.FAK="FAK",e))(cn||{}),Qi=(e=>(e.Matched="TRADE_STATUS_MATCHED",e.MatchedNotBroadcasted="TRADE_STATUS_MATCHED_NOT_BROADCASTED",e.Mined="TRADE_STATUS_MINED",e.Confirmed="TRADE_STATUS_CONFIRMED",e.Retrying="TRADE_STATUS_RETRYING",e.Failed="TRADE_STATUS_FAILED",e))(Qi||{}),yo=(e=>(e.ALL="ALL",e.CLOB="CLOB",e.COMBOSRFQ="COMBOSRFQ",e))(yo||{}),Ih=de.z.string().min(1).transform(e=>e);e_=de.z.string().transform(nq),os=de.z.string().transform(tq),bo=de.z.string().transform(kw),t_=de.z.string().transform(rq),Xs=de.z.string().transform(oq),n_=de.z.string().transform(sq),Zt=de.z.string().refine(e=>qI(e)!==void 0,"Expected a protocol v2 combo condition ID").transform(e=>qI(e)),xe=de.z.string().refine(e=>ln(e)&&(e.length===64||e.length===66),"Expected a 31-byte or 32-byte hex string").transform(e=>e),Nh=de.z.custom(ln,"Expected a hex-encoded market condition ID"),J=de.z.string().refine(e=>ln(e)&&e.length===42,"Expected an EVM address").transform(hJ),pe=de.z.number().int().transform(pd),wo=de.z.number().int().transform(e=>pd(e*1e3)),Sw=de.z.union([de.z.number().int(),de.z.string().regex(/^\d+$/).transform(Number)]),Pw=de.z.string().transform(e=>/^\d{4}-\d{2}-\d{2}$/.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString():e),Pr=de.z.string().regex(/^\d+$/).transform(e=>pd(Number(e))),hd=de.z.union([Sw.transform(e=>new Date(e).toISOString()),Pw]),Xi=de.z.union([Sw.transform(e=>new Date(e<1e12?e*1e3:e).toISOString()),Pw]),mJ=de.z.union([Sw.transform(e=>e===0?void 0:new Date(e).toISOString()),Pw]),r_=de.z.union([Sw.transform(e=>e===0?void 0:new Date(e<1e12?e*1e3:e).toISOString()),Pw]),un=hd,Gt=de.z.union([de.z.string(),de.z.number().int().transform(String)]).transform(GI),Pl=de.z.union([de.z.literal(.1),de.z.literal(.01),de.z.literal(.005),de.z.literal(.0025),de.z.literal(.001),de.z.literal(1e-4)]),oe=de.z.string().transform(KI).or(de.z.date().transform(e=>e.toISOString())),Wn=de.z.string().transform(lq).or(de.z.date().transform(e=>e.toISOString().slice(0,10))),o_=de.z.string().transform(cq),s_=de.z.string().transform(iq),i_=de.z.string().transform(aq),Ji=de.z.string().transform(xw),a_=de.z.number().int().transform(uq),Js=de.z.enum(Rh),fd=de.z.string().transform(dq),Nt=de.z.enum(Ue),Oh=de.z.enum(cn),Lh=de.z.preprocess(e=>typeof e!="string"||e.startsWith("TRADE_STATUS_")?e:Object.values(Qi).find(t=>t.slice(13)===e)??e,de.z.enum(Qi)),ye=de.z.custom(e=>typeof e=="string"&&e.length>0,"Expected a non-empty pagination cursor"),Xe=de.z.string().transform(Aw),Me=de.z.string().transform(e=>e),vo=de.z.string().refine(e=>ln(e)&&e.length===66,"Expected a 32-byte hex string").transform(e=>e),l_=de.z.string().transform(pq),ar=de.z.string().transform(md),Zi=de.z.string().transform(Tw),Ew=de.z.string().transform(mq),Dh=de.z.string().transform(hq),Rw=de.z.string().transform(gq),ea=de.z.string().min(1).transform(fq),et=de.z.string().refine(e=>ln(e)&&e.length===66,"Expected a transaction hash").transform(e=>e),R=de.z.string().transform(Ch),yn=de.z.string().regex(/^\d+$/).transform(e=>{let t=BigInt(e),n=t/1000000n,r=(t%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return`${n}${r===""?"":`.${r}`}`}),H=de.z.union([R,de.z.number().transform(e=>String(e))]),ko=de.z.union([de.z.number(),de.z.string().transform(Number)]).pipe(de.z.number().positive()),ss=de.z.string().transform(Sl);dn=de.z.preprocess(Gn,R.nullish())});function Nw(e){return{id:e.id,version:e.version,slug:e.slug,conditionId:e.conditionId,question:e.question,groupItemTitle:e.groupItemTitle,description:e.description,category:e.category,image:e.image,icon:e.icon,state:{active:e.active,closed:e.closed,archived:e.archived,comboStatus:e.comboStatus,acceptingOrders:e.acceptingOrders,enableOrderBook:e.enableOrderBook,negRisk:e.negRisk,startDate:e.startDate,endDate:e.endDate,closedTime:e.closedTime},outcomes:EJ(e),metrics:{volume:e.volume,volumeNum:e.volumeNum,volume24hr:e.volume24hr,volume1wk:e.volume1wk,volume1mo:e.volume1mo,volume1yr:e.volume1yr,volumeClob:e.volumeClob,liquidity:e.liquidity,liquidityNum:e.liquidityNum,liquidityClob:e.liquidityClob},prices:{bestBid:e.bestBid,bestAsk:e.bestAsk,lastTradePrice:e.lastTradePrice,spread:e.spread,oneHourPriceChange:e.oneHourPriceChange,oneDayPriceChange:e.oneDayPriceChange,oneWeekPriceChange:e.oneWeekPriceChange,oneMonthPriceChange:e.oneMonthPriceChange,oneYearPriceChange:e.oneYearPriceChange},trading:{minimumOrderSize:e.orderMinSize,minimumTickSize:e.orderPriceMinTickSize,secondsDelay:e.secondsDelay,feesEnabled:e.feesEnabled,feeType:e.feeType,feeSchedule:e.feeSchedule},resolution:{questionId:e.questionID,negRiskRequestId:e.negRiskRequestID,umaResolutionStatus:e.umaResolutionStatus,source:e.resolutionSource,resolvedBy:e.resolvedBy},rewards:{clobRewards:e.clobRewards,rewardsMinSize:e.rewardsMinSize,rewardsMaxSpread:e.rewardsMaxSpread,holdingRewardsEnabled:e.holdingRewardsEnabled},sports:{sportsMarketType:e.sportsMarketType,line:e.line,gameId:e.gameId,gameStartTime:e.gameStartTime},events:(e.events??[]).map(t=>({id:t.id,slug:t.slug??null,title:t.title??null})),positionIds:e.positionIds,tags:(e.tags??[]).map(t=>({id:t.id,slug:t.slug,label:t.label}))}}function Uh(e){return e??null}function Ow(e){return typeof e=="string"?JSON.parse(e):e}function Bh(e){return e.outcomes.length===2}function EJ(e){if(!Bh(e))throw new TypeError(`Expected binary market outcomes, received ${e.outcomes.length}`);let[t,n]=e.outcomes;return{yes:{label:t,tokenId:e.clobTokenIds[0]??null,positionId:e.positionIds[0]??null,price:e.outcomePrices[0]??null},no:{label:n,tokenId:e.clobTokenIds[1]??null,positionId:e.positionIds[1]??null,price:e.outcomePrices[1]??null}}}function HJ(e){return{id:e.id,version:e.version,parentEventId:e.parentEventId,ticker:e.ticker,slug:e.slug,title:e.title,subtitle:e.subtitle,description:e.description,category:e.category,subcategory:e.subcategory,image:e.image,icon:e.icon,featuredImage:e.featuredImage,createdAt:e.createdAt,updatedAt:e.updatedAt,publishedAt:e.published_at,state:{active:e.active,closed:e.closed,archived:e.archived,new:e.new,featured:e.featured,restricted:e.restricted,cyom:e.cyom,live:e.live,ended:e.ended,automaticallyActive:e.automaticallyActive,commentsEnabled:e.commentsEnabled},schedule:{startDate:e.startDate,creationDate:e.creationDate,endDate:e.endDate,closedTime:e.closedTime,startTime:e.startTime,eventDate:e.eventDate,eventWeek:e.eventWeek,finishedAt:e.finishedTimestamp},metrics:{liquidity:e.liquidity,liquidityClob:e.liquidityClob,volume:e.volume,volume24hr:e.volume24hr,volume1wk:e.volume1wk,volume1mo:e.volume1mo,volume1yr:e.volume1yr,openInterest:e.openInterest,competitive:e.competitive,commentCount:e.commentCount,tweetCount:e.tweetCount},display:{sortBy:e.sortBy,showAllOutcomes:e.showAllOutcomes,showMarketImages:e.showMarketImages,gmpChartMode:e.gmpChartMode,color:e.color,featuredOrder:e.featuredOrder,countryName:e.countryName,electionType:e.electionType,imageOptimized:e.imageOptimized,iconOptimized:e.iconOptimized,featuredImageOptimized:e.featuredImageOptimized},trading:{enableOrderBook:e.enableOrderBook,negRisk:e.negRisk,negRiskMarketId:e.negRiskMarketID,negRiskFeeBips:e.negRiskFeeBips,enableNegRisk:e.enableNegRisk,negRiskAugmented:e.negRiskAugmented,cumulativeMarkets:e.cumulativeMarkets},resolution:{source:e.resolutionSource,automaticallyResolved:e.automaticallyResolved},estimation:{estimateValue:e.estimateValue,cantEstimate:e.cantEstimate,estimatedValue:e.estimatedValue},sports:{seriesSlug:e.seriesSlug,score:e.score,elapsed:e.elapsed,period:e.period,gameStatus:e.gameStatus,gameId:e.gameId,rescheduledFromGameId:e.rescheduledFromGameId,sportsradarMatchId:e.sportsradarMatchId,homeTeamName:e.homeTeamName,awayTeamName:e.awayTeamName,spreadsMainLine:e.spreadsMainLine,totalsMainLine:e.totalsMainLine,bestLines:e.bestLines??[],teams:e.teams??[],sport:e.sport,lastHighlight:e.lastHighlight,lastHighlightType:e.lastHighlightType,lastHighlightAt:e.lastHighlightAt},partners:(e.externalPartners??[]).map(t=>({id:t.id,externalId:t.externalId,partner:t.partner?{id:t.partner.id,slug:t.partner.slug,name:t.partner.name}:null,createdAt:t.createdAt,updatedAt:t.updatedAt})),metadata:e.eventMetadata??null,markets:e.markets??[],series:(e.series??[]).map(t=>({id:t.id,slug:t.slug,title:t.title,subtitle:t.subtitle,description:t.description,image:t.image,icon:t.icon,active:t.active,closed:t.closed,archived:t.archived,volume:t.volume,liquidity:t.liquidity,startDate:t.startDate})),tags:(e.tags??[]).map(t=>({id:t.id,slug:t.slug,label:t.label})),creators:(e.eventCreators??[]).map(t=>({id:t.id,name:t.creatorName,handle:t.creatorHandle,url:t.creatorUrl??t.creatorURL,image:t.creatorImage,createdAt:t.createdAt,updatedAt:t.updatedAt}))}}var b,gJ,Zs,yq,yJ,bq,El,wq,vq,c_,bJ,wJ,vJ,kJ,xJ,Iw,AJ,ta,TJ,u_,SJ,_w,Cw,kq,PJ,d_,p_,RJ,IJ,_J,CJ,NJ,OJ,xq,Mh,LJ,DJ,UJ,BJ,Lw,Dw,Uw,Aq,Tq,Sq,Pq,Eq,Fh,m_,h_,f_,g_,y_,MJ,FJ,Rq,ei,qJ,b_,w_,Iq,Rl,v_,_q,yd,Bw,qh,Hh,k_,$h=L(()=>{"use strict";xo();b=require("zod"),gJ=b.z.preprocess(e=>e===""?void 0:e,Nh.optional()),Zs=b.z.object({id:s_,imageUrlSource:b.z.string().nullish(),imageUrlOptimized:b.z.string().nullish(),imageSizeKbSource:b.z.number().nullish(),imageSizeKbOptimized:b.z.number().nullish(),imageOptimizedComplete:b.z.boolean().nullish(),imageOptimizedLastUpdated:oe.nullish(),relID:b.z.number().int().nullish(),field:b.z.string().nullish(),relname:b.z.string().nullish()}),yq=b.z.object({exponent:b.z.number(),rate:H,takerOnly:b.z.boolean(),rebateRate:H}),yJ=b.z.object({id:Gt}),bq=b.z.object({id:e_,label:b.z.string().nullish(),parentCategory:b.z.string().nullish(),slug:b.z.string().nullish(),publishedAt:oe.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish()}),El=b.z.object({id:Dh,label:b.z.string().nullish(),slug:b.z.string().nullish(),forceShow:b.z.boolean().nullish(),publishedAt:oe.nullish(),createdBy:b.z.number().int().nullish(),updatedBy:b.z.number().int().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),forceHide:b.z.boolean().nullish(),isCarousel:b.z.boolean().nullish(),activeEventsCount:b.z.number().int().nullish()}),wq=b.z.object({id:Ji,conditionId:gJ,slug:b.z.string().nullish(),image:b.z.string().nullish(),volume:R.nullish(),question:b.z.string().nullish(),outcomes:b.z.string().nullish(),outcomePrices:b.z.string().nullish(),startDate:oe.nullish(),eventSlug:b.z.string().nullish()}),vq=b.z.object({id:t_,conditionId:Nh,assetAddress:b.z.string(),rewardsAmount:H,rewardsDailyRate:H,startDate:Wn,endDate:Wn.nullish()}),c_=b.z.object({id:i_,username:b.z.string().nullish()}),bJ=b.z.object({id:Gt,slug:b.z.string().nullish(),title:b.z.string().nullish()}),wJ=b.z.preprocess(Ow,b.z.array(b.z.string()).nullish()).transform(e=>e??[]),vJ=b.z.preprocess(Ow,b.z.array(R).nullish()).transform(e=>e??[]),kJ=b.z.preprocess(Ow,b.z.array(Rw).nullish()).transform(e=>e??[]),xJ=b.z.preprocess(Ow,b.z.array(Xe).nullish()).transform(e=>e??[]),Iw=(e=>(e.Pending="pending",e.Enabled="enabled",e.Disabled="disabled",e))(Iw||{}),AJ=b.z.string().transform(e=>e),ta=(e=>(e.V1="v1",e.V2="v2",e))(ta||{}),TJ=b.z.enum(ta),u_=(e=>(e.Disputed="disputed",e.Proposed="proposed",e.Requested="requested",e.Resolved="resolved",e.Settled="settled",e))(u_||{}),SJ=b.z.enum(u_),_w=b.z.object({id:Ji,version:TJ.nullish(),question:b.z.string().nullish(),conditionId:b.z.preprocess(Gn,Nh.nullish()).transform(Uh),slug:b.z.string().nullish(),twitterCardImage:b.z.string().nullish(),resolutionSource:b.z.string().nullish(),endDate:oe.nullish(),category:b.z.string().nullish(),liquidity:R.nullish(),sponsorName:b.z.string().nullish(),sponsorImage:b.z.string().nullish(),startDate:oe.nullish(),xAxisValue:b.z.string().nullish(),yAxisValue:b.z.string().nullish(),denominationToken:b.z.string().nullish(),fee:R.nullish(),image:b.z.string().nullish(),icon:b.z.string().nullish(),lowerBound:R.nullish(),upperBound:R.nullish(),description:b.z.string().nullish(),outcomes:wJ,outcomePrices:vJ,volume:R.nullish(),active:b.z.boolean().nullish(),marketType:b.z.string().nullish(),formatType:b.z.string().nullish(),lowerBoundDate:Wn.nullish(),upperBoundDate:Wn.nullish(),closed:b.z.boolean().nullish(),createdBy:b.z.number().int().nullish(),updatedBy:b.z.number().int().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),closedTime:oe.nullish(),wideFormat:b.z.boolean().nullish(),new:b.z.boolean().nullish(),sentDiscord:b.z.boolean().nullish(),mailchimpTag:b.z.string().nullish(),featured:b.z.boolean().nullish(),submitted_by:b.z.string().nullish(),subcategory:b.z.string().nullish(),categoryMailchimpTag:b.z.string().nullish(),twitterCardLocation:b.z.string().nullish(),twitterCardLastRefreshed:oe.nullish(),twitterCardLastValidated:oe.nullish(),archived:b.z.boolean().nullish(),resolvedBy:b.z.preprocess(Gn,J.nullish()).transform(Uh),restricted:b.z.boolean().nullish(),marketGroup:b.z.number().int().nullish(),groupItemTitle:b.z.string().nullish(),groupItemThreshold:R.nullish(),questionID:b.z.preprocess(Gn,vo.nullish()).transform(Uh),umaEndDate:o_.nullish(),enableOrderBook:b.z.boolean().nullish(),orderPriceMinTickSize:Pl.nullish(),orderMinSize:H.nullish(),umaResolutionStatus:b.z.preprocess(Gn,SJ.nullish()).transform(Uh),curationOrder:b.z.number().int().nullish(),volumeNum:H.nullish(),liquidityNum:H.nullish(),endDateIso:Wn.nullish(),startDateIso:Wn.nullish(),umaEndDateIso:Wn.nullish(),hasReviewedDates:b.z.boolean().nullish(),readyForCron:b.z.boolean().nullish(),commentsEnabled:b.z.boolean().nullish(),volume24hr:H.nullish(),volume1wk:H.nullish(),volume1mo:H.nullish(),volume1yr:H.nullish(),gameStartTime:oe.nullish(),secondsDelay:b.z.number().int().nullish(),clobTokenIds:kJ,comboStatus:AJ.nullish(),positionIds:xJ,disqusThread:b.z.string().nullish(),shortOutcomes:b.z.string().nullish(),teamAID:b.z.string().nullish(),teamBID:b.z.string().nullish(),umaBond:R.nullish(),umaReward:R.nullish(),volume24hrClob:H.nullish(),volume1wkClob:H.nullish(),volume1moClob:H.nullish(),volume1yrClob:H.nullish(),volumeClob:H.nullish(),liquidityClob:H.nullish(),makerBaseFee:b.z.number().nullish(),takerBaseFee:b.z.number().nullish(),customLiveness:b.z.number().int().nullish(),acceptingOrders:b.z.boolean().nullish(),negRisk:b.z.boolean().nullish(),negRiskMarketID:b.z.string().nullish(),negRiskRequestID:b.z.preprocess(Gn,l_.nullish()).transform(Uh),notificationsEnabled:b.z.boolean().nullish(),score:b.z.number().int().nullish(),imageOptimized:Zs.nullish(),iconOptimized:Zs.nullish(),events:b.z.array(bJ).nullish(),categories:b.z.array(b.z.unknown()).nullish(),markets:b.z.array(wq).nullish(),creator:b.z.string().nullish(),ready:b.z.boolean().nullish(),funded:b.z.boolean().nullish(),pastSlugs:b.z.string().nullish(),readyTimestamp:oe.nullish(),fundedTimestamp:oe.nullish(),acceptingOrdersTimestamp:oe.nullish(),tags:b.z.array(El).nullish(),cyom:b.z.boolean().nullish(),competitive:b.z.number().nullish(),approved:b.z.boolean().nullish(),clobRewards:b.z.array(vq).nullish(),rewardsMinSize:H.nullish(),rewardsMaxSpread:b.z.number().nullish(),spread:H.nullish(),automaticallyResolved:b.z.boolean().nullish(),oneDayPriceChange:H.nullish(),oneHourPriceChange:H.nullish(),oneWeekPriceChange:H.nullish(),oneMonthPriceChange:H.nullish(),oneYearPriceChange:H.nullish(),lastTradePrice:H.nullish(),bestBid:H.nullish(),bestAsk:H.nullish(),automaticallyActive:b.z.boolean().nullish(),clearBookOnStart:b.z.boolean().nullish(),chartColor:b.z.string().nullish(),seriesColor:b.z.string().nullish(),showGmpSeries:b.z.boolean().nullish(),showGmpOutcome:b.z.boolean().nullish(),manualActivation:b.z.boolean().nullish(),negRiskOther:b.z.boolean().nullish(),gameId:b.z.string().nullish(),groupItemRange:b.z.string().nullish(),sportsMarketType:b.z.string().nullish(),line:b.z.number().nullish(),umaResolutionStatuses:b.z.string().nullish(),pendingDeployment:b.z.boolean().nullish(),deploying:b.z.boolean().nullish(),deployingTimestamp:oe.nullish(),scheduledDeploymentTimestamp:oe.nullish(),rfqEnabled:b.z.boolean().nullish(),eventStartTime:oe.nullish(),internalUsers:b.z.array(c_).nullish(),holdingRewardsEnabled:b.z.boolean().nullish(),feesEnabled:b.z.boolean().nullish(),makerRebatesFeeShareBps:b.z.number().nullish(),feeType:b.z.string().nullish(),feeSchedule:yq.nullish()}),Cw=_w.transform((e,t)=>Bh(e)?Nw(e):(t.addIssue({code:"custom",message:`Expected binary market outcomes, received ${e.outcomes.length}`}),b.z.NEVER)),kq=_w.transform(e=>Bh(e)?Nw(e):null),PJ=b.z.array(kq).transform(e=>e.filter(t=>t!==null)),d_=b.z.object({markets:b.z.array(kq),next_cursor:ye.optional()}).transform(({markets:e,next_cursor:t})=>({items:e.filter(n=>n!==null),nextCursor:t})),p_=b.z.array(El);RJ=b.z.string().transform(HI),IJ=b.z.string().transform($I),_J=b.z.string().transform(jI),CJ=b.z.string().transform(zI),NJ=b.z.number().int().transform(WI),OJ=b.z.union([Gt,b.z.number().int().transform(e=>String(e))]),xq=b.z.number().int().transform(YI),Mh=b.z.union([b.z.string(),b.z.number().int().transform(String)]).transform(QI),LJ=b.z.number().int().transform(XI),DJ=b.z.number().int().transform(JI),UJ=b.z.string().transform(ZI),BJ=b.z.enum(ta),Lw=b.z.object({id:_J,ticker:b.z.string().nullish(),slug:b.z.string().nullish(),title:b.z.string().nullish(),subtitle:b.z.string().nullish(),collectionType:b.z.string().nullish(),description:b.z.string().nullish(),tags:b.z.string().nullish(),image:b.z.string().nullish(),icon:b.z.string().nullish(),headerImage:b.z.string().nullish(),layout:b.z.string().nullish(),active:b.z.boolean().nullish(),closed:b.z.boolean().nullish(),archived:b.z.boolean().nullish(),new:b.z.boolean().nullish(),featured:b.z.boolean().nullish(),restricted:b.z.boolean().nullish(),isTemplate:b.z.boolean().nullish(),templateVariables:b.z.string().nullish(),publishedAt:oe.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),disqusThread:b.z.string().nullish(),commentsEnabled:b.z.boolean().nullish()}),Dw=b.z.object({id:Mh,ticker:b.z.string().nullish(),slug:b.z.string().nullish(),title:b.z.string().nullish(),subtitle:b.z.string().nullish(),seriesType:b.z.string().nullish(),recurrence:b.z.string().nullish(),description:b.z.string().nullish(),image:b.z.string().nullish(),icon:b.z.string().nullish(),layout:b.z.string().nullish(),active:b.z.boolean().nullish(),closed:b.z.boolean().nullish(),archived:b.z.boolean().nullish(),new:b.z.boolean().nullish(),featured:b.z.boolean().nullish(),restricted:b.z.boolean().nullish(),isTemplate:b.z.boolean().nullish(),templateVariables:b.z.boolean().nullish(),publishedAt:oe.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),commentsEnabled:b.z.boolean().nullish(),competitive:b.z.string().nullish(),volume24hr:H.nullish(),volume:H.nullish(),liquidity:H.nullish(),startDate:oe.nullish(),pythTokenID:b.z.string().nullish(),cgAssetName:b.z.string().nullish(),score:b.z.number().int().nullish(),commentCount:b.z.number().int().nullish()}),Uw=b.z.object({id:UJ,displayName:b.z.string().nullish(),eventTitle:b.z.string().nullish(),eventSlug:b.z.string().nullish(),description:b.z.string().nullish(),resolutionSource:b.z.string().nullish(),marketsOrder:b.z.string().nullish(),marketsNegRisk:b.z.boolean().nullish(),marketsAugmentedNegRisk:b.z.boolean().nullish(),marketsShowImages:b.z.boolean().nullish(),markets:b.z.string().nullish(),userVariables:b.z.string().nullish(),creatorUserId:b.z.string().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish()}),Aq=b.z.object({id:IJ,channelId:b.z.string().nullish(),channelName:b.z.string().nullish(),channelImage:b.z.string().nullish(),live:b.z.boolean().nullish(),startTime:oe.nullish(),endTime:oe.nullish()}),Tq=b.z.object({id:CJ,creatorName:b.z.string().nullish(),creatorHandle:b.z.string().nullish(),creatorUrl:b.z.string().nullish(),creatorURL:b.z.string().nullish(),creatorImage:b.z.string().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish()}),Sq=b.z.object({id:xq,slug:b.z.string(),name:b.z.string(),createdAt:oe.nullish(),updatedAt:oe.nullish()}),Pq=b.z.object({id:NJ,eventId:OJ,partnerId:xq,externalId:b.z.string(),partner:Sq.nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish()}),Eq=b.z.object({id:RJ,lineType:b.z.string().nullish(),line:b.z.number().nullish()}),Fh=(e=>(e.Home="home",e.Away="away",e))(Fh||{}),m_=b.z.object({id:DJ,name:b.z.string().nullish(),league:b.z.string().nullish(),record:b.z.string().nullish(),logo:b.z.string().nullish(),abbreviation:b.z.string().nullish(),alias:b.z.string().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),providerId:b.z.number().int().nullish(),color:b.z.string().nullish(),ordering:b.z.enum(Fh).nullish()}),h_=b.z.object({id:LJ,sport:b.z.string(),name:b.z.string().nullish(),image:b.z.string(),resolution:b.z.string(),ordering:b.z.string(),tags:b.z.string(),series:b.z.string(),createdAt:oe.nullish(),updatedAt:oe.nullish()}),f_=b.z.array(m_),g_=b.z.array(h_),y_=b.z.object({marketTypes:b.z.array(b.z.string()).nullish()}),MJ=_w.transform(e=>Bh(e)?Nw(e):null),FJ=b.z.array(MJ).transform(e=>e.filter(t=>t!==null)),Rq=b.z.object({id:Gt,version:BJ.nullish(),ticker:b.z.string().nullish(),slug:b.z.string().nullish(),title:b.z.string().nullish(),subtitle:b.z.string().nullish(),description:b.z.string().nullish(),resolutionSource:b.z.string().nullish(),startDate:oe.nullish(),creationDate:oe.nullish(),endDate:oe.nullish(),image:b.z.string().nullish(),icon:b.z.string().nullish(),active:b.z.boolean().nullish(),closed:b.z.boolean().nullish(),archived:b.z.boolean().nullish(),new:b.z.boolean().nullish(),featured:b.z.boolean().nullish(),restricted:b.z.boolean().nullish(),liquidity:H.nullish(),volume:H.nullish(),openInterest:H.nullish(),sortBy:b.z.string().nullish(),category:b.z.string().nullish(),subcategory:b.z.string().nullish(),isTemplate:b.z.boolean().nullish(),templateVariables:b.z.string().nullish(),published_at:oe.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),commentsEnabled:b.z.boolean().nullish(),competitive:b.z.number().nullish(),volume24hr:H.nullish(),volume1wk:H.nullish(),volume1mo:H.nullish(),volume1yr:H.nullish(),featuredImage:b.z.string().nullish(),disqusThread:b.z.string().nullish(),parentEventId:Gt.nullish(),enableOrderBook:b.z.boolean().nullish(),liquidityClob:H.nullish(),negRisk:b.z.boolean().nullish(),negRiskMarketID:b.z.string().nullish(),negRiskFeeBips:b.z.number().nullish(),commentCount:b.z.number().int().nullish(),imageOptimized:Zs.nullish(),iconOptimized:Zs.nullish(),featuredImageOptimized:Zs.nullish(),subEvents:b.z.array(b.z.string()).nullish(),markets:FJ.nullish(),series:b.z.array(Dw).nullish(),categories:b.z.array(bq).nullish(),collections:b.z.array(Lw).nullish(),tags:b.z.array(El).nullish(),tag_labels:b.z.array(b.z.string()).nullish(),tag_slugs:b.z.array(b.z.string()).nullish(),cyom:b.z.boolean().nullish(),closedTime:oe.nullish(),showAllOutcomes:b.z.boolean().nullish(),showMarketImages:b.z.boolean().nullish(),automaticallyResolved:b.z.boolean().nullish(),enableNegRisk:b.z.boolean().nullish(),automaticallyActive:b.z.boolean().nullish(),eventDate:Wn.nullish(),startTime:oe.nullish(),eventWeek:b.z.number().int().nullish(),seriesSlug:b.z.string().nullish(),score:b.z.string().nullish(),elapsed:b.z.string().nullish(),period:b.z.string().nullish(),live:b.z.boolean().nullish(),ended:b.z.boolean().nullish(),finishedTimestamp:oe.nullish(),gmpChartMode:b.z.string().nullish(),eventCreators:b.z.array(Tq).nullish(),negRiskAugmented:b.z.boolean().nullish(),countryName:b.z.string().nullish(),electionType:b.z.string().nullish(),color:b.z.string().nullish(),tweetCount:b.z.number().int().nullish(),chats:b.z.array(Aq).nullish(),featuredOrder:b.z.number().int().nullish(),estimateValue:b.z.boolean().nullish(),cantEstimate:b.z.boolean().nullish(),estimatedValue:R.nullish(),cumulativeMarkets:b.z.boolean().nullish(),templates:b.z.array(Uw).nullish(),spreadsMainLine:b.z.number().nullish(),totalsMainLine:b.z.number().nullish(),carouselMap:b.z.string().nullish(),pendingDeployment:b.z.boolean().nullish(),deploying:b.z.boolean().nullish(),deployingTimestamp:oe.nullish(),scheduledDeploymentTimestamp:oe.nullish(),gameStatus:b.z.string().nullish(),internalUsers:b.z.array(c_).nullish(),gameId:b.z.number().int().nullish(),rescheduledFromGameId:b.z.number().int().nullish(),sportsradarMatchId:b.z.string().nullish(),bestLines:b.z.array(Eq).nullish(),homeTeamName:b.z.string().nullish(),awayTeamName:b.z.string().nullish(),turnProviderId:b.z.string().nullish(),lastHighlight:b.z.string().nullish(),lastHighlightType:b.z.string().nullish(),lastHighlightAt:oe.nullish(),eventMetadata:b.z.record(b.z.string(),b.z.unknown()).nullish(),teams:b.z.array(m_).nullish(),sport:h_.nullish(),externalPartners:b.z.array(Pq).nullish()}),ei=Rq.transform(HJ),qJ=b.z.array(ei),b_=b.z.object({events:b.z.array(ei),next_cursor:ye.optional()}).transform(({events:e,next_cursor:t})=>({items:e,nextCursor:t})),w_=b.z.array(El);Iq=b.z.object({tokenId:Rw.nullish(),positionSize:ss.nullish()}),Rl=b.z.object({name:b.z.string().nullish(),pseudonym:b.z.string().nullish(),displayUsernamePublic:b.z.boolean().nullish(),bio:b.z.string().nullish(),isMod:b.z.boolean().nullish(),isCreator:b.z.boolean().nullish(),proxyWallet:b.z.string().nullish(),baseAddress:b.z.string().nullish(),profileImage:b.z.string().nullish(),profileImageOptimized:Zs.nullish(),positions:b.z.array(Iq).nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),v_=(e=>(e.Heart="HEART",e))(v_||{}),_q=b.z.enum(v_),yd=b.z.object({id:b.z.string(),commentID:b.z.number().int().nullish(),reactionType:_q.nullish(),icon:b.z.string().nullish(),userAddress:b.z.string().nullish(),createdAt:oe.nullish(),profile:Rl.nullish()}),Bw=b.z.object({id:b.z.string(),commentID:b.z.number().int().nullish(),provider:b.z.string().nullish(),providerMediaId:b.z.string().nullish(),url:b.z.string().nullish(),mediaType:b.z.string().nullish(),altText:b.z.string().nullish(),createdAt:oe.nullish()}),qh=b.z.object({id:Xs,body:b.z.string().nullish(),parentEntityType:Js.nullish(),parentEntityID:b.z.union([Gt,Mh]).nullish(),parentCommentID:Xs.nullish(),userAddress:b.z.string().nullish(),replyAddress:b.z.string().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),media:b.z.array(Bw).nullish(),profile:Rl.nullish(),reactions:b.z.array(yd).nullish(),reportCount:b.z.number().int().nullish(),reactionCount:b.z.number().int().nullish(),tradeAsset:b.z.string().nullish()}),Hh=b.z.array(qh),k_=b.z.object({comments:b.z.array(qh),next_cursor:ye.optional()}).transform(({comments:e,next_cursor:t})=>({items:e,nextCursor:t}))});function Il(e){return e}function dH(e,t){let[n="0",r=""]=e.split("."),[o="0",s=""]=t.split("."),i=Math.max(r.length,s.length),a=BigInt(`${n}${r.padEnd(i,"0")}`),l=BigInt(`${o}${s.padEnd(i,"0")}`),c=a+l,u=(c<0n?-c:c).toString().padStart(i+1,"0"),d=i===0?"":u.slice(-i).replace(/0+$/,""),p=i===0?u:u.slice(0,-i);return`${c<0n?"-":""}${p}${d?`.${d}`:""}`}function hH(e){return e??"Perps command was rejected."}var P,Ae,Cn,Er,_l,Cq,na,x_,Mw,A_,Nq,Oq,Ao,jh,zh,Wh,ti,ra,vd,Gh,Fw,qw,Kh,Yh,T_,Qh,S_,Xh,ni,P_,Lq,Dq,kd,xd,Uq,Bq,Hw,$w,E_,Kn,Cl,To,Vw,R_,Mq,I_,Fq,$J,VJ,jw,__,qq,C_,N_,Hq,O_,$q,L_,Vq,D_,jJ,jq,U_,B_,M_,Kr,wd,Ad,Jh,zw,F_,Zh,Ww,q_,zJ,H_,zq,$_,Wq,V_,j_,Gq,z_,W_,G_,Kq,K_,Y_,WJ,GJ,Yq,Q_,Qq,X_,J_,Td,Xq,Z_,eC,Vh,tC,nC,KJ,rC,Jq,oC,sC,Zq,iC,eH,tH,nH,aC,lC,ef,rH,tf,cC,nf,oH,sH,iH,aH,YJ,QJ,lH,cH,Gw,uH,XJ,JJ,uC,dC,pC,bd,rf,mC,hC,pH,Sd,mH,ZJ,of,sf,Kw,fC,gC,yC,bC,wC,vC,fH,kC,xC,AC=L(()=>{"use strict";xo();P=require("zod");Ae=P.z.number().int().nonnegative().transform(Il),Cn=P.z.number().int().nonnegative().transform(Il),Er=P.z.string().regex(/^[0-9a-f]{32}$/).transform(e=>e),_l=P.z.uuid().transform(e=>e),Cq=P.z.string().min(1).transform(e=>e),na=P.z.number().int().nonnegative().transform(Il),x_=P.z.number().int().nonnegative().transform(Il),Mw=P.z.number().int().nonnegative().transform(Il),A_=P.z.number().int().nonnegative().transform(Il),Nq=P.z.number().int().positive().transform(Il),Oq=P.z.string().regex(/^[1-9]\d*h$/).transform(e=>e),Ao=H,jh=(e=>(e.Perpetual="perpetual",e))(jh||{}),zh=(e=>(e.Equity="equity",e.Commodity="commodity",e.Index="index",e.Crypto="crypto",e))(zh||{}),Wh=(e=>(e.Long="long",e.Short="short",e))(Wh||{}),ti=(e=>(e.GTC="gtc",e.IOC="ioc",e.FOK="fok",e))(ti||{}),ra=(e=>(e.TakeProfit="tp",e.StopLoss="sl",e))(ra||{}),vd=(e=>(e.Order="order",e.Position="position",e))(vd||{}),Gh=(e=>(e.Pending="pending",e.Confirmed="confirmed",e.Removed="removed",e))(Gh||{}),Fw=(e=>(e.Pending="pending",e.Confirmed="confirmed",e.Removed="removed",e.Failed="failed",e))(Fw||{}),qw=(e=>(e.Transfer="transfer",e.ReferralPayout="referral_payout",e))(qw||{}),Kh=(e=>(e.In="in",e.Out="out",e))(Kh||{}),Yh=(e=>(e.OneSecond="1s",e.OneMinute="1m",e.FiveMinutes="5m",e.FifteenMinutes="15m",e.OneHour="1h",e.FourHours="4h",e.OneDay="1d",e.OneWeek="1w",e))(Yh||{}),T_=(e=>(e.OneHour="1h",e.FourHours="4h",e.OneDay="1d",e.OneWeek="1w",e))(T_||{}),Qh=(e=>(e.Descending="desc",e.Ascending="asc",e))(Qh||{}),S_=P.z.enum(jh),Xh=P.z.enum(zh),ni=P.z.enum(Wh),P_=P.z.enum(ti),Lq=P.z.enum(ra),Dq=P.z.enum(vd),kd=P.z.enum(Gh),xd=P.z.string().transform(e=>e),Uq=P.z.string().min(1).transform(e=>e),Bq=P.z.enum(Kh),Hw=P.z.enum(Yh),$w=P.z.enum(T_),E_=P.z.enum(Qh),Kn=P.z.string().min(1),Cl=P.z.preprocess(e=>e==="0x"||e===""?void 0:e,et.optional()),To=e=>P.z.object({data:P.z.array(e),more:P.z.boolean()}),Vw=P.z.object({asset:Kn,balance:R,value:R}),R_=P.z.array(Vw),Mq=P.z.object({volume_7d:R,taker_volume_7d:R,maker_volume_7d:R,account_maker_share_7d:R,entity_maker_share_7d:R.optional(),entity_id:Nq.optional(),entity_name:P.z.string().min(1).optional()}).transform(e=>({volume7d:e.volume_7d,takerVolume7d:e.taker_volume_7d,makerVolume7d:e.maker_volume_7d,accountMakerShare7d:e.account_maker_share_7d,entityMakerShare7d:e.entity_maker_share_7d,entityId:e.entity_id,entityName:e.entity_name})),I_=Mq,Fq=P.z.object({instrument_id:Ae,symbol:P.z.string().min(1),size:R,entry_price:R,leverage:P.z.number().int().positive(),cross:P.z.boolean(),initial_margin:R,maintenance_margin:R,position_value:R,liquidation_price:R,unrealized_pnl:R,return_on_equity:R,cumulative_funding:R}).transform(e=>({instrumentId:e.instrument_id,symbol:e.symbol,size:e.size,entryPrice:e.entry_price,leverage:e.leverage,cross:e.cross,initialMargin:e.initial_margin,maintenanceMargin:e.maintenance_margin,positionValue:e.position_value,liquidationPrice:e.liquidation_price,unrealizedPnl:e.unrealized_pnl,returnOnEquity:e.return_on_equity,cumulativeFunding:e.cumulative_funding})),$J=P.z.object({totalAccountValue:R,totalInitialMargin:R,totalMaintenanceMargin:R,totalPositionValue:R}),VJ=P.z.object({total_account_value:R,total_initial_margin:R,total_maintenance_margin:R,total_position_value:R}).transform(e=>({totalAccountValue:e.total_account_value,totalInitialMargin:e.total_initial_margin,totalMaintenanceMargin:e.total_maintenance_margin,totalPositionValue:e.total_position_value})),jw=P.z.object({positions:P.z.array(Fq),margin:VJ,withdrawable:R,in_liquidation:P.z.boolean(),timestamp:pe}).transform(e=>({positions:e.positions,margin:e.margin,withdrawable:e.withdrawable,inLiquidation:e.in_liquidation,timestamp:e.timestamp})),__=jw,qq=P.z.object({id:x_,instrument_id:Ae,size:R,funding_rate:R,funding_asset:Kn,funding:R,timestamp:pe}).transform(e=>({id:e.id,instrumentId:e.instrument_id,size:e.size,fundingRate:e.funding_rate,fundingAsset:e.funding_asset,funding:e.funding,timestamp:e.timestamp})),C_=To(qq),N_=P.z.object({id:x_,iid:Ae,sz:R,fr:R,fund:R,fua:Kn,ts:pe}).transform(e=>({id:e.id,instrumentId:e.iid,size:e.sz,fundingRate:e.fr,fundingAsset:e.fua,funding:e.fund,timestamp:e.ts})),Hq=P.z.object({instrument_id:Ae,leverage:P.z.number().int().positive(),cross:P.z.boolean()}).transform(e=>({instrumentId:e.instrument_id,leverage:e.leverage,cross:e.cross})),O_=P.z.array(Hq),$q=P.z.tuple([pe,R]).transform(([e,t])=>({timestamp:e,equity:t})),L_=To($q),Vq=P.z.tuple([pe,R]).transform(([e,t])=>({timestamp:e,pnl:t})),D_=To(Vq),jJ=P.z.number().finite().positive().refine(e=>Number.isInteger(e),"Expected integer").transform(e=>e>Number.MAX_SAFE_INTEGER?Math.floor(e/1e6):e).pipe(pe),jq=P.z.object({proxy:J,label:P.z.string().optional(),expiry:jJ}).transform(e=>({proxy:e.proxy,label:e.label,expiresAt:e.expiry})),U_=P.z.object({address:J,keys:P.z.array(jq)}).transform(e=>({address:e.address,keys:e.keys})),B_=P.z.object({secret:P.z.string().min(1)}),M_=P.z.object({status:P.z.enum(["ok","err"]),error:P.z.string().optional()}),Kr=P.z.string().regex(/^-?\d+(?:\.\d+)?$/).pipe(R),wd=P.z.number().int().nonnegative(),Ad=P.z.object({address:J,fee_rate:Kr}).transform(e=>({address:e.address,feeRate:e.fee_rate})),Jh=P.z.object({address:J,registered:P.z.boolean(),enabled:P.z.boolean(),admission_enabled:P.z.boolean(),max_fee_rate:Kr}).transform(e=>({address:e.address,registered:e.registered,enabled:e.enabled,admissionEnabled:e.admission_enabled,maxFeeRate:e.max_fee_rate})),zw=P.z.object({trader:J,builder:J,max_fee_rate:Kr,approval_version:P.z.number().int().positive(),timestamp:pe,sequence:wd}).transform(e=>({trader:e.trader,builder:e.builder,maxFeeRate:e.max_fee_rate,approvalVersion:e.approval_version,timestamp:e.timestamp,sequence:e.sequence})),F_=P.z.object({data:P.z.array(zw)}),Zh=(e=>(e.Maker="maker",e.Taker="taker",e))(Zh||{}),Ww=P.z.object({earning_id:Cq,trade_id:na,order_id:Cn,instrument_id:Ae,trader:J,buy:P.z.boolean(),price:Kr,quantity:Kr,client_order_id:Er.optional(),side:P.z.enum(Zh),timestamp:pe,sequence:wd,notional:Kr,fee_asset:Kn,fee:Kr,builder_fee:Kr,total_fee:Kr,fee_rate:Kr}).transform(e=>({earningId:e.earning_id,tradeId:e.trade_id,orderId:e.order_id,instrumentId:e.instrument_id,trader:e.trader,side:e.buy?"BUY":"SELL",price:e.price,quantity:e.quantity,...e.client_order_id===void 0?{}:{clientOrderId:e.client_order_id},liquidityRole:e.side,timestamp:e.timestamp,sequence:e.sequence,notional:e.notional,feeAsset:e.fee_asset,fee:e.fee,builderFee:e.builder_fee,totalFee:e.total_fee,feeRate:e.fee_rate})),q_=P.z.object({start_timestamp:pe,end_timestamp:pe,as_of_sequence:wd}),zJ=q_.transform(e=>({start:e.start_timestamp,end:e.end_timestamp,asOfSequence:e.as_of_sequence})),H_=q_.extend({data:P.z.array(Ww),more:P.z.boolean(),cursor:P.z.string().min(1).optional()}).transform(e=>({data:e.data,more:e.more,...e.cursor===void 0?{}:{cursor:e.cursor},snapshot:{start:e.start_timestamp,end:e.end_timestamp,asOfSequence:e.as_of_sequence}})),zq=P.z.object({fee_asset:Kn,fill_count:wd,notional:Kr,builder_fee:Kr}).transform(e=>({feeAsset:e.fee_asset,fillCount:e.fill_count,notional:e.notional,builderFee:e.builder_fee})),$_=q_.extend({data:P.z.array(zq),trader_count:wd,active_approval_count:wd}).transform(e=>({assets:e.data,traderCount:e.trader_count,activeApprovalCount:e.active_approval_count,snapshot:{start:e.start_timestamp,end:e.end_timestamp,asOfSequence:e.as_of_sequence}})),Wq=P.z.object({hash:et,asset:Kn,amount:ss,status:kd,from:J,to:J,confirmations:P.z.number().int().nonnegative(),required_confirmations:P.z.number().int().nonnegative(),created_timestamp:pe,confirmed_timestamp:pe.optional()}).transform(e=>({hash:e.hash,asset:e.asset,amount:e.amount,status:e.status,from:e.from,to:e.to,confirmations:e.confirmations,requiredConfirmations:e.required_confirmations,createdTimestamp:e.created_timestamp,confirmedTimestamp:e.confirmed_timestamp})),V_=To(Wq),j_=P.z.object({hash:Cl,asset:Kn,amount:ss,status:kd}).transform(e=>({hash:e.hash,asset:e.asset,amount:e.amount,status:e.status})),Gq=P.z.object({withdraw_id:Mw,asset:Kn,amount:ss,fee:R,status:xd,to:J,hash:Cl,confirmations:P.z.number().int().nonnegative(),required_confirmations:P.z.number().int().nonnegative(),created_timestamp:pe,confirmed_timestamp:pe.optional()}).transform(e=>({withdrawalId:e.withdraw_id,asset:e.asset,amount:e.amount,fee:e.fee,status:e.status,to:e.to,hash:e.hash,confirmations:e.confirmations,requiredConfirmations:e.required_confirmations,createdTimestamp:e.created_timestamp,confirmedTimestamp:e.confirmed_timestamp})),z_=To(Gq),W_=P.z.object({status:P.z.enum(["ok","err"]),withdraw_id:Mw.optional(),error:P.z.string().optional()}).transform(e=>({status:e.status,withdrawalId:e.withdraw_id,error:e.error})),G_=P.z.object({withdraw_id:Mw,asset:Kn,amount:ss,fee:R,status:xd,to:J,hash:Cl}).transform(e=>({withdrawalId:e.withdraw_id,asset:e.asset,amount:e.amount,fee:e.fee,status:e.status,to:e.to,hash:e.hash})),Kq=P.z.object({transfer_id:A_,type:Uq,asset:Kn,amount:R,direction:Bq,counterparty:J,label:P.z.string().optional(),created_timestamp:pe}).transform(e=>({transferId:e.transfer_id,type:e.type,asset:e.asset,amount:e.amount,direction:e.direction,counterparty:e.counterparty,label:e.label,createdTimestamp:e.created_timestamp})),K_=To(Kq),Y_=P.z.strictObject({status:P.z.literal("ok"),transfer_id:A_}).transform(e=>({status:e.status,transferId:e.transfer_id})),WJ=P.z.object({lowerBound:R,maxLeverage:P.z.number().int().positive()}),GJ=P.z.object({lower_bound:R,max_leverage:P.z.number().int().positive()}).transform(e=>({lowerBound:e.lower_bound,maxLeverage:e.max_leverage})),Yq=P.z.object({instrument_id:Ae,instrument_type:S_,category:Xh,symbol:P.z.string().min(1),base_asset:Kn,quote_asset:Kn,funding_interval:Oq,quantity_decimals:P.z.number().int().nonnegative(),price_decimals:P.z.number().int().nonnegative(),price_bounds:R,liquidation_fee:R,max_order_count:P.z.number().int().positive(),min_notional:R,max_market_notional:R,max_limit_notional:R,max_leverage:P.z.number().int().positive(),isolated_only:P.z.boolean(),risk_tiers:P.z.array(GJ)}).transform(e=>({id:e.instrument_id,category:e.category,symbol:e.symbol,baseAsset:e.base_asset,quoteAsset:e.quote_asset,fundingInterval:e.funding_interval,quantityDecimals:e.quantity_decimals,priceDecimals:e.price_decimals,priceBounds:e.price_bounds,liquidationFee:e.liquidation_fee,maxOrderCount:e.max_order_count,minNotional:e.min_notional,maxMarketNotional:e.max_market_notional,maxLimitNotional:e.max_limit_notional,maxLeverage:e.max_leverage,isolatedOnly:e.isolated_only,riskTiers:e.risk_tiers})),Q_=P.z.array(Yq),Qq=P.z.object({instrument_id:Ae,symbol:P.z.string().min(1),index_price:R,mark_price:R,last_price:R,mid_price:R,open_interest:R,funding_rate:R,next_funding:pe,timestamp:pe.optional()}).transform(e=>({instrumentId:e.instrument_id,symbol:e.symbol,indexPrice:e.index_price,markPrice:e.mark_price,lastPrice:e.last_price,midPrice:e.mid_price,openInterest:e.open_interest,fundingRate:e.funding_rate,nextFunding:e.next_funding,timestamp:e.timestamp})),X_=P.z.array(Qq),J_=P.z.object({iid:Ae,idx:R,mark:R,last:R,mid:R,oi:R,fr:R,nxf:pe}).transform(e=>({instrumentId:e.iid,indexPrice:e.idx,markPrice:e.mark,lastPrice:e.last,midPrice:e.mid,openInterest:e.oi,fundingRate:e.fr,nextFunding:e.nxf})),Td=P.z.tuple([pe,R,R,R,R,R,P.z.number().int().nonnegative()]).transform(([e,t,n,r,o,s,i])=>({timestamp:e,open:t,high:n,low:r,close:o,volume:s,trades:i})),Xq=P.z.object({instrument_id:Ae,symbol:P.z.string().min(1).optional(),volume:R,open_price:R,klines:P.z.array(Td)}).transform(e=>({instrumentId:e.instrument_id,symbol:e.symbol,volume:e.volume,openPrice:e.open_price,klines:e.klines})),Z_=P.z.array(Xq),eC=P.z.object({iid:Ae,vol:R,open:R,klines:P.z.array(Td)}).transform(e=>({instrumentId:e.iid,volume:e.vol,openPrice:e.open,klines:e.klines})),Vh=P.z.tuple([R,R]).transform(([e,t])=>({price:e,quantity:t})),tC=P.z.object({instrument_id:Ae,bids:P.z.array(Vh),asks:P.z.array(Vh),timestamp:pe,sequence:P.z.number().int().nonnegative()}).transform(e=>({instrumentId:e.instrument_id,bids:e.bids,asks:e.asks,timestamp:e.timestamp,sequence:e.sequence})),nC=P.z.object({b:P.z.array(Vh),a:P.z.array(Vh)}).transform(e=>({bids:e.b,asks:e.a})),KJ=P.z.object({instrumentId:Ae,bidPrice:R,bidQuantity:R,askPrice:R,askQuantity:R,timestamp:pe.optional()}),rC=P.z.object({iid:Ae,bp:R,bq:R,ap:R,aq:R}).transform(e=>({instrumentId:e.iid,bidPrice:e.bp,bidQuantity:e.bq,askPrice:e.ap,askQuantity:e.aq})),Jq=P.z.object({trade_id:na,instrument_id:Ae,side:ni,price:R,quantity:R,timestamp:pe,hash:Cl}).transform(e=>({tradeId:e.trade_id,instrumentId:e.instrument_id,side:e.side,price:e.price,quantity:e.quantity,timestamp:e.timestamp,hash:e.hash})),oC=P.z.object({tid:na,iid:Ae,side:ni,p:R,qty:R,ts:pe,hash:Cl}).transform(e=>({tradeId:e.tid,instrumentId:e.iid,side:e.side,price:e.p,quantity:e.qty,timestamp:e.ts,hash:e.hash})),sC=To(Jq),Zq=P.z.object({funding_rate:R,timestamp:pe}).transform(e=>({fundingRate:e.funding_rate,timestamp:e.timestamp})),iC=To(Zq),eH=P.z.object({min_volume_30d:R,taker_fee_rate:R,maker_fee_rate:R}).transform(e=>({minVolume30d:e.min_volume_30d,takerFeeRate:e.taker_fee_rate,makerFeeRate:e.maker_fee_rate})),tH=P.z.object({instrument_type:S_,category:Xh,taker_fee_rate:R,maker_fee_rate:R,tiers:P.z.array(eH)}).transform(e=>({category:e.category,takerFeeRate:e.taker_fee_rate,makerFeeRate:e.maker_fee_rate,tiers:e.tiers})),nH=P.z.object({fee_schedule:P.z.array(tH)}).transform(e=>({feeSchedule:e.fee_schedule})),aC=nH,lC=To(Td),ef=(e=>(e.PositionOpened="position_opened",e.PositionIncreased="position_increased",e.PositionReduced="position_reduced",e.PositionClosed="position_closed",e.LimitOrderCanceled="limit_order_canceled",e.LiquidationWarning="liquidation_warning",e.PositionLiquidated="position_liquidated",e))(ef||{}),rH=P.z.enum(ef),tf=(e=>(e.Market="market",e.Limit="limit",e.TakeProfit="take_profit",e.StopLoss="stop_loss",e))(tf||{}),cC=P.z.enum(tf),nf=(e=>(e.Cross="cross",e.Isolated="isolated",e))(nf||{}),oH=P.z.enum(nf),sH=P.z.object({id:_l,type:P.z.enum(["position_opened","position_increased","position_reduced"]),instrument_id:Ae,side:ni,size:R,avg_price:R,leverage:P.z.number().int().positive(),order_type:cC.optional()}).transform(e=>({id:e.id,type:e.type,instrumentId:e.instrument_id,side:e.side,size:e.size,avgPrice:e.avg_price,leverage:e.leverage,orderType:e.order_type})),iH=P.z.object({id:_l,type:P.z.literal("position_closed"),instrument_id:Ae,side:ni,size:R,avg_price:R,pnl:R,order_type:cC.optional()}).transform(e=>({id:e.id,type:e.type,instrumentId:e.instrument_id,side:e.side,size:e.size,avgPrice:e.avg_price,pnl:e.pnl,orderType:e.order_type})),aH=P.z.object({id:_l,type:P.z.literal("limit_order_canceled"),instrument_id:Ae,side:ni,size:R,price:R}).transform(e=>({id:e.id,type:e.type,instrumentId:e.instrument_id,side:e.side,size:e.size,price:e.price})),YJ=P.z.object({id:_l,type:P.z.literal("liquidation_warning"),margin_type:P.z.literal("isolated"),instrument_id:Ae,mark_price:R,liq_price:R}).transform(e=>({id:e.id,type:e.type,marginType:e.margin_type,instrumentId:e.instrument_id,markPrice:e.mark_price,liquidationPrice:e.liq_price})),QJ=P.z.object({id:_l,type:P.z.literal("liquidation_warning"),margin_type:P.z.literal("cross"),instrument_id:P.z.null(),mark_price:R,affected_instruments:P.z.array(Ae)}).transform(e=>({id:e.id,type:e.type,marginType:e.margin_type,markPrice:e.mark_price,affectedInstruments:e.affected_instruments})),lH=P.z.discriminatedUnion("margin_type",[YJ,QJ]),cH=P.z.object({id:_l,type:P.z.literal("position_liquidated"),instrument_id:Ae,side:ni,size_closed:R,pnl:R.nullable(),margin_type:oH,via_backstop:P.z.boolean()}).transform(e=>({id:e.id,type:e.type,instrumentId:e.instrument_id,side:e.side,sizeClosed:e.size_closed,pnl:e.pnl,marginType:e.margin_type,viaBackstop:e.via_backstop})),Gw=P.z.discriminatedUnion("type",[sH,iH,aH,lH,cH]),uH=P.z.object({notification:Gw,read_at:pe.nullable(),ts:pe}).transform(e=>({notification:e.notification,readAt:e.read_at,timestamp:e.ts})),XJ=P.z.object({notification:P.z.object({type:rH})}),JJ=P.z.array(P.z.unknown()).transform((e,t)=>{let n=[];return e.forEach((r,o)=>{if(!XJ.safeParse(r).success)return;let s=uH.safeParse(r);if(s.success){n.push(s.data);return}for(let i of s.error.issues)t.addIssue({...i,path:[o,...i.path]})}),n}),uC=P.z.object({items:JJ,unread:P.z.number().int().nonnegative(),durable_source_seq:P.z.number().int().nonnegative(),has_more:P.z.boolean(),next_cursor:P.z.string().nullable()}),dC=P.z.object({unread:P.z.number().int().nonnegative()}),pC=P.z.object({status:P.z.enum(["ok","err"]),error:P.z.string().optional()}),bd=P.z.string().regex(/^-?\d+(?:\.\d+)?$/).pipe(R);rf=(e=>(e.Accepted="accepted",e.Open="open",e.Partial="partial",e.Filled="filled",e.Cancelled="cancelled",e.AutoCancelled="auto_cancelled",e.PostOnlyRejected="post_only_rejected",e.FokUnfilled="fok_unfilled",e.IocNoFill="ioc_no_fill",e.IocExpired="ioc_expired",e.StpCancelled="stp_cancelled",e.ZeroQuantity="zero_quantity",e.DuplicateOrder="duplicate_order",e.OrderNotFound="order_not_found",e.ReduceOnlyInvalid="reduce_only_invalid",e.ReduceOnlyExpired="reduce_only_expired",e.OrderExpired="order_expired",e.Untriggered="untriggered",e.Armed="armed",e.Triggered="triggered",e.ParentCancelled="parent_cancelled",e.PositionClosed="position_closed",e.PositionFlipped="position_flipped",e.ReduceOnlyInvalidAtTrigger="reduce_only_invalid_at_trigger",e.Expired="expired",e))(rf||{}),mC=P.z.object({kind:Lq,scope:Dq,trp:R,parent_oid:Cn.optional(),armed_qty:R.optional(),slip_bps:P.z.number().int().nonnegative().optional()}).transform(e=>({kind:e.kind,scope:e.scope,triggerPrice:e.trp,parentOrderId:e.parent_oid,armedQuantity:e.armed_qty,slippageBps:e.slip_bps})),hC=P.z.enum(rf),pH=P.z.enum(["ok","err"]),Sd=(e=>(e.OrderUnknown="order_unknown",e.OrderNotInOrderbook="order_not_in_orderbook",e.OrderInFlight="order_in_flight",e.OrderNotPendingEngine="order_not_pending_engine",e.OrderNotFound="order_not_found",e))(Sd||{}),mH=P.z.string().min(1).transform(e=>e),ZJ=P.z.string().min(1).optional().transform(hH),of=P.z.discriminatedUnion("status",[P.z.object({status:P.z.literal("ok")}),P.z.object({status:P.z.literal("err"),error:ZJ})]),sf=P.z.object({status:pH,oid:Cn.optional(),coid:Er.optional(),error:P.z.string().optional(),builder:Ad.optional()}).transform((e,t)=>e.status==="err"?{status:"err",error:hH(e.error),clientOrderId:e.coid}:e.oid===void 0?(t.addIssue({code:"custom",message:"Expected Perps place order acknowledgement order id."}),P.z.NEVER):{status:"ok",orderId:e.oid,clientOrderId:e.coid,...e.builder===void 0?{}:{builder:e.builder}}),Kw=P.z.discriminatedUnion("status",[P.z.object({status:P.z.literal("ok"),oid:Cn.optional(),coid:Er.optional()}),P.z.object({status:P.z.literal("err"),error:mH,oid:Cn.optional(),coid:Er.optional()})]).transform(e=>e.status==="err"?{status:"err",error:e.error,orderId:e.oid,clientOrderId:e.coid}:{status:"ok",orderId:e.oid,clientOrderId:e.coid}),fC=P.z.object({status:P.z.literal("ok")}),gC=P.z.object({status:P.z.literal("ok"),instrument_id:Ae,leverage:P.z.number().int().positive(),cross:P.z.boolean()}).transform(e=>({status:e.status,instrumentId:e.instrument_id,leverage:e.leverage,crossMargin:e.cross}));yC=P.z.object({order_id:Cn,instrument_id:Ae,buy:P.z.boolean(),price:R,quantity:R,tif:P_,post_only:P.z.boolean(),ro:P.z.boolean(),status:hC,resting_quantity:R,filled_quantity:R,created_timestamp:pe,updated_timestamp:pe,client_order_id:P.z.string().optional(),tpsl:mC.nullish(),builder:Ad.optional()}).transform(e=>({id:e.order_id,instrumentId:e.instrument_id,side:e.buy?"BUY":"SELL",price:e.price,quantity:e.quantity,timeInForce:e.tif,postOnly:e.post_only,reduceOnly:e.ro,status:e.status,restingQuantity:e.resting_quantity,filledQuantity:e.filled_quantity,createdTimestamp:e.created_timestamp,updatedTimestamp:e.updated_timestamp,clientOrderId:e.client_order_id,tpSl:e.tpsl??void 0,...e.builder===void 0?{}:{builder:e.builder}})),bC=P.z.array(yC),wC=P.z.array(yC),vC=P.z.object({oid:Cn,iid:Ae,buy:P.z.boolean(),p:R,qty:R,tif:P_,po:P.z.boolean(),ro:P.z.boolean(),status:hC,rest:R,fill:R,cts:pe,uts:pe,coid:P.z.string().optional(),tpsl:mC.nullish(),builder:Ad.optional()}).transform(e=>({id:e.oid,instrumentId:e.iid,side:e.buy?"BUY":"SELL",price:e.p,quantity:e.qty,timeInForce:e.tif,postOnly:e.po,reduceOnly:e.ro,status:e.status,restingQuantity:e.rest,filledQuantity:e.fill,createdTimestamp:e.cts,updatedTimestamp:e.uts,clientOrderId:e.coid,tpSl:e.tpsl??void 0,...e.builder===void 0?{}:{builder:e.builder}})),fH=P.z.object({trade_id:na,order_id:Cn,instrument_id:Ae,side:ni,price:R,quantity:R,taker:P.z.boolean(),fee:bd,builder_fee:bd.optional(),total_fee:bd.optional(),builder:Ad.optional(),fee_asset:Kn,previous_size:R,previous_entry_price:R,pnl:R,liquidation:P.z.boolean(),timestamp:pe,hash:Cl}).transform(e=>({tradeId:e.trade_id,orderId:e.order_id,instrumentId:e.instrument_id,side:e.side,price:e.price,quantity:e.quantity,taker:e.taker,fee:e.fee,builderFee:e.builder_fee??"0",totalFee:e.total_fee??dH(e.fee,e.builder_fee??"0"),...e.builder===void 0?{}:{builder:e.builder},feeAsset:e.fee_asset,previousSize:e.previous_size,previousEntryPrice:e.previous_entry_price,pnl:e.pnl,liquidation:e.liquidation,timestamp:e.timestamp,hash:e.hash})),kC=To(fH),xC=P.z.object({tid:na,oid:Cn,iid:Ae,side:ni,p:R,qty:R,taker:P.z.boolean(),fee:bd,builder_fee:bd.optional(),total_fee:bd.optional(),builder:Ad.optional(),fea:Kn,psz:R,pep:R,pnl:R,liq:P.z.boolean(),ts:pe,coid:P.z.string().optional()}).transform(e=>({tradeId:e.tid,orderId:e.oid,instrumentId:e.iid,side:e.side,price:e.p,quantity:e.qty,taker:e.taker,fee:e.fee,builderFee:e.builder_fee??"0",totalFee:e.total_fee??dH(e.fee,e.builder_fee??"0"),...e.builder===void 0?{}:{builder:e.builder},feeAsset:e.fea,previousSize:e.psz,previousEntryPrice:e.pep,pnl:e.pnl,liquidation:e.liq,timestamp:e.ts,clientOrderId:e.coid}))});function oa(e,t,n){return kZ.extend({ch:T.z.literal(t),data:n}).transform(r=>{let o=r;return{type:e,channel:o.ch,timestamp:o.ts,sequence:o.sq,payload:o.data}})}function LH(e){let[,t]=e.split("::");return Ae.parse(Number(t))}function OZ(e){let[,,t]=e.split("::");return t}function FH(e){let t={timestamp:e.ts,seq:e.seq,dropped:e.dropped,type:e.snapshot?"subscribe":"update",payload:e.payload};switch(e.channel){case"price.crypto":return BZ.safeParse({...t,topic:"prices.crypto"}).data;case"price.crypto.twap":return MZ.safeParse({...t,topic:"prices.crypto.twap"}).data;case"price.equity":return FZ.safeParse({...t,topic:"prices.equity"}).data}}function ree(e){let t=BigInt(e),n=t<0n,r=n?-t:t,o=r/yH,s=(r%yH).toString().padStart(18,"0").replace(/0+$/,"");return`${n?"-":""}${o}${s===""?"":`.${s}`}`}function $H(e){return see.extend({window_s:T.z.literal(e)}).transform(t=>({symbol:t.symbol,timestamp:t.timestamp,value:t.full_accuracy_value,windowSeconds:t.window_s}))}var T,af,bH,eZ,gH,Yw,tZ,wH,nZ,vH,kH,xH,AH,TH,SH,PH,EH,rZ,oZ,sZ,iZ,I_e,__e,RH,IH,_H,aZ,lZ,cZ,uZ,dZ,pZ,mZ,hZ,ri,fZ,gZ,yZ,bZ,wZ,vZ,CH,kZ,xZ,AZ,TZ,SZ,PZ,EZ,RZ,IZ,_Z,NH,CZ,NZ,OH,Ed,Rd,Nl,DH,UH,LZ,BH,TC,MH,DZ,UZ,Pd,BZ,MZ,FZ,qZ,HZ,$Z,VZ,jZ,qH,zZ,WZ,HH,GZ,KZ,YZ,QZ,XZ,JZ,ZZ,eee,tee,nee,yH,oee,see,VH,jH,C_e,iee,aee,lee,cee,uee,dee,zH,pee,mee,hee,fee,WH,gee,GH,Qw=L(()=>{"use strict";$h();AC();xo();T=require("zod"),af=T.z.preprocess(e=>typeof e=="string"?e.toUpperCase():e,Nt),bH=(e=>(e.Live="LIVE",e.Matched="MATCHED",e.Delayed="DELAYED",e.Unmatched="UNMATCHED",e.Canceled="CANCELED",e))(bH||{}),eZ=T.z.enum(bH),gH=T.z.object({price:R,size:R}),Yw=T.z.string().regex(/^\d+$/).transform(e=>new Date(Number(e)*1e3).toISOString()),tZ=T.z.string().regex(/^\d+$/).transform(e=>e==="0"?void 0:new Date(Number(e)*1e3).toISOString()),wH=T.z.object({event_type:T.z.literal("book"),market:xe,asset_id:Me,bids:T.z.array(gH),asks:T.z.array(gH),hash:T.z.string().nullish(),timestamp:Pr.nullish(),min_order_size:dn,tick_size:dn,neg_risk:T.z.boolean().nullish(),last_trade_price:dn}).transform(({event_type:e,asset_id:t,min_order_size:n,tick_size:r,neg_risk:o,last_trade_price:s,...i})=>({topic:"market",type:e,payload:{...i,conditionId:i.market,market:i.market,assetId:t,tokenId:t,minOrderSize:n,tickSize:r,negRisk:o,lastTradePrice:s}})),nZ=T.z.object({asset_id:Me,price:R,size:R,side:af,hash:T.z.string().nullish(),best_bid:dn,best_ask:dn}).transform(({asset_id:e,best_bid:t,best_ask:n,...r})=>({...r,assetId:e,tokenId:e,bestBid:t,bestAsk:n})),vH=T.z.object({event_type:T.z.literal("price_change"),market:xe,price_changes:T.z.array(nZ),timestamp:Pr.nullish()}).transform(({event_type:e,price_changes:t,...n})=>({topic:"market",type:e,payload:{...n,conditionId:n.market,market:n.market,priceChanges:t}})),kH=T.z.object({event_type:T.z.literal("last_trade_price"),market:xe,asset_id:Me,price:R,size:dn,fee_rate_bps:dn,side:af,timestamp:Pr.nullish(),transaction_hash:T.z.string().nullish()}).transform(({event_type:e,asset_id:t,fee_rate_bps:n,transaction_hash:r,...o})=>({topic:"market",type:e,payload:{...o,conditionId:o.market,market:o.market,assetId:t,tokenId:t,feeRateBps:n,transactionHash:r}})),xH=T.z.object({event_type:T.z.literal("tick_size_change"),market:xe,asset_id:Me,old_tick_size:dn,new_tick_size:R,timestamp:Pr.nullish()}).transform(({event_type:e,asset_id:t,old_tick_size:n,new_tick_size:r,...o})=>({topic:"market",type:e,payload:{...o,conditionId:o.market,market:o.market,assetId:t,tokenId:t,oldTickSize:n,newTickSize:r}})),AH=T.z.object({event_type:T.z.literal("best_bid_ask"),market:xe,asset_id:Me,best_bid:dn,best_ask:dn,spread:dn,timestamp:Pr.nullish()}).transform(({event_type:e,asset_id:t,best_bid:n,best_ask:r,...o})=>({topic:"market",type:e,payload:{...o,conditionId:o.market,market:o.market,assetId:t,tokenId:t,bestBid:n,bestAsk:r}})),TH=T.z.object({id:T.z.string(),ticker:T.z.string().nullish(),slug:T.z.string().nullish(),title:T.z.string().nullish(),description:T.z.string().nullish()}),SH=T.z.object({event_type:T.z.literal("new_market"),id:T.z.string(),question:T.z.string().nullish(),market:T.z.string(),slug:T.z.string().nullish(),description:T.z.string().nullish(),assets_ids:T.z.array(Me).nullish(),outcomes:T.z.array(T.z.string()).nullish(),event_message:TH.nullish(),timestamp:Pr.nullish(),tags:T.z.array(T.z.string()).nullish(),condition_id:xe.nullish(),active:T.z.boolean().nullish(),clob_token_ids:T.z.array(T.z.string()).nullish(),sports_market_type:T.z.string().nullish(),line:dn,game_start_time:un.nullish(),order_price_min_tick_size:dn,group_item_title:T.z.string().nullish(),taker_base_fee:dn,fees_enabled:T.z.boolean().nullish(),fee_schedule:T.z.unknown().nullish()}).transform(({event_type:e,assets_ids:t,event_message:n,condition_id:r,clob_token_ids:o,sports_market_type:s,game_start_time:i,order_price_min_tick_size:a,group_item_title:l,taker_base_fee:c,fees_enabled:u,fee_schedule:d,...p})=>({topic:"market",type:e,payload:{...p,assetIds:t,tokenIds:t,eventMessage:n,conditionId:r,clobTokenIds:o,sportsMarketType:s,gameStartTime:i,orderPriceMinTickSize:a,groupItemTitle:l,takerBaseFee:c,feesEnabled:u,feeSchedule:d}})),PH=T.z.object({event_type:T.z.literal("market_resolved"),id:T.z.string(),market:xe,assets_ids:T.z.array(Me).nullish(),winning_asset_id:Me.nullish(),winning_outcome:T.z.string().nullish(),event_message:TH.nullish(),timestamp:Pr.nullish(),tags:T.z.array(T.z.string()).nullish()}).transform(({event_type:e,assets_ids:t,winning_asset_id:n,winning_outcome:r,event_message:o,...s})=>({topic:"market",type:e,payload:{...s,conditionId:s.market,market:s.market,assetIds:t,tokenIds:t,winningAssetId:n,winningTokenId:n,winningOutcome:r,eventMessage:o}})),EH=(e=>(e.Placement="PLACEMENT",e.Update="UPDATE",e.Cancellation="CANCELLATION",e))(EH||{}),rZ=T.z.enum(EH),oZ=T.z.object({event_type:T.z.literal("order"),id:T.z.string(),owner:T.z.string(),market:xe,asset_id:Me,side:af,order_owner:T.z.string().nullish(),original_size:R,size_matched:R,price:R,associate_trades:T.z.array(T.z.string()).nullish(),outcome:T.z.string().nullish(),type:rZ,created_at:Yw.nullish(),expiration:tZ.nullish(),order_type:Oh.nullish(),status:eZ.nullish(),maker_address:T.z.string().nullish(),timestamp:Pr}).transform(({event_type:e,type:t,asset_id:n,order_owner:r,original_size:o,size_matched:s,associate_trades:i,created_at:a,expiration:l,order_type:c,maker_address:u,...d})=>({topic:"user",type:e,payload:{...d,conditionId:d.market,market:d.market,orderEventType:t,assetId:n,tokenId:n,orderOwner:r,originalSize:o,sizeMatched:s,associateTrades:i,createdAt:a,expiresAt:l,orderType:c,makerAddress:u}})),sZ=T.z.object({order_id:T.z.string(),owner:T.z.string(),maker_address:T.z.string().nullish(),matched_amount:R,price:R,fee_rate_bps:dn,asset_id:Me,outcome:T.z.string().nullish(),outcome_index:T.z.number().int().nullish(),side:af}).transform(({order_id:e,maker_address:t,matched_amount:n,fee_rate_bps:r,asset_id:o,outcome_index:s,...i})=>({...i,orderId:e,makerAddress:t,matchedAmount:n,feeRateBps:r,assetId:o,tokenId:o,outcomeIndex:s})),iZ=T.z.object({event_type:T.z.literal("trade"),type:T.z.literal("TRADE"),id:T.z.string(),taker_order_id:T.z.string(),market:xe,asset_id:Me,side:af,size:R,fee_rate_bps:dn,price:R,status:Lh,match_time:Yw.nullish(),matchtime:Yw.nullish(),last_update:Yw.nullish(),outcome:T.z.string().nullish(),owner:T.z.string(),trade_owner:T.z.string().nullish(),maker_address:T.z.string().nullish(),transaction_hash:T.z.string().nullish(),bucket_index:T.z.number().int().nullish(),maker_orders:T.z.array(sZ).nullish(),trader_side:T.z.union([T.z.literal("TAKER"),T.z.literal("MAKER")]).nullish(),timestamp:Pr}).transform(({event_type:e,type:t,taker_order_id:n,asset_id:r,fee_rate_bps:o,match_time:s,matchtime:i,last_update:a,trade_owner:l,maker_address:c,transaction_hash:u,bucket_index:d,maker_orders:p,trader_side:m,...g})=>({topic:"user",type:e,payload:{...g,conditionId:g.market,market:g.market,takerOrderId:n,assetId:r,tokenId:r,feeRateBps:o,matchedAt:s??i,updatedAt:a,tradeOwner:l,makerAddress:c,transactionHash:u,bucketIndex:d,makerOrders:p,traderSide:m}})),I_e=T.z.discriminatedUnion("event_type",[wH,vH,kH,xH]),__e=T.z.discriminatedUnion("event_type",[AH,SH,PH]),RH=T.z.discriminatedUnion("event_type",[wH,vH,kH,xH,AH,SH,PH]),IH=T.z.discriminatedUnion("event_type",[oZ,iZ]),_H=T.z.number().int().nonnegative(),aZ=T.z.string().regex(/^trades::\d+$/),lZ=T.z.string().regex(/^bbo::\d+$/),cZ=T.z.string().regex(/^book::\d+$/),uZ=T.z.string().regex(/^tickers::(all|\d+)$/),dZ=T.z.string().regex(/^statistics::(all|\d+)$/),pZ=T.z.string().regex(/^klines::\d+::(1m|5m|15m|1h|4h|1d|1w)$/),mZ=T.z.string().regex(/^tpsl::\d+$/),hZ=T.z.enum(["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications"]),ri=T.z.object({ts:pe,sq:_H}),fZ=ri.extend({ch:aZ,data:T.z.array(oC)}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.trades",type:"trade",channel:e,timestamp:t,sequence:n,payload:r})),gZ=ri.extend({ch:lZ,data:rC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.bbo",type:"bbo",channel:e,timestamp:t,sequence:n,payload:r})),yZ=ri.extend({ch:cZ,data:nC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.book",type:"book",channel:e,timestamp:t,sequence:n,payload:{instrumentId:LH(e),...r}})),bZ=ri.extend({ch:uZ,data:J_}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.tickers",type:"ticker",channel:e,timestamp:t,sequence:n,payload:r})),wZ=ri.extend({ch:dZ,data:eC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.statistics",type:"statistic",channel:e,timestamp:t,sequence:n,payload:r})),vZ=ri.extend({ch:pZ,data:T.z.array(Td)}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.candles",type:"candle",channel:e,timestamp:t,sequence:n,payload:{instrumentId:LH(e),interval:OZ(e),candles:r}})),CH=T.z.union([fZ,gZ,yZ,bZ,wZ,vZ]),kZ=ri.extend({ch:hZ});xZ=oa("balance","balances",Vw),AZ=oa("portfolio","portfolio",jw),TZ=oa("order","orders",vC),SZ=oa("fill","fills",T.z.array(xC)),PZ=ri.extend({ch:T.z.literal("builderFills"),data:T.z.array(Ww)}).transform(({ch:e,ts:t,sq:n,data:r})=>({type:"builderFill",channel:e,timestamp:t,sequence:n,payload:r})),EZ=oa("funding","funding",N_),RZ=oa("deposit","deposits",j_),IZ=oa("withdrawal","withdrawals",G_),_Z=oa("notification","notifications",Gw),NH=T.z.object({ch:T.z.literal("notifications"),ts:pe,sq:_H,type:T.z.literal("resync")}).transform(({ch:e,ts:t,sq:n})=>({type:"resync",channel:e,timestamp:t,sequence:n})),CZ=T.z.object({oid:Cn,st:T.z.enum(["untriggered","armed","cancelled","expired"]),reason:T.z.string().optional()}),NZ=ri.extend({ch:mZ,data:CZ.transform(e=>({orderId:e.oid,status:e.st,reason:e.reason}))}).transform(({ch:e,ts:t,sq:n,data:r})=>({type:"tpsl",channel:e,timestamp:t,sequence:n,payload:r})),OH=T.z.union([xZ,AZ,TZ,SZ,PZ,EZ,RZ,IZ,_Z,NZ]);Ed=(e=>(e.BadOp="bad_op",e.BadChannel="bad_channel",e.BadFilter="bad_filter",e.SubscriptionLimit="sub_limit",e.RateLimited="rate_limited",e.AuthRequired="auth_required",e.AuthUnavailable="auth_unavailable",e.AuthExpired="auth_expired",e.AuthAttempts="auth_attempts",e.AuthInvalid="auth_invalid",e))(Ed||{}),Rd=(e=>(e.Crypto="price.crypto",e.Twap="price.crypto.twap",e.Equity="price.equity",e))(Rd||{}),Nl=(e=>(e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.Pong="pong",e.Authed="authed",e.Error="error",e))(Nl||{}),DH=T.z.object({op:T.z.enum(Nl),channel:T.z.string().optional(),rid:T.z.string().optional(),code:T.z.string().transform(e=>e).optional()}),UH=T.z.object({v:T.z.literal(1),channel:T.z.enum(Rd),seq:T.z.number().int().nonnegative(),ts:pe,snapshot:T.z.boolean().optional(),dropped:T.z.number().int().nonnegative().optional(),payload:T.z.unknown()}),LZ=T.z.object({timestamp:pe,value:H,full_accuracy_value:R}).transform(({timestamp:e,full_accuracy_value:t})=>({timestamp:e,value:t})),BH=T.z.object({symbol:T.z.string(),timestamp:pe,value:H,full_accuracy_value:R,received_at:pe.optional(),is_carried_forward:T.z.boolean().optional()}).transform(({symbol:e,timestamp:t,full_accuracy_value:n,received_at:r,is_carried_forward:o})=>({symbol:e,timestamp:t,value:n,receivedAt:r,isCarriedForward:o})),TC=T.z.object({symbol:T.z.string(),data:T.z.array(LZ)}),MH=T.z.literal(60),DZ=T.z.object({symbol:T.z.string(),timestamp:pe,value:H,full_accuracy_value:R,window_seconds:MH}).transform(({symbol:e,timestamp:t,full_accuracy_value:n,window_seconds:r})=>({symbol:e,timestamp:t,value:n,windowSeconds:r})),UZ=TC.extend({window_seconds:MH}).transform(({symbol:e,data:t,window_seconds:n})=>({symbol:e,data:t,windowSeconds:n})),Pd=T.z.object({timestamp:pe,seq:T.z.number().optional(),dropped:T.z.number().optional()}),BZ=T.z.union([Pd.extend({topic:T.z.literal("prices.crypto"),type:T.z.literal("update"),payload:BH}),Pd.extend({topic:T.z.literal("prices.crypto"),type:T.z.literal("subscribe"),payload:TC})]),MZ=T.z.union([Pd.extend({topic:T.z.literal("prices.crypto.twap"),type:T.z.literal("update"),payload:DZ}),Pd.extend({topic:T.z.literal("prices.crypto.twap"),type:T.z.literal("subscribe"),payload:UZ})]),FZ=T.z.union([Pd.extend({topic:T.z.literal("prices.equity"),type:T.z.literal("update"),payload:BH}),Pd.extend({topic:T.z.literal("prices.equity"),type:T.z.literal("subscribe"),payload:TC})]);qZ=T.z.object({id:T.z.string(),body:T.z.string().nullish(),parentEntityType:Js.nullish(),parentEntityID:T.z.number().int().nullish(),parentCommentID:T.z.string().nullish(),userAddress:T.z.string().nullish(),replyAddress:T.z.string().nullish(),createdAt:T.z.string().nullish(),updatedAt:T.z.string().nullish(),media:T.z.array(Bw).nullish(),profile:Rl.nullish(),reactions:T.z.array(yd).nullish(),reportCount:T.z.number().int().nullish(),reactionCount:T.z.number().int().nullish(),tradeAsset:T.z.string().nullish()}),HZ=T.z.object({topic:T.z.literal("comments"),type:T.z.literal("comment_created"),timestamp:pe,payload:qh}),$Z=T.z.object({topic:T.z.literal("comments"),type:T.z.literal("comment_removed"),timestamp:pe,payload:qZ}),VZ=T.z.object({topic:T.z.literal("comments"),type:T.z.literal("reaction_created"),timestamp:pe,payload:yd}),jZ=T.z.object({topic:T.z.literal("comments"),type:T.z.literal("reaction_removed"),timestamp:pe,payload:yd}),qH=T.z.object({symbol:T.z.string(),timestamp:pe,value:H}),zZ="prices.crypto.binance",WZ="prices.crypto.chainlink",HH="prices.crypto.chainlink.twap",GZ=T.z.literal("crypto_prices"),KZ=T.z.literal("crypto_prices_chainlink"),YZ=T.z.literal("crypto_prices_twap_thirty"),QZ=T.z.literal("crypto_prices_twap_sixty"),XZ=GZ.transform(()=>zZ),JZ=KZ.transform(()=>WZ),ZZ=YZ.transform(()=>HH),eee=QZ.transform(()=>HH),tee=T.z.object({topic:XZ,type:T.z.literal("update"),timestamp:pe,payload:qH}),nee=T.z.object({topic:JZ,type:T.z.literal("update"),timestamp:pe,payload:qH}),yH=1000000000000000000n;oee=T.z.string().regex(/^-?\d+$/).transform(ree),see=T.z.object({symbol:T.z.string(),value:H,full_accuracy_value:oee,timestamp:pe});VH=T.z.object({topic:ZZ,type:T.z.literal("update"),timestamp:pe,payload:$H(30)}),jH=T.z.object({topic:eee,type:T.z.literal("update"),timestamp:pe,payload:$H(60)}),C_e=T.z.union([VH,jH]),iee=T.z.discriminatedUnion("topic",[tee,nee,VH,jH]),aee=T.z.object({symbol:T.z.string(),value:H,full_accuracy_value:R.nullish(),timestamp:pe,received_at:pe.nullish(),is_carried_forward:T.z.boolean().nullish()}).transform(({full_accuracy_value:e,received_at:t,is_carried_forward:n,value:r,...o})=>({...o,value:e??r,receivedAt:t,isCarriedForward:n})),lee=T.z.object({timestamp:T.z.number(),value:H}),cee=T.z.object({symbol:T.z.string(),data:T.z.array(lee)}),uee=T.z.literal("equity_prices"),dee="prices.equity.pyth",zH=uee.transform(()=>dee),pee=T.z.object({topic:zH,type:T.z.literal("update"),timestamp:pe,payload:aee}),mee=T.z.object({topic:zH,type:T.z.literal("subscribe"),timestamp:pe,payload:cee}),hee=T.z.discriminatedUnion("type",[pee,mee]),fee=T.z.discriminatedUnion("type",[HZ,$Z,VZ,jZ]),WH=T.z.discriminatedUnion("topic",[fee,iee,hee]),gee=T.z.object({gameId:T.z.number().int(),sportradarGameId:T.z.string().nullish(),slug:T.z.string().nullish(),leagueAbbreviation:T.z.string(),homeTeam:T.z.string().nullish(),awayTeam:T.z.string().nullish(),status:T.z.string(),live:T.z.boolean(),ended:T.z.boolean(),score:T.z.string(),period:T.z.string().nullish(),elapsed:T.z.string().nullish(),finishedTimestamp:un.nullish(),finished_timestamp:un.nullish(),turn:T.z.string().nullish()}).transform(({finishedTimestamp:e,finished_timestamp:t,...n})=>({...n,finishedAt:e??t})),GH=gee.transform(e=>({topic:"sports",type:"sport_result",payload:e}))});function bee(e){let t=YH(e.issues);return t.length===0?"It was not possible to determine a more specific reason.":["Fix the following issues:",KH(t)].join(`
|
|
5
5
|
`)}function wee(e,t){let n=YH(e.issues);return n.length===0?["Received an incompatible API response.",`Endpoint: ${t.endpoint}`,"This usually means the API response shape changed in a breaking way or the SDK is outdated.","It was not possible to determine a more specific reason."].join(`
|
|
6
6
|
`):["Received an incompatible API response.",`Endpoint: ${t.endpoint}`,"This usually means the API response shape changed in a breaking way or the SDK is outdated.","Fix the following issues:",KH(n)].join(`
|
|
7
7
|
`)}function KH(e){return e.map(t=>t.path===null?`- ${t.message}`:`- ${t.path}: ${t.message}`).join(`
|
|
8
|
-
`)}function YH(e){return QH(e).slice(0,99)}function QH(e,t=[]){let n=e.flatMap(r=>{let o=[...t,...r.path];return r.code==="invalid_union"?r.errors.flatMap(s=>QH(s,o)):[{code:r.code,message:r.message,path:o.length===0?null:xee(o)}]});return vee(n)}function vee(e){let t=new Set,n=[];for(let r of e){let o=`${r.code}:${r.path??""}:${r.message}`;t.has(o)||(t.add(o),n.push(r))}return n.sort(kee)}function kee(e,t){return e.path===null&&t.path!==null?-1:e.path!==null&&t.path===null?1:(e.path??"").localeCompare(t.path??"")}function xee(e){return e.reduce((t,n)=>typeof n=="number"?`${t}[${n.toString()}]`:typeof n!="string"?t:n.includes('"')?`${t}["${n.replaceAll('"','\\"')}"]`:yee.test(n)?t.length===0?n:`${t}.${n}`:`${t}["${n}"]`,"")}function B(...e){return{isError(t){return e.some(n=>t instanceof n)}}}var yee,E,Ol,C,_,SC,Yr,PC,O,$,tt,Xw,en,bt,So,lf,Jw,ue,Zw=L(()=>{"use strict";Qw();Tl();yee=/^[$A-Z_a-z][$\w]*$/;E=class XH extends Ct{name="UserInputError";constructor(t,n={}){super(t,n)}static fromZodError(t){return new XH(bee(t),{cause:t})}},Ol=class extends Ct{name="PaginationLimitError";constructor(e,t={}){super(e,t)}},C=class JH extends Ct{name="UnexpectedResponseError";constructor(t,n={}){super(t,n)}static fromZodError(t,n){return new JH(wee(t,n),{cause:t})}},_=class ZH extends Ct{name="TransportError";constructor(t,n={}){super(t,n)}static fromError(t){return new ZH(t instanceof Error?t.message:"Request failed",{cause:t})}},SC=(e=>(e[e.NormalClosure=1e3]="NormalClosure",e[e.GoingAway=1001]="GoingAway",e[e.ProtocolError=1002]="ProtocolError",e[e.UnsupportedData=1003]="UnsupportedData",e[e.NoStatusReceived=1005]="NoStatusReceived",e[e.AbnormalClosure=1006]="AbnormalClosure",e[e.InvalidFramePayload=1007]="InvalidFramePayload",e[e.PolicyViolation=1008]="PolicyViolation",e[e.MessageTooBig=1009]="MessageTooBig",e[e.InternalError=1011]="InternalError",e[e.ServiceRestart=1012]="ServiceRestart",e[e.TryAgainLater=1013]="TryAgainLater",e))(SC||{}),Yr=class extends Ct{name="ConnectionLostError";code;reason;constructor(e,t){super(e,t),this.code=t.code,this.reason=t.reason}},PC=(e=>(e.RESTARTING="restarting",e.POST_ONLY="post_only",e))(PC||{}),O=class extends Ct{name="RequestRejectedError";status;code;retryAfter;restriction;constructor(e,t){super(e,t),this.status=t.status,this.code=t.code,this.retryAfter=t.retryAfter,this.restriction=t.restriction}},$=class extends Ct{name="RateLimitError";retryAfter;rateLimit;constructor(e,t={}){super(e,t),this.retryAfter=t.retryAfter,this.rateLimit=t.rateLimit}},tt=class extends Ct{name="TimeoutError";constructor(e,t={}){super(e,t)}},Xw=class e3 extends Ct{name="OperationAbortedError";constructor(t,n={}){super(t,n)}static fromReason(t){return new e3("Operation was aborted.",{cause:t})}},en=class extends Ct{name="TransactionFailedError";constructor(e,t={}){super(e,t)}},bt=class t3 extends Ct{name="CancelledSigningError";constructor(t,n={}){super(t,n)}static fromError(t){return new t3(t.message,{cause:t})}},So=class extends Ct{name="InsufficientLiquidityError";constructor(e,t={}){super(e,t)}},lf=class extends Ct{name="AutoCancelDailyLimitError";constructor(e,t={}){super(e,t)}},Jw=class extends Ct{name="PerpsCancelRetryError";results;pendingIndexes;constructor(e,t){super(e,t),this.results=[...t.results],this.pendingIndexes=[...t.pendingIndexes]}},ue=class n3 extends Ct{name="SigningError";constructor(t,n={}){super(t,n)}static fromError(t,n){let r=n??(t instanceof Error?t.message:"Signing failed");return new n3(r,{cause:t})}}});var cf=L(()=>{"use strict";xo()});var o3,Rr,EC,RC=L(()=>{"use strict";o3=require("zod"),Rr=(e=>(e[e.EOA=0]="EOA",e[e.POLY_PROXY=1]="POLY_PROXY",e[e.POLY_GNOSIS_SAFE=2]="POLY_GNOSIS_SAFE",e[e.POLY_1271=3]="POLY_1271",e))(Rr||{}),EC=o3.z.enum(Rr)});function e0(e){return A.z.object({count:A.z.number(),data:A.z.array(e),limit:A.z.number(),next_cursor:A.z.string()}).transform(({next_cursor:t,...n})=>({...n,nextCursor:t}))}function is(e,t){return A.z.object({id:a_,owner:os,payload:t,timestamp:Yee,type:A.z.literal(e)})}function fte(e){return e.success&&e.errorMsg===""&&e.orderID!==""&&wte(e.status)}function gte(e){switch(e){case"live":return"live";case"matched":return"matched";case"delayed":return"delayed";default:YF(`Unexpected order post status: ${e}`)}}function yte(e){return fte(e)?mte.parse({makingAmount:e.makingAmount,ok:!0,orderId:e.orderID,status:gte(e.status),takingAmount:e.takingAmount,tradeIds:e.tradeIDs,transactionsHashes:e.transactionsHashes}):hte.parse({code:bte(e),message:e.errorMsg||"Unknown order failure",ok:!1})}function bte(e){if(e.status==="unmatched")return"unmatched";switch(e.errorMsg){case"the market is not yet ready to process new orders":return"market_not_ready";case"invalid nonce":return"invalid_nonce";case"invalid expiration":return"invalid_expiration";case"invalid post-only order: order crosses book":return"post_only_would_cross";case"post-only mode: only post-only orders and cancels are allowed":return"post_only_mode";case"order couldn't be fully filled. FOK orders are fully filled or killed.":return"fok_not_filled";case"no orders found to match with FAK order. FAK orders are partially filled or killed if no match is found.":return"fak_not_filled"}return e.errorMsg.includes("not enough balance / allowance")?"insufficient_balance_or_allowance":"unknown"}function wte(e){return e==="live"||e==="matched"||e==="delayed"}var A,c3,IC,u3,Aee,Tee,d3,sa,p3,m3,h3,f3,See,g3,Pee,y3,b3,Eee,Ree,Iee,_ee,w3,_C,v3,k3,s3,x3,Cee,A3,i3,Nee,T3,S3,P3,E3,R3,Oee,I3,_3,C3,Lee,N3,Dee,O3,Uee,L3,Bee,Mee,Fee,D3,qee,U3,t0,Hee,CC,$ee,Vee,B3,jee,zee,Wee,Gee,Kee,Yee,Qee,Xee,Jee,Zee,ete,tte,nte,rte,ote,ste,ite,ate,M3,a3,lte,cte,F3,q3,H3,l3,ute,n0,dte,r0,pte,mte,hte,NC,$3,Yn,vte,kte,V3,xte,Ate,Tte,j3,Ste,z3,Pte,W3,OC=L(()=>{"use strict";RC();$h();xo();A=require("zod");Tl();c3=A.z.object({closed_only:A.z.boolean()}).transform(({closed_only:e})=>({closedOnly:e})),IC=A.z.object({asset_id:Me,associate_trades:A.z.array(A.z.string()),created_at:Xi,expiration:r_,id:A.z.string(),maker_address:A.z.string(),market:xe,order_type:A.z.string(),original_size:R,outcome:A.z.string(),owner:A.z.string(),price:R,side:A.z.string(),size_matched:R,status:A.z.string()}).transform(({asset_id:e,associate_trades:t,created_at:n,expiration:r,maker_address:o,market:s,order_type:i,original_size:a,size_matched:l,...c})=>{let u={...c,conditionId:s,assetId:e,tokenId:e,associateTrades:t,createdAt:n,makerAddress:o,orderType:i,originalSize:a,sizeMatched:l};return r===void 0?u:{...u,expiresAt:r}}),u3=e0(IC),Aee=A.z.object({asset_id:Me,fee_rate_bps:A.z.preprocess(Gn,R.nullable()),maker_address:A.z.string(),matched_amount:R,order_id:A.z.string(),outcome:A.z.string(),owner:A.z.string(),price:R,side:A.z.string()}).transform(({asset_id:e,fee_rate_bps:t,maker_address:n,matched_amount:r,order_id:o,...s})=>({...s,assetId:e,tokenId:e,feeRateBps:t,makerAddress:n,matchedAmount:r,orderId:o})),Tee=A.z.object({asset_id:Me,bucket_index:A.z.number(),fee_rate_bps:R,id:A.z.string(),last_update:Xi,maker_address:A.z.string(),maker_orders:A.z.array(Aee),market:xe,match_time:Xi,outcome:A.z.string(),owner:A.z.string(),price:R,side:A.z.string(),size:R,status:Lh,taker_order_id:A.z.string(),trader_side:A.z.enum(["TAKER","MAKER"]),transaction_hash:A.z.preprocess(gd,A.z.string().optional())}).transform(({asset_id:e,bucket_index:t,fee_rate_bps:n,last_update:r,maker_address:o,maker_orders:s,market:i,match_time:a,taker_order_id:l,trader_side:c,transaction_hash:u,...d})=>({...d,conditionId:i,assetId:e,tokenId:e,bucketIndex:t,feeRateBps:n,updatedAt:r,makerAddress:o,makerOrders:s,matchedAt:a,takerOrderId:l,traderSide:c,transactionHash:u})),d3=e0(Tee),sa=(e=>(e.COLLATERAL="COLLATERAL",e.CONDITIONAL="CONDITIONAL",e.CONDITIONAL_V2="CONDITIONAL-V2",e))(sa||{}),p3=A.z.enum(sa),m3=A.z.object({allowances:A.z.record(J,A.z.string().transform(BigInt)),balance:ss}),h3=A.z.object({scoring:A.z.boolean()}),f3=A.z.record(A.z.string(),A.z.boolean()),See=A.z.object({asset_address:A.z.string(),asset_rate:H,condition_id:xe,date:un,earnings:H,maker_address:A.z.string()}).transform(({asset_address:e,asset_rate:t,condition_id:n,maker_address:r,...o})=>({...o,assetAddress:e,assetRate:t,conditionId:n,makerAddress:r})),g3=e0(See),Pee=A.z.object({asset_address:A.z.string(),asset_rate:H,date:un,earnings:H,maker_address:A.z.string()}).transform(({asset_address:e,asset_rate:t,maker_address:n,...r})=>({...r,assetAddress:e,assetRate:t,makerAddress:n})),y3=A.z.array(Pee),b3=A.z.record(xe,A.z.number()),Eee=A.z.object({outcome:A.z.string(),price:H,token_id:Me}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Ree=A.z.object({asset_address:A.z.string(),end_date:un,rate_per_day:H,start_date:un,total_rewards:H}).transform(({asset_address:e,end_date:t,rate_per_day:n,start_date:r,total_rewards:o})=>({assetAddress:e,endDate:t,ratePerDay:n,startDate:r,totalRewards:o})),Iee=A.z.object({asset_address:A.z.string(),asset_rate:H,earnings:H}).transform(({asset_address:e,asset_rate:t,...n})=>({...n,assetAddress:e,assetRate:t})),_ee=A.z.object({condition_id:xe,earning_percentage:A.z.number(),earnings:A.z.array(Iee),event_slug:A.z.string(),image:A.z.string(),maker_address:A.z.string(),market_competitiveness:A.z.number(),market_slug:A.z.string(),question:A.z.string(),rewards_config:A.z.array(Ree),rewards_max_spread:A.z.number(),rewards_min_size:H,tokens:A.z.array(Eee)}).transform(({condition_id:e,earning_percentage:t,event_slug:n,maker_address:r,market_competitiveness:o,market_slug:s,rewards_config:i,rewards_max_spread:a,rewards_min_size:l,...c})=>({...c,conditionId:e,earningPercentage:t,eventSlug:n,makerAddress:r,marketCompetitiveness:o,marketSlug:s,rewardsConfig:i,rewardsMaxSpread:a,rewardsMinSize:l})),w3=e0(_ee),_C=A.z.object({apiKey:os,secret:A.z.string(),passphrase:A.z.string()}).transform(e=>({key:e.apiKey,passphrase:e.passphrase,secret:e.secret})),v3=A.z.object({apiKeys:A.z.array(os)}),k3=A.z.object({key:os,secret:A.z.string(),passphrase:A.z.string()}),s3=A.z.object({key:os,createdAt:un.optional(),revokedAt:un.nullable().optional()}),x3=A.z.array(A.z.union([os.transform(e=>({key:e})),s3])).transform(e=>e.map(t=>s3.parse(t))),Cee=A.z.object({id:A.z.string(),tradeType:A.z.string(),takerOrderHash:A.z.string(),builder:A.z.string(),market:xe,assetId:Me,side:Nt,size:R,sizeUsdc:R,price:R,status:A.z.string(),outcome:A.z.string(),outcomeIndex:A.z.number().int(),owner:A.z.string(),maker:A.z.string(),transactionHash:A.z.string(),matchTime:Xi,bucketIndex:A.z.number().int(),fee:R,feeUsdc:R,err_msg:A.z.string().nullable().optional(),createdAt:un.optional(),updatedAt:un.optional()}).transform(({err_msg:e,assetId:t,market:n,matchTime:r,...o})=>({...o,conditionId:n,assetId:t,tokenId:t,errMsg:e,matchedAt:r})),A3=A.z.object({limit:A.z.number().int(),count:A.z.number().int(),next_cursor:A.z.string(),data:A.z.array(Cee)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),i3=1e4,Nee=A.z.object({builder_maker_fee_rate_bps:A.z.number(),builder_taker_fee_rate_bps:A.z.number()}).transform(({builder_maker_fee_rate_bps:e,builder_taker_fee_rate_bps:t})=>({maker:e/i3,taker:t/i3})),T3=Nee,S3=A.z.object({canceled:A.z.array(fd),not_canceled:A.z.record(fd,A.z.string())}).transform(({canceled:e,not_canceled:t})=>({canceled:e,notCanceled:t})),P3=A.z.object({mid:R}),E3=A.z.record(Me,R),R3=A.z.object({price:R}),Oee=A.z.partialRecord(Nt,R),I3=A.z.record(Me,Oee),_3=A.z.object({spread:R}),C3=A.z.record(Me,R),Lee=A.z.object({price:R,side:Nt}),N3=Lee.extend({side:A.z.union([Nt,A.z.literal("")])}).transform(e=>e.side===""?null:{price:e.price,side:e.side}),Dee=A.z.object({price:R,side:Nt,token_id:Me}).transform(({token_id:e,price:t,side:n})=>({assetId:e,tokenId:e,price:t,side:n})),O3=A.z.array(Dee),Uee=A.z.object({condition_id:xe}).transform(({condition_id:e})=>e),L3=Uee,Bee=A.z.object({r:A.z.number().default(0),e:A.z.number().default(0)}).transform(({r:e,e:t})=>({rate:e,exponent:t})),Mee=A.z.object({t:Me,o:A.z.string()}).transform(({t:e,o:t})=>({assetId:e,tokenId:e,outcome:t})),Fee=A.z.object({fd:Bee.nullish(),mts:Pl,nr:A.z.boolean().optional(),t:A.z.array(Mee)}).transform(({fd:e,mts:t,nr:n,t:r})=>({feeInfo:e??{rate:0,exponent:0},negRisk:n??!1,tickSize:t,tokens:r})),D3=Fee,qee=A.z.object({neg_risk:A.z.boolean()}).transform(({neg_risk:e,...t})=>({...t,negRisk:e})),U3=qee,t0=(e=>(e[e.ORDER_CANCELLATION=1]="ORDER_CANCELLATION",e[e.ORDER_FILL=2]="ORDER_FILL",e[e.MARKET_REGISTERED=3]="MARKET_REGISTERED",e[e.MARKET_RESOLVED=4]="MARKET_RESOLVED",e[e.REWARD_PAYOUT=5]="REWARD_PAYOUT",e[e.CHILD_COMMENT_CREATED=6]="CHILD_COMMENT_CREATED",e[e.YIELD_PAYOUT=7]="YIELD_PAYOUT",e[e.ORDER_FILL_FAILED=8]="ORDER_FILL_FAILED",e[e.AUTO_REDEEMED=9]="AUTO_REDEEMED",e[e.COMBO_AUTO_REDEEMED=10]="COMBO_AUTO_REDEEMED",e))(t0||{}),Hee=A.z.enum(t0),CC=A.z.object({asset_id:Me,eventSlug:A.z.string().optional(),icon:A.z.string().optional(),image:A.z.string().optional(),market:xe,market_slug:A.z.string().optional(),matched_size:R,order_id:fd,original_size:R,outcome:A.z.string(),outcome_index:A.z.number().int(),price:R,question:A.z.string().optional(),remaining_size:R,seriesSlug:A.z.string().optional(),side:Nt,trade_id:A.z.preprocess(gd,A.z.string().optional()),transaction_hash:A.z.preprocess(gd,et.optional()),type:A.z.preprocess(gd,Oh.optional())}).transform(({asset_id:e,market:t,market_slug:n,matched_size:r,order_id:o,original_size:s,outcome_index:i,remaining_size:a,trade_id:l,transaction_hash:c,type:u,...d})=>({...d,conditionId:t,assetId:e,tokenId:e,marketSlug:n,matchedSize:r,orderId:o,orderType:u,originalSize:s,outcomeIndex:i,remainingSize:a,tradeId:l,transactionHash:c})),$ee=A.z.object({outcome:A.z.string(),price:H.optional(),token_id:Me,winner:A.z.boolean()}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Vee=A.z.object({max_spread:A.z.number(),min_size:H,rates:A.z.array(A.z.object({asset_address:A.z.string(),rewards_daily_rate:H}).transform(({asset_address:e,rewards_daily_rate:t})=>({assetAddress:e,dailyRate:t}))).nullish()}).transform(({max_spread:e,min_size:t,...n})=>({...n,maxSpread:e,minSize:t})),B3=A.z.object({accepting_order_timestamp:hd.nullish(),accepting_orders:A.z.boolean(),active:A.z.boolean(),archived:A.z.boolean().optional(),closed:A.z.boolean(),condition_id:xe,description:A.z.string(),enable_order_book:A.z.boolean().optional(),end_date_iso:hd.nullish(),eventSlug:A.z.string().optional(),fpmm:A.z.string(),game_start_time:hd.nullish(),icon:A.z.string(),image:A.z.string(),is_50_50_outcome:A.z.boolean().optional(),maker_base_fee:A.z.number().nullable(),market_slug:A.z.string(),minimum_order_size:H,minimum_tick_size:H,neg_risk:A.z.boolean().optional(),neg_risk_market_id:A.z.string().optional(),neg_risk_request_id:A.z.string().optional(),notifications_enabled:A.z.boolean().optional(),question:A.z.string(),question_id:vo,rewards:Vee.optional(),seconds_delay:A.z.number().int(),tags:A.z.array(A.z.string()).nullish(),taker_base_fee:A.z.number().nullable(),tokens:A.z.array($ee)}).transform(({accepting_order_timestamp:e,accepting_orders:t,condition_id:n,enable_order_book:r,end_date_iso:o,game_start_time:s,is_50_50_outcome:i,maker_base_fee:a,market_slug:l,minimum_order_size:c,minimum_tick_size:u,neg_risk:d,neg_risk_market_id:p,neg_risk_request_id:m,notifications_enabled:g,question_id:f,seconds_delay:y,taker_base_fee:w,...v})=>({...v,acceptingOrders:t,acceptingOrdersTimestamp:e,conditionId:n,enableOrderBook:r,endDate:o,gameStartTime:s,is5050Outcome:i,makerBaseFee:a,marketSlug:l,minimumOrderSize:c,minimumTickSize:u,negRisk:d,negRiskMarketId:p,negRiskRequestId:m,notificationsEnabled:g,questionId:f,secondsDelay:y,takerBaseFee:w})),jee=A.z.object({proxyWallet:J,reward:H,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),zee=A.z.object({amount:H,proxyWallet:J,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),Wee=A.z.object({body:A.z.string().nullish(),createdAt:oe.nullish(),eventSlug:A.z.string().nullish(),eventTitle:A.z.string().nullish(),id:Xs,image:A.z.string().nullish(),parentCommentID:Xs.nullish(),parentEntityID:A.z.number().int().nullish(),parentEntityType:Js.nullish(),profile:Rl.nullish(),seriesSlug:A.z.string().nullish(),seriesTitle:A.z.string().nullish(),userAddress:A.z.string().nullish()}),Gee=A.z.object({amount:H,conditionId:xe,image:A.z.string(),marketUrl:A.z.string().optional(),negRisk:A.z.boolean(),portfolioUrl:A.z.string().optional(),position:A.z.string().optional(),proxyWallet:J,question:A.z.string(),slug:A.z.string(),txnHash:et}).transform(({slug:e,txnHash:t,...n})=>({...n,marketSlug:e,transactionHash:t})),Kee=A.z.object({amount:H,conditionId:Zt,legs:A.z.number().int(),outcomeIndex:A.z.number().int(),portfolioUrl:A.z.string().optional(),positionId:Xe,proxyWallet:J,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),Yee=A.z.preprocess(e=>typeof e!="string"?e:/^\d+$/.test(e)?Number(e):Date.parse(e),pe);Qee=is(1,CC),Xee=is(2,CC),Jee=is(3,B3),Zee=is(4,B3),ete=is(5,jee),tte=is(6,Wee),nte=is(7,zee),rte=is(8,CC),ote=is(9,Gee),ste=is(10,Kee),ite=A.z.discriminatedUnion("type",[Qee,Xee,Jee,Zee,ete,tte,nte,rte,ote,ste]),ate=A.z.object({type:A.z.number().int()}),M3=A.z.array(A.z.unknown()).transform((e,t)=>{let n=[];return e.forEach((r,o)=>{let s=ate.safeParse(r);if(!s.success){for(let a of s.error.issues)t.addIssue({...a,path:[o,...a.path]});return}if(!Hee.safeParse(s.data.type).success)return;let i=ite.safeParse(r);if(i.success){n.push(i.data);return}for(let a of i.error.issues)t.addIssue({...a,path:[o,...a.path]})}),n}),a3=A.z.object({price:R,size:R}),lte=A.z.string().regex(/^[a-f0-9]{40}$/).transform(e=>e),cte=R.transform(Number).pipe(Pl),F3=A.z.object({market:xe,asset_id:Me,timestamp:Pr.nullish(),bids:A.z.array(a3),asks:A.z.array(a3),min_order_size:R,tick_size:cte,neg_risk:A.z.boolean(),last_trade_price:R.nullish(),hash:lte}).transform(({market:e,asset_id:t,min_order_size:n,tick_size:r,neg_risk:o,last_trade_price:s,...i})=>({...i,conditionId:e,assetId:t,tokenId:t,minOrderSize:n,tickSize:r,negRisk:o,lastTradePrice:s})),q3=F3,H3=A.z.array(F3),l3=A.z.preprocess(e=>e===""?"0":e,R),ute=A.z.object({errorMsg:A.z.string(),makingAmount:l3,orderID:A.z.string(),status:A.z.string(),success:A.z.boolean(),takingAmount:l3,tradeIDs:A.z.array(A.z.string()).default([]),transactionsHashes:A.z.array(A.z.string()).default([])}),n0=(e=>(e.LIVE="live",e.MATCHED="matched",e.DELAYED="delayed",e))(n0||{}),dte=A.z.nativeEnum(n0),r0=(e=>(e.UNMATCHED="unmatched",e.MARKET_NOT_READY="market_not_ready",e.INSUFFICIENT_BALANCE_OR_ALLOWANCE="insufficient_balance_or_allowance",e.INVALID_NONCE="invalid_nonce",e.INVALID_EXPIRATION="invalid_expiration",e.POST_ONLY_WOULD_CROSS="post_only_would_cross",e.POST_ONLY_MODE="post_only_mode",e.FOK_NOT_FILLED="fok_not_filled",e.FAK_NOT_FILLED="fak_not_filled",e.UNKNOWN="unknown",e))(r0||{}),pte=A.z.nativeEnum(r0),mte=A.z.object({ok:A.z.literal(!0),orderId:fd.refine(e=>e.length>0),status:dte,makingAmount:R,takingAmount:R,tradeIds:A.z.array(A.z.string()),transactionsHashes:A.z.array(et)}),hte=A.z.object({ok:A.z.literal(!1),code:pte,message:A.z.string().min(1)}),NC=ute.transform(yte),$3=A.z.array(NC);Yn="LTE=",vte=A.z.object({id:A.z.number().int().optional(),asset_address:A.z.string(),start_date:un,end_date:un.optional(),rate_per_day:H,total_rewards:H.optional()}).transform(({asset_address:e,start_date:t,end_date:n,rate_per_day:r,total_rewards:o,...s})=>({...s,assetAddress:e,startDate:t,endDate:n,ratePerDay:r,totalRewards:o})),kte=A.z.object({condition_id:xe,rewards_max_spread:A.z.number().optional(),rewards_min_size:H.optional(),rewards_config:A.z.array(vte).optional(),sponsored_daily_rate:H.optional(),sponsors_count:A.z.number().int().optional(),native_daily_rate:H.optional(),total_daily_rate:H.optional()}).transform(({condition_id:e,rewards_max_spread:t,rewards_min_size:n,rewards_config:r,sponsored_daily_rate:o,sponsors_count:s,native_daily_rate:i,total_daily_rate:a,...l})=>({...l,conditionId:e,rewardsMaxSpread:t,rewardsMinSize:n,rewardsConfig:r,sponsoredDailyRate:o,sponsorsCount:s,nativeDailyRate:i,totalDailyRate:a})),V3=A.z.object({limit:A.z.number().int(),count:A.z.number().int(),next_cursor:A.z.string(),data:A.z.array(kte)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),xte=A.z.object({token_id:Me,outcome:A.z.string(),price:H}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Ate=A.z.object({asset_address:A.z.string(),start_date:un,end_date:un.optional(),rate_per_day:H,total_rewards:H.optional()}).transform(({asset_address:e,start_date:t,end_date:n,rate_per_day:r,total_rewards:o,...s})=>({...s,assetAddress:e,startDate:t,endDate:n,ratePerDay:r,totalRewards:o})),Tte=A.z.object({condition_id:xe,question:A.z.string(),market_slug:A.z.string().optional(),event_slug:A.z.string().optional(),image:A.z.string().optional(),rewards_max_spread:A.z.number().optional(),rewards_min_size:H.optional(),market_competitiveness:A.z.number().optional(),tokens:A.z.array(xte),rewards_config:A.z.array(Ate).optional()}).transform(({condition_id:e,market_slug:t,event_slug:n,rewards_max_spread:r,rewards_min_size:o,market_competitiveness:s,rewards_config:i,...a})=>({...a,conditionId:e,marketSlug:t,eventSlug:n,rewardsMaxSpread:r,rewardsMinSize:o,marketCompetitiveness:s,rewardsConfig:i})),j3=A.z.object({limit:A.z.number().int(),count:A.z.number().int(),next_cursor:A.z.string(),data:A.z.array(Tte)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),Ste=A.z.object({address:J,scopes:A.z.array(Ih).min(1),valid_until:A.z.number().int().nonnegative()}).transform(({valid_until:e,...t})=>({...t,validUntil:e})),z3=A.z.object({signers:A.z.array(Ste),wallet:J}),Pte=A.z.object({minimum_tick_size:Pl}).transform(({minimum_tick_size:e,...t})=>({...t,minimumTickSize:e})),W3=Pte});var ae,uf,Ete,Rte,G3,iCe,Ite,_te,K3,Cte,Nte,Y3,Id,Ote,Q3,LC,DC,UC,X3,Se,aCe,o0=L(()=>{"use strict";$h();$h();xo();ae=require("zod"),uf=(e=>(e.Pending="pending",e.Queued="queued",e.Success="success",e.Failed="failed",e.Cancelled="cancelled",e))(uf||{}),Ete=ae.z.union([ae.z.string(),ae.z.number().int().transform(String)]).transform(xw),Rte=ae.z.object({id:ae.z.number().int(),marketId:Ete.nullish(),eventId:Gt.nullish(),questionId:vo.nullish(),content:ae.z.string().nullish(),state:ae.z.enum(uf).nullish(),clearBook:ae.z.boolean().nullish(),notifyDiscord:ae.z.boolean().nullish(),showInFrontend:ae.z.boolean().nullish(),adapterAddress:J.nullish(),negRiskRequestId:ae.z.string().nullish(),txHash:et.nullish(),createdAt:oe.nullish(),queuedAt:oe.nullish(),scheduledFor:oe.nullish(),txTimestamp:oe.nullish()}),G3=ae.z.array(Rte),iCe=ae.z.object({hasMore:ae.z.boolean().nullish(),totalResults:ae.z.number().int().nullish()}),Ite=ae.z.object({id:ae.z.string(),communityMod:ae.z.boolean().nullish(),creator:ae.z.boolean().nullish(),mod:ae.z.boolean().nullish()}),_te=ae.z.object({id:ae.z.string().nullish(),name:ae.z.string().nullish(),user:ae.z.number().int().nullish(),referral:ae.z.string().nullish(),createdBy:ae.z.number().int().nullish(),updatedBy:ae.z.number().int().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),utmSource:ae.z.string().nullish(),utmMedium:ae.z.string().nullish(),utmCampaign:ae.z.string().nullish(),utmContent:ae.z.string().nullish(),utmTerm:ae.z.string().nullish(),walletActivated:ae.z.boolean().nullish(),pseudonym:ae.z.string().nullish(),displayUsernamePublic:ae.z.boolean().nullish(),profileImage:ae.z.string().nullish(),bio:ae.z.string().nullish(),proxyWallet:ae.z.string().nullish(),profileImageOptimized:Zs.nullish(),isCloseOnly:ae.z.boolean().nullish(),isCertReq:ae.z.boolean().nullish(),certReqDate:oe.nullish(),discordUsername:ae.z.string().nullish(),xUsername:ae.z.string().nullish(),verifiedBadge:ae.z.boolean().nullish(),dubPartnerId:ae.z.string().nullish(),termsAcceptedAt:oe.nullish(),viewOnlyAcknowledgedAt:oe.nullish(),isReferralRestricted:ae.z.boolean().nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),K3=ae.z.object({createdAt:oe.nullish(),proxyWallet:J.nullish(),profileImage:ae.z.string().nullish(),displayUsernamePublic:ae.z.boolean().nullish(),bio:ae.z.string().nullish(),pseudonym:ae.z.string().nullish(),name:ae.z.string().nullish(),users:ae.z.array(Ite).nullish(),xUsername:ae.z.string().nullish(),verifiedBadge:ae.z.boolean().nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),Cte=ae.z.object({id:Dh,event_count:ae.z.number().int().nullish(),label:ae.z.string().nullish(),slug:ae.z.string().nullish()}).transform(({event_count:e,...t})=>({...t,eventCount:e})),Nte=ae.z.object({hasMore:ae.z.boolean().nullish(),totalResults:ae.z.number().int().nullish()}),Y3=ae.z.object({events:ae.z.array(ei).nullish(),tags:ae.z.array(Cte).nullish(),profiles:ae.z.array(_te).nullish(),pagination:Nte.nullish()}),Id=El.extend({templates:ae.z.array(Uw).nullish()}),Ote=ae.z.object({id:ae.z.string(),tagID:ae.z.number().int().nullish(),relatedTagID:ae.z.number().int().nullish(),rank:ae.z.number().int().nullish()}).transform(({tagID:e,relatedTagID:t,...n})=>({...n,tagId:e,relatedTagId:t})),Q3=ae.z.array(Id),LC=ae.z.array(Ote),DC=ae.z.array(Id),UC=Dw.extend({events:ae.z.array(ei).nullish(),collections:ae.z.array(Lw).nullish(),tags:ae.z.array(Id).nullish()}),X3=ae.z.array(UC),Se=(e=>(e[e.EOA=0]="EOA",e[e.POLY_PROXY=1]="POLY_PROXY",e[e.GNOSIS_SAFE=2]="GNOSIS_SAFE",e[e.DEPOSIT_WALLET=3]="DEPOSIT_WALLET",e))(Se||{}),aCe=ae.z.object({type:ae.z.enum(Se),typeName:ae.z.enum(["EOA","POLY_PROXY","GNOSIS_SAFE","DEPOSIT_WALLET"])})});var Ll,BC=L(()=>{"use strict";Ll=class extends Error{response;request;options;constructor(t,n,r){let o=t.status||t.status===0?t.status:"",s=t.statusText??"",i=`${o} ${s}`.trim(),a=i?`status code ${i}`:"an unknown error";super(`Request failed with ${a}: ${n.method} ${n.url}`),this.name="HTTPError",this.response=t,this.request=n,this.options=r}}});var _d,MC=L(()=>{"use strict";_d=class extends Error{name="NonError";value;constructor(t){let n="Non-error value was thrown";try{typeof t=="string"?n=t:t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"&&(n=t.message)}catch{}super(n),this.value=t}}});var Cd,J3=L(()=>{"use strict";MC();Cd=class extends Error{name="ForceRetryError";customDelay;code;customRequest;constructor(t){let n=t?.cause?t.cause instanceof Error?t.cause:new _d(t.cause):void 0;super(t?.code?`Forced retry: ${t.code}`:"Forced retry",n?{cause:n}:void 0),this.customDelay=t?.delay,this.code=t?.code,this.customRequest=t?.request}}});var FC,Z3,s0,e$,t$,i0,Lte,n$,a0,r$,l0,df,o$,s$,i$,a$,Dl=L(()=>{"use strict";FC=(()=>{let e=!1,t=!1,n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(n&&r)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(o){if(o instanceof Error&&o.message==="unsupported BodyInit type")return!1;throw o}return e&&!t})(),Z3=typeof globalThis.AbortController=="function",s0=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",e$=typeof globalThis.ReadableStream=="function",t$=typeof globalThis.FormData=="function",i0=["get","post","put","patch","head","delete"],Lte=()=>{};Lte();n$={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},a0=2147483647,r$=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,l0=Symbol("stop"),df=class{options;constructor(t){this.options=t}},o$=e=>new df(e),s$={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},i$={next:!0},a$={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0}});var Dte,l$,c$,u$,d$=L(()=>{"use strict";Dl();Dte=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=r$,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r=="string"?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},l$=(e,t,n)=>{let r,o=0;return e.pipeThrough(new TransformStream({transform(s,i){if(i.enqueue(s),r){o+=r.byteLength;let a=t===0?0:o/t;a>=1&&(a=1-Number.EPSILON),n?.({percent:a,totalBytes:Math.max(t,o),transferredBytes:o},r)}r=s},flush(){r&&(o+=r.byteLength,n?.({percent:1,totalBytes:Math.max(t,o),transferredBytes:o},r))}}))},c$=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let n=Math.max(0,Number(e.headers.get("content-length"))||0);return new Response(l$(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},u$=(e,t,n)=>{if(!e.body)return e;let r=Dte(n??e.body);return new Request(e,{duplex:"half",body:l$(e.body,r,t)})}});var ia,p$=L(()=>{"use strict";ia=e=>e!==null&&typeof e=="object"});function c0(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:$C(e[n]??[],t[n]??[])}var pf,qC,HC,Ute,$C,VC=L(()=>{"use strict";Dl();p$();pf=(...e)=>{for(let t of e)if((!ia(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return $C({},...e)},qC=(e={},t={})=>{let n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(let[s,i]of o.entries())r&&i==="undefined"||i===void 0?n.delete(s):n.set(s,i);return n};HC=(e={},t={})=>({beforeRequest:c0(e,t,"beforeRequest"),beforeRetry:c0(e,t,"beforeRetry"),afterResponse:c0(e,t,"afterResponse"),beforeError:c0(e,t,"beforeError")}),Ute=(e,t)=>{let n=new URLSearchParams;for(let r of[e,t])if(r!==void 0)if(r instanceof URLSearchParams)for(let[o,s]of r.entries())n.append(o,s);else if(Array.isArray(r))for(let o of r){if(!Array.isArray(o)||o.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");n.append(String(o[0]),String(o[1]))}else if(ia(r))for(let[o,s]of Object.entries(r))s!==void 0&&n.append(o,String(s));else{let o=new URLSearchParams(r);for(let[s,i]of o.entries())n.append(s,i)}return n},$C=(...e)=>{let t={},n={},r={},o,s=[];for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(ia(i)){for(let[a,l]of Object.entries(i)){if(a==="signal"&&l instanceof globalThis.AbortSignal){s.push(l);continue}if(a==="context"){if(l!=null&&(!ia(l)||Array.isArray(l)))throw new TypeError("The `context` option must be an object");t={...t,context:l==null?{}:{...t.context,...l}};continue}if(a==="searchParams"){l==null?o=void 0:o=o===void 0?l:Ute(o,l);continue}ia(l)&&a in t&&(l=$C(t[a],l)),t={...t,[a]:l}}ia(i.hooks)&&(r=HC(r,i.hooks),t.hooks=r),ia(i.headers)&&(n=qC(n,i.headers),t.headers=n)}return o!==void 0&&(t.searchParams=o),s.length>0&&(s.length===1?t.signal=s[0]:s0?t.signal=AbortSignal.any(s):t.signal=s.at(-1)),t}});var h$,Bte,Mte,Fte,m$,f$,g$=L(()=>{"use strict";Dl();h$=e=>i0.includes(e)?e.toUpperCase():e,Bte=["get","put","head","delete","options","trace"],Mte=[408,413,429,500,502,503,504],Fte=[413,429,503],m$={limit:2,methods:Bte,statusCodes:Mte,afterStatusCodes:Fte,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},f$=(e={})=>{if(typeof e=="number")return{...m$,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.methods&&=e.methods.map(n=>n.toLowerCase()),e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");let t=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));return{...m$,...t}}});var Ul,jC=L(()=>{"use strict";Ul=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}}});async function zC(e,t,n,r){return new Promise((o,s)=>{let i=setTimeout(()=>{n&&n.abort(),s(new Ul(e))},r.timeout);r.fetch(e,t).then(o).catch(s).then(()=>{clearTimeout(i)})})}var y$=L(()=>{"use strict";jC()});async function WC(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));function o(){clearTimeout(s),r(t.reason)}let s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e)})}var b$=L(()=>{"use strict"});var w$,v$,k$=L(()=>{"use strict";Dl();w$=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in a$)&&!(r in s$)&&(!(r in e)||r in i$)&&(n[r]=t[r]);return n},v$=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e});function x$(e){return e instanceof Ll||e?.name===Ll.name}function A$(e){return e instanceof Ul||e?.name===Ul.name}var T$=L(()=>{"use strict";BC();jC()});var mf,S$=L(()=>{"use strict";BC();MC();J3();d$();VC();g$();y$();b$();k$();T$();Dl();mf=class e{static create(t,n){let r=new e(t,n),o=async()=>{if(typeof r.#n.timeout=="number"&&r.#n.timeout>a0)throw new RangeError(`The \`timeout\` option cannot be greater than ${a0}`);await Promise.resolve();let i=await r.#y();for(let a of r.#n.hooks.afterResponse){let l=r.#c(i.clone()),c;try{c=await a(r.request,r.#h(),l,{retryCount:r.#r})}catch(d){throw r.#d(l),r.#d(i),d}if(c instanceof df)throw r.#d(l),r.#d(i),new Cd(c.options);let u=c instanceof globalThis.Response?c:i;l!==u&&r.#d(l),i!==u&&r.#d(i),i=u}if(r.#c(i),!i.ok&&(typeof r.#n.throwHttpErrors=="function"?r.#n.throwHttpErrors(i.status):r.#n.throwHttpErrors)){let a=new Ll(i,r.request,r.#h());for(let l of r.#n.hooks.beforeError)a=await l(a,{retryCount:r.#r});throw a}if(r.#n.onDownloadProgress){if(typeof r.#n.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!e$)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");let a=i.clone();return r.#d(i),c$(a,r.#n.onDownloadProgress)}return i},s=r.#m(o).finally(()=>{let i=r.#o;r.#p(i?.body??void 0),r.#p(r.request.body??void 0)});for(let[i,a]of Object.entries(n$))i==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(s[i]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||a);let l=await s;if(i==="json"){if(l.status===204)return"";let c=await l.text();return c===""?"":n.parseJson?n.parseJson(c):JSON.parse(c)}return l[i]()});return s}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t}request;#t;#r=0;#s;#n;#o;#i;#a;constructor(t,n={}){if(this.#s=t,this.#n={...n,headers:qC(this.#s.headers,n.headers),hooks:HC({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:h$(n.method??this.#s.method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:f$(n.retry),throwHttpErrors:n.throwHttpErrors??!0,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis),context:n.context??{}},typeof this.#s!="string"&&!(this.#s instanceof URL||this.#s instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this.#n.prefixUrl&&typeof this.#s=="string"){if(this.#s.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this.#n.prefixUrl.endsWith("/")||(this.#n.prefixUrl+="/"),this.#s=this.#n.prefixUrl+this.#s}Z3&&s0&&(this.#i=this.#n.signal??this.#s.signal,this.#t=new globalThis.AbortController,this.#n.signal=this.#i?AbortSignal.any([this.#i,this.#t.signal]):this.#t.signal),FC&&(this.#n.duplex="half"),this.#n.json!==void 0&&(this.#n.body=this.#n.stringifyJson?.(this.#n.json)??JSON.stringify(this.#n.json),this.#n.headers.set("content-type",this.#n.headers.get("content-type")??"application/json"));let r=n.headers&&new globalThis.Headers(n.headers).has("content-type");if(this.#s instanceof globalThis.Request&&(t$&&this.#n.body instanceof globalThis.FormData||this.#n.body instanceof URLSearchParams)&&!r&&this.#n.headers.delete("content-type"),this.request=new globalThis.Request(this.#s,this.#n),v$(this.#n.searchParams)){let s="?"+(typeof this.#n.searchParams=="string"?this.#n.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this.#n.searchParams)).toString()),i=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,s);this.request=new globalThis.Request(i,this.#n)}if(this.#n.onUploadProgress){if(typeof this.#n.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!FC)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#g(this.request,this.#n.body??void 0)}}#u(){let t=this.#n.retry.delay(this.#r),n=t;this.#n.retry.jitter===!0?n=Math.random()*t:typeof this.#n.retry.jitter=="function"&&(n=this.#n.retry.jitter(t),(!Number.isFinite(n)||n<0)&&(n=t));let r=this.#n.retry.backoffLimit??Number.POSITIVE_INFINITY;return Math.min(r,n)}async#l(t){if(this.#r++,this.#r>this.#n.retry.limit)throw t;let n=t instanceof Error?t:new _d(t);if(n instanceof Cd)return n.customDelay??this.#u();if(!this.#n.retry.methods.includes(this.request.method.toLowerCase()))throw t;if(this.#n.retry.shouldRetry!==void 0){let r=await this.#n.retry.shouldRetry({error:n,retryCount:this.#r});if(r===!1)throw t;if(r===!0)return this.#u()}if(A$(t)&&!this.#n.retry.retryOnTimeout)throw t;if(x$(t)){if(!this.#n.retry.statusCodes.includes(t.response.status))throw t;let r=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Retry-After")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(r&&this.#n.retry.afterStatusCodes.includes(t.response.status)){let o=Number(r)*1e3;Number.isNaN(o)?o=Date.parse(r)-Date.now():o>=Date.parse("2024-01-01")&&(o-=Date.now());let s=this.#n.retry.maxRetryAfter??o;return o<s?o:s}if(t.response.status===413)throw t}return this.#u()}#c(t){return this.#n.parseJson&&(t.json=async()=>this.#n.parseJson(await t.text())),t}#p(t){t&&t.cancel().catch(()=>{})}#d(t){this.#p(t.body??void 0)}async#m(t){try{return await t()}catch(n){let r=Math.min(await this.#l(n),a0);if(this.#r<1)throw n;if(await WC(r,this.#i?{signal:this.#i}:{}),n instanceof Cd&&n.customRequest){let o=this.#n.signal?new globalThis.Request(n.customRequest,{signal:this.#n.signal}):new globalThis.Request(n.customRequest);this.#f(o)}for(let o of this.#n.hooks.beforeRetry){let s=await o({request:this.request,options:this.#h(),error:n,retryCount:this.#r});if(s instanceof globalThis.Request){this.#f(s);break}if(s instanceof globalThis.Response)return s;if(s===l0)return}return this.#m(t)}}async#y(){this.#t?.signal.aborted&&(this.#t=new globalThis.AbortController,this.#n.signal=this.#i?AbortSignal.any([this.#i,this.#t.signal]):this.#t.signal,this.request=new globalThis.Request(this.request,{signal:this.#n.signal}));for(let n of this.#n.hooks.beforeRequest){let r=await n(this.request,this.#h(),{retryCount:this.#r});if(r instanceof Response)return r;if(r instanceof globalThis.Request){this.#f(r);break}}let t=w$(this.request,this.#n);return this.#o=this.request,this.request=this.#o.clone(),this.#n.timeout===!1?this.#n.fetch(this.#o,t):zC(this.#o,t,this.#t,this.#n)}#h(){if(!this.#a){let{hooks:t,...n}=this.#n;this.#a=Object.freeze(n)}return this.#a}#f(t){this.#a=void 0,this.request=this.#g(t)}#g(t,n){return!this.#n.onUploadProgress||!t.body?t:u$(t,this.#n.onUploadProgress,n??this.#n.body??void 0)}}});var GC,qte,u0,P$=L(()=>{"use strict";S$();Dl();VC();GC=e=>{let t=(n,r)=>mf.create(n,pf(e,r));for(let n of i0)t[n]=(r,o)=>mf.create(r,pf(e,o,{method:n}));return t.create=n=>GC(pf(n)),t.extend=n=>(typeof n=="function"&&(n=n(e??{})),GC(pf(e,n))),t.stop=l0,t.retry=o$,t},qte=GC(),u0=qte});function Hte(e){let t=e.length===64?`${e}00`:e;return _h(t.toLowerCase())}function $te(e){if(e.length===66)return!0;let t=e.toLowerCase();return t.startsWith("0x01")||t.startsWith("0x02")}function ls(e){return U.z.object({data:U.z.array(e),pagination:U.z.object({limit:U.z.number().int(),offset:U.z.number().int(),has_more:U.z.boolean(),next_cursor:U.z.string().min(1).nullable()})}).refine(t=>t.pagination.has_more===(t.pagination.next_cursor!==null),{message:"has_more and next_cursor must agree",path:["pagination","next_cursor"]}).transform(({data:t,pagination:n})=>({items:t,hasMore:n.has_more,nextCursor:n.next_cursor===null?void 0:n.next_cursor}))}function si(e){return U.z.object({data:e}).transform(t=>t.data)}function sne(e){let t=ine(e);switch(e.type){case"SPLIT":return{...t,type:"SPLIT"};case"MERGE":return{...t,type:"MERGE"};case"CONVERT":return{...t,type:"CONVERT"};case"COMPRESS":return{...t,type:"COMPRESS"};case"WRAP":return{...t,type:"WRAP"};case"UNWRAP":return{...t,type:"UNWRAP"};case"REDEEM":return{...t,type:"REDEEM",payout:e.payout_usdc??null}}}function ine(e){return{id:e.id,type:e.type,wallet:e.proxy_wallet,conditionId:e.combo_condition_id,positionId:e.combo_position_id,amount:e.amount_usdc??null,timestamp:e.timestamp,transactionHash:e.transaction_hash,blockNumber:e.block_number,legs:e.legs}}function ane(e){let t=cne(e);switch(e.type){case"TRADE":return lne(e,t);case"SPLIT":case"MERGE":case"REDEEM":case"CONVERSION":return{...t,type:e.type,conditionId:Ir(e.condition_id,"condition_id"),amount:e.usdc_size,title:Ir(e.title,"title"),slug:Ir(e.slug,"slug"),icon:e.icon??null,eventSlug:Ir(e.event_slug,"event_slug")};case"MIGRATION":case"REWARD":case"MAKER_REBATE":case"REFERRAL_REWARD":case"YIELD":case"DEPOSIT":case"WITHDRAWAL":case"TAKER_REBATE":return{...t,type:e.type,amount:e.usdc_size};case"TIP":return{...t,type:e.type,amount:e.usdc_size,side:e.side===void 0?null:R$.parse(e.side)}}}function lne(e,t){let n={...t,type:"TRADE",side:Nt.parse(Ir(e.side,"side")),shares:e.size,amount:e.usdc_size,price:e.price,title:Ir(e.title,"title"),icon:e.icon??null};if(e.is_combo===!0)return{...n,isCombo:!0,conditionId:Zt.parse(Ir(e.condition_id,"condition_id")),positionId:Xe.parse(Ir(e.token_id,"token_id"))};let r=Ir(e.token_id,"token_id");return{...n,isCombo:!1,conditionId:Ir(e.condition_id,"condition_id"),assetId:r,tokenId:r,outcome:Ir(e.outcome,"outcome"),outcomeIndex:e.outcome_index,slug:Ir(e.slug,"slug"),eventSlug:Ir(e.event_slug,"event_slug")}}function cne(e){return{wallet:e.proxy_wallet,timestamp:e.timestamp,transactionHash:e.transaction_hash,name:e.name??null,pseudonym:e.pseudonym??null,bio:e.bio??null,profileImage:e.profile_image??null,profileImageOptimized:e.profile_image_optimized??null}}function Ir(e,t){if(e==null)throw new TypeError(`Expected activity.${t} to be present`);return e}var U,p0,KC,Bl,R$,Ml,m0,Fl,I$,ql,ii,Nd,ai,_$,Vte,Hl,C$,$l,N$,Vl,O$,oi,jte,zte,Wte,jl,YC,zl,d0,pn,L$,Gte,Kte,Yte,Qte,Xte,D$,Jte,U$,B$,M$,F$,q$,H$,Wl,Zte,ene,tne,Kt,$$,nne,rne,one,V$,j$,z$,Po,W$,une,G$,hf,dne,pne,mne,hne,fne,K$,Y$,Q$,Gl,ff,Kl,X$,Yl,J$,Ql,YCe,gne,yne,as,bne,wne,vne,kne,xne,Z$,e4,t4,n4,r4,Xl,Ane,Jl,Tne,Zl,Sne,ec,Pne,E$,Ene,o4,h0=L(()=>{"use strict";xo();U=require("zod"),p0=(e=>(e.TRADE="TRADE",e.SPLIT="SPLIT",e.MERGE="MERGE",e.REDEEM="REDEEM",e.REWARD="REWARD",e.CONVERSION="CONVERSION",e.MIGRATION="MIGRATION",e.MAKER_REBATE="MAKER_REBATE",e.REFERRAL_REWARD="REFERRAL_REWARD",e.YIELD="YIELD",e.DEPOSIT="DEPOSIT",e.WITHDRAWAL="WITHDRAWAL",e.TAKER_REBATE="TAKER_REBATE",e.TIP="TIP",e))(p0||{}),KC=U.z.enum(p0),Bl=(e=>(e.In="IN",e.Out="OUT",e))(Bl||{}),R$=U.z.enum(Bl),Ml=(e=>(e.Asc="ASC",e.Desc="DESC",e))(Ml||{}),m0=U.z.enum(Ml),Fl=(e=>(e.Cash="CASH",e.Tokens="TOKENS",e))(Fl||{}),I$=U.z.enum(Fl);ql=xe.refine($te,"Expected a 32-byte condition ID or a 31-byte protocol v2 market condition ID").transform(Hte);ii=(e=>(e.Open="OPEN",e.Redeemable="REDEEMABLE",e.Partial="PARTIAL",e.ResolvedPartial="RESOLVED_PARTIAL",e.ResolvedWin="RESOLVED_WIN",e.ResolvedLoss="RESOLVED_LOSS",e))(ii||{}),Nd=U.z.enum(ii),ai=(e=>(e.Open="OPEN",e.Redeemable="REDEEMABLE",e.RedeemableLost="REDEEMABLE_LOST",e.Mergeable="MERGEABLE",e.Closed="CLOSED",e))(ai||{}),_$=U.z.enum(ai),Vte=U.z.enum(["OPEN","REDEEMABLE","CLOSED"]),Hl=(e=>(e.CurrentValue="CURRENT_VALUE",e.Tokens="TOKENS",e.UnrealizedPnl="UNREALIZED_PNL",e.RealizedPnl="REALIZED_PNL",e.TotalPnl="TOTAL_PNL",e.Timestamp="TIMESTAMP",e))(Hl||{}),C$=U.z.enum(Hl),$l=(e=>(e.Cash="CASH",e.Tokens="TOKENS",e))($l||{}),N$=U.z.enum($l),Vl=(e=>(e.FirstEntry="FIRST_ENTRY",e.EntryCost="ENTRY_COST",e.CurrentValue="CURRENT_VALUE",e.Updated="UPDATED",e))(Vl||{}),O$=U.z.enum(Vl),oi=U.z.preprocess(e=>e===""?void 0:e,U.z.string().optional()),jte=U.z.preprocess(e=>e===999?void 0:e,U.z.number().int().optional()),zte=U.z.object({proxy_wallet:J,token_id:Me,condition_id:xe,current_size:H,avg_price:H,entry_cost_usdc:H,entry_fees_usdc:H,total_cost_usdc:H,current_price:H,current_value:H,total_size:H,realized_pnl:H,unrealized_pnl:H,total_pnl:H,percent_pnl:H,percent_realized_pnl:H,status:Vte,redeemable:U.z.boolean(),mergeable:U.z.boolean(),negative_risk:U.z.boolean(),archived:U.z.boolean(),title:oi,slug:oi,icon:oi,event_id:oi,event_slug:oi,outcome:oi,outcome_index:jte,opposite_outcome:oi,opposite_token_id:U.z.preprocess(e=>e===""?void 0:e,Me.optional()),end_date:U.z.preprocess(e=>e===""?void 0:e,Wn.optional()),last_event_at:U.z.preprocess(e=>e===0?void 0:e,wo.optional()),name:oi,profile_image:oi,verified:U.z.boolean()}).transform(e=>({wallet:e.proxy_wallet,assetId:e.token_id,tokenId:e.token_id,conditionId:e.condition_id,currentSize:e.current_size,avgPrice:e.avg_price,entryCostUsdc:e.entry_cost_usdc,entryFeesUsdc:e.entry_fees_usdc,totalCostUsdc:e.total_cost_usdc,currentPrice:e.current_price,currentValue:e.current_value,totalSize:e.total_size,realizedPnl:e.realized_pnl,unrealizedPnl:e.unrealized_pnl,totalPnl:e.total_pnl,percentPnl:e.percent_pnl,percentRealizedPnl:e.percent_realized_pnl,status:e.status,redeemable:e.redeemable,mergeable:e.mergeable,negativeRisk:e.negative_risk,archived:e.archived,title:e.title,slug:e.slug,icon:e.icon,eventId:e.event_id,eventSlug:e.event_slug,outcome:e.outcome,outcomeIndex:e.outcome_index,oppositeOutcome:e.opposite_outcome,oppositeAssetId:e.opposite_token_id,oppositeTokenId:e.opposite_token_id,endDate:e.end_date,lastEventAt:e.last_event_at,name:e.name,profileImage:e.profile_image,verified:e.verified})),Wte=U.z.object({proxy_wallet:J,value:H}).transform(({proxy_wallet:e,value:t})=>({wallet:e,value:t})),jl=(e=>(e.Max="max",e.OneMonth="1m",e.OneWeek="1w",e.OneDay="1d",e.TwelveHours="12h",e.SixHours="6h",e))(jl||{}),YC=U.z.enum(jl),zl=(e=>(e.OneDay="1d",e.EighteenHours="18h",e.TwelveHours="12h",e.ThreeHours="3h",e.OneHour="1h",e))(zl||{}),d0=U.z.enum(zl),pn=H.nullish().transform(e=>e??null),L$=U.z.object({timestamp:wo,source_block:U.z.number().int().nonnegative(),realized_market_pnl:H,realized_lp_pnl:H,realized_combo_pnl:H,unrealized_pnl:pn,fees_refunded:pn,maker_rebate:pn,taker_rebate:pn,reward_income:pn,yield_income:pn,referral_income:pn,deposits:pn,withdrawals:pn,realized_pnl:H,wallet_income:pn,position_pnl:pn,settled_pnl:pn,economic_pnl:pn,trade_pnl:pn,sponsored_income:pn,fees:pn,fees_paid:pn,cashflow_net:pn,volume:H,volume_usdc:H,trade_count:U.z.number().int().nonnegative()}).transform(({source_block:e,realized_market_pnl:t,realized_lp_pnl:n,realized_combo_pnl:r,unrealized_pnl:o,fees_refunded:s,maker_rebate:i,taker_rebate:a,reward_income:l,yield_income:c,referral_income:u,realized_pnl:d,wallet_income:p,position_pnl:m,settled_pnl:g,economic_pnl:f,trade_pnl:y,sponsored_income:w,fees_paid:v,cashflow_net:x,volume_usdc:k,trade_count:S,...D})=>({...D,sourceBlock:e,realizedMarketPnl:t,realizedLpPnl:n,realizedComboPnl:r,unrealizedPnl:o,feesRefunded:s,makerRebate:i,takerRebate:a,rewardIncome:l,yieldIncome:c,referralIncome:u,realizedPnl:d,walletIncome:p,positionPnl:m,settledPnl:g,economicPnl:f,tradePnl:y,sponsoredIncome:w,feesPaid:v,cashflowNet:x,volumeUsdc:k,tradeCount:S})),Gte=U.z.object({proxy_wallet:J,interval:YC,fidelity:d0,source_fidelity:d0,points:U.z.array(L$)}).transform(({proxy_wallet:e,source_fidelity:t,...n})=>({...n,wallet:e,sourceFidelity:t})),Kte=U.z.object({volume:H,volume_usdc:H,trade_count:U.z.number().int().nonnegative()}).transform(({volume_usdc:e,trade_count:t,...n})=>({...n,volumeUsdc:e,tradeCount:t})),Yte=U.z.object({proxy_wallet:J,trades:U.z.number().int().nonnegative(),biggest_win:H,views:U.z.number().int().nonnegative(),join_date:wo.nullish(),all_time_pnl:L$.nullish()}).transform(({proxy_wallet:e,trades:t,biggest_win:n,join_date:r,all_time_pnl:o,...s})=>({...s,wallet:e,tradedMarketCount:t,biggestWin:n,joinDate:r??null,allTimePnl:o??null})),Qte=U.z.object({event_id:U.z.string().nullish(),event_slug:U.z.string().nullish(),event_title:U.z.string().nullish(),event_image:U.z.string().nullish()}).transform(({event_id:e,event_slug:t,event_title:n,event_image:r})=>({eventId:e,eventSlug:t,eventTitle:n,eventImage:r})),Xte=U.z.object({market_id:U.z.string().nullish(),slug:U.z.string().nullish(),title:U.z.string().nullish(),question:U.z.string().nullish(),group_item_title:U.z.string().nullish(),sports_market_type:U.z.string().nullish(),line:U.z.number().nullish(),outcomes:U.z.array(U.z.string()).nullish(),outcome:U.z.string().nullish(),image_url:U.z.string().nullish(),icon_url:U.z.string().nullish(),category:U.z.string().nullish(),subcategory:U.z.string().nullish(),tags:U.z.array(U.z.string()).nullish(),end_date:oe.nullish(),event:Qte.nullish()}).transform(({market_id:e,image_url:t,icon_url:n,end_date:r,group_item_title:o,sports_market_type:s,...i})=>({...i,marketId:e,groupItemTitle:o,sportsMarketType:s,imageUrl:t,iconUrl:n,endDate:r})),D$=U.z.object({leg_index:U.z.number().int(),leg_position_id:Xe,leg_condition_id:xe,leg_outcome_index:U.z.number().int(),leg_outcome_label:U.z.string().nullish(),leg_status:Nd,leg_resolved_at:oe.nullish(),leg_current_price:H.nullish(),market:Xte.nullish()}).transform(({leg_index:e,leg_position_id:t,leg_condition_id:n,leg_outcome_index:r,leg_outcome_label:o,leg_status:s,leg_resolved_at:i,leg_current_price:a,...l})=>({...l,legIndex:e,legPositionId:t,legConditionId:n,legOutcomeIndex:r,legOutcomeLabel:o,legStatus:s,legResolvedAt:i,legCurrentPrice:a})),Jte=U.z.object({combo_condition_id:Zt,outcome_index:U.z.number().int(),outcome_label:U.z.string(),combo_position_id:Xe,proxy_wallet:J,current_size:H,entry_avg_price_usdc:H,entry_cost_usdc:H,gross_entry_cost_usdc:H,entry_fees_usdc:H,realized_payout_usdc:H,status:Nd,redeemable:U.z.boolean(),first_entry_at:oe,resolved_at:oe.nullish(),legs_total:U.z.number().int(),legs_resolved:U.z.number().int(),legs_pending:U.z.number().int(),legs:U.z.array(D$),updated_at:oe}).transform(({combo_condition_id:e,outcome_index:t,outcome_label:n,combo_position_id:r,proxy_wallet:o,current_size:s,entry_avg_price_usdc:i,entry_cost_usdc:a,gross_entry_cost_usdc:l,entry_fees_usdc:c,realized_payout_usdc:u,first_entry_at:d,resolved_at:p,legs_total:m,legs_resolved:g,legs_pending:f,updated_at:y,...w})=>({...w,conditionId:e,outcomeIndex:t,outcomeLabel:n,positionId:r,wallet:o,currentSize:s,entryAvgPriceUsdc:i,entryCostUsdc:a,grossEntryCostUsdc:l,entryFeesUsdc:c,realizedPayoutUsdc:u,firstEntryAt:d,resolvedAt:p,legsTotal:m,legsResolved:g,legsPending:f,updatedAt:y})),U$=ls(zte),B$=si(Wte),M$=si(Yte.nullable()),F$=si(Gte),q$=si(Kte),H$=ls(Jte),Wl=(e=>(e.Split="SPLIT",e.Merge="MERGE",e.Convert="CONVERT",e.Compress="COMPRESS",e.Wrap="WRAP",e.Unwrap="UNWRAP",e.Redeem="REDEEM",e))(Wl||{}),Zte=U.z.enum(Wl),ene=U.z.object({id:n_,type:Zte,proxy_wallet:J,combo_condition_id:Zt,combo_position_id:Xe,amount_usdc:H.nullish(),payout_usdc:H.nullish(),timestamp:wo,transaction_hash:et,block_number:U.z.number().int(),legs:U.z.array(D$)}),tne=ene.transform(sne),Kt=U.z.preprocess(e=>e===""?void 0:e,U.z.string().optional()),$$=U.z.preprocess(e=>e===999?void 0:e,U.z.number().int().optional()),nne=U.z.object({proxy_wallet:J,side:Nt,token_id:Me,condition_id:xe,size:H,price:H,timestamp:wo,title:Kt,slug:Kt,icon:Kt,event_slug:Kt,outcome:Kt,outcome_index:$$,name:Kt,pseudonym:Kt,bio:Kt,profile_image:Kt,profile_image_optimized:Kt,transaction_hash:et}).transform(e=>({wallet:e.proxy_wallet,side:e.side,assetId:e.token_id,tokenId:e.token_id,conditionId:e.condition_id,size:e.size,price:e.price,timestamp:e.timestamp,title:e.title,slug:e.slug,icon:e.icon,eventSlug:e.event_slug,outcome:e.outcome,outcomeIndex:e.outcome_index,name:e.name,pseudonym:e.pseudonym,bio:e.bio,profileImage:e.profile_image,profileImageOptimized:e.profile_image_optimized,transactionHash:e.transaction_hash})),rne=U.z.object({proxy_wallet:J,timestamp:wo,condition_id:U.z.preprocess(e=>e===""?void 0:e,xe.optional()),type:KC,size:H,usdc_size:H,transaction_hash:et,price:H,token_id:U.z.preprocess(e=>e===""?void 0:e,Me.optional()),side:U.z.preprocess(e=>e===""?void 0:e,U.z.union([Nt,R$]).optional()),is_combo:U.z.boolean().optional(),outcome_index:$$,title:Kt,slug:Kt,icon:Kt,event_slug:Kt,outcome:Kt,name:Kt,pseudonym:Kt,bio:Kt,profile_image:Kt,profile_image_optimized:Kt}),one=rne.transform(ane),V$=ls(nne),j$=ls(one),z$=ls(tne);Po=(e=>(e.Max="max",e.OneMonth="1m",e.OneWeek="1w",e.OneDay="1d",e.SixHours="6h",e.OneHour="1h",e))(Po||{}),W$=U.z.enum(Po),une=U.z.object({timestamp:wo,price:H,resolution_seconds:U.z.number().int().nonnegative()}).transform(({price:e,resolution_seconds:t,timestamp:n})=>({timestamp:n,price:e,resolutionSeconds:t})),G$=ls(une),hf=U.z.preprocess(e=>e===""?null:e,U.z.string().nullable()),dne=U.z.object({proxy_wallet:J,bio:hf,token_id:Me,pseudonym:hf,amount:H,display_username_public:U.z.boolean(),outcome_index:U.z.preprocess(e=>e===999?null:e,U.z.number().int().nullable()),name:hf,profile_image:hf,profile_image_optimized:hf,verified:U.z.boolean(),avg_price:H.nullish(),entry_cost_usdc:H.nullish(),current_price:H.nullish(),current_value:H.nullish(),realized_pnl:H.nullish(),unrealized_pnl:H.nullish(),total_pnl:H.nullish()}).transform(e=>({wallet:e.proxy_wallet,assetId:e.token_id,tokenId:e.token_id,amount:e.amount,displayUsernamePublic:e.display_username_public,outcomeIndex:e.outcome_index,verified:e.verified,bio:e.bio,pseudonym:e.pseudonym,name:e.name,profileImage:e.profile_image,profileImageOptimized:e.profile_image_optimized,avgPrice:e.avg_price,entryCostUsdc:e.entry_cost_usdc,currentPrice:e.current_price,currentValue:e.current_value,realizedPnl:e.realized_pnl,unrealizedPnl:e.unrealized_pnl,totalPnl:e.total_pnl})),pne=U.z.object({token_id:Me,holders:U.z.array(dne)}).transform(({holders:e,token_id:t})=>({assetId:t,token:t,holders:e})),mne=U.z.object({condition_id:U.z.union([xe,U.z.literal("GLOBAL")]),value:H}).transform(({condition_id:e,value:t})=>({conditionId:e==="GLOBAL"?null:e,value:t})),hne=U.z.object({condition_id:U.z.preprocess(Gn,xe.nullable()),taker_volume:H}).transform(({condition_id:e,taker_volume:t})=>({conditionId:e,takerVolume:t})),fne=U.z.object({taker_volume_total:H,conditions:U.z.array(hne)}).transform(({conditions:e,taker_volume_total:t})=>({markets:e,takerVolumeTotal:t})),K$=ls(pne),Y$=si(U.z.array(mne)),Q$=si(fne),Gl=(e=>(e.Day="day",e.Week="week",e.Month="month",e.All="all",e))(Gl||{}),ff=U.z.enum(Gl),Kl=(e=>(e.Day="day",e.Week="week",e.Month="month",e.Year="all",e))(Kl||{}),X$=U.z.enum(Kl),Yl=(e=>(e.Pnl="PNL",e.Volume="VOLUME",e))(Yl||{}),J$=U.z.enum(Yl),Ql=(e=>(e.Market="market",e.Combo="combo",e))(Ql||{}),YCe=U.z.enum(Ql),gne=U.z.object({rank:U.z.number().int().positive(),builder_name:U.z.string(),builder_code:bo,profile_image:U.z.string(),verified:U.z.boolean(),volume:H,active_users:U.z.number().int().min(0)}).transform(({active_users:e,builder_code:t,builder_name:n,profile_image:r,...o})=>({...o,activeUsers:e,builderCode:t,builderName:n,...r===""?{}:{profileImage:r}})),yne=U.z.object({date:Wn,rank:U.z.number().int().min(0),builder_name:U.z.string(),builder_code:bo,profile_image:U.z.string(),verified:U.z.boolean(),volume:H,active_users:U.z.number().int().min(0)}).transform(({active_users:e,builder_code:t,builder_name:n,date:r,profile_image:o,...s})=>({...s,activeUsers:e,bucketDate:r,builderCode:t,builderName:n,...o===""?{}:{profileImage:o}})),as=U.z.preprocess(Gn,U.z.string().nullable()),bne=U.z.object({rank:U.z.number().int().min(0),user_id:J,pnl:H,volume:H,user_name:as,profile_image:as,x_username:as,verified:U.z.boolean()}).transform(({profile_image:e,user_id:t,user_name:n,x_username:r,...o})=>({...o,wallet:t,userName:n,profileImage:e,xUsername:r})),wne=U.z.object({user_id:J,pnl:H,volume:H,rank_pnl:U.z.number().int().positive().nullable(),rank_volume:U.z.number().int().positive().nullable(),user_name:as,profile_image:as,x_username:as,verified:U.z.boolean()}).transform(({profile_image:e,rank_pnl:t,rank_volume:n,user_id:r,user_name:o,x_username:s,...i})=>({...i,wallet:r,pnlRank:t,volumeRank:n,userName:o,profileImage:e,xUsername:s})),vne=U.z.object({win_rank:U.z.number().int().positive(),kind:U.z.literal("market"),user_id:J,pnl:H,initial_value:H,final_value:H,resolved_at:wo,condition_id:xe,position_id:Me,event_id:Gt,event_slug:U.z.string(),event_title:U.z.string(),user_name:as,profile_image:as}),kne=U.z.object({win_rank:U.z.number().int().positive(),kind:U.z.literal("combo"),user_id:J,pnl:H,initial_value:H,final_value:H,resolved_at:wo,condition_id:Zt,position_id:Xe,event_id:U.z.literal(0),event_slug:U.z.literal(""),event_title:U.z.string(),user_name:as,profile_image:as}),xne=U.z.discriminatedUnion("kind",[vne,kne]).transform(e=>e.kind==="combo"?{rank:e.win_rank,kind:e.kind,wallet:e.user_id,pnl:e.pnl,initialValue:e.initial_value,finalValue:e.final_value,resolvedAt:e.resolved_at,conditionId:e.condition_id,positionId:e.position_id,eventId:null,eventSlug:null,eventTitle:e.event_title,userName:e.user_name,profileImage:e.profile_image}:{rank:e.win_rank,kind:e.kind,wallet:e.user_id,pnl:e.pnl,initialValue:e.initial_value,finalValue:e.final_value,resolvedAt:e.resolved_at,conditionId:e.condition_id,assetId:e.position_id,eventId:e.event_id,eventSlug:e.event_slug,eventTitle:e.event_title,userName:e.user_name,profileImage:e.profile_image}),Z$=ls(gne),e4=si(U.z.array(yne)),t4=ls(bne),n4=si(wne.nullable()),r4=ls(xne),Xl=(e=>(e.Initialized="initialized",e.Posed="posed",e.Proposed="proposed",e.Challenged="challenged",e.Reproposed="reproposed",e.Disputed="disputed",e.Active="active",e.Arbitration="arbitration",e.Resolved="resolved",e))(Xl||{}),Ane=U.z.enum(Xl),Jl=(e=>(e.Binary="BINARY",e.IncrementalNegRisk="INCREMENTAL_NEGRISK",e.AtomicNegRisk="ATOMIC_NEGRISK",e))(Jl||{}),Tne=U.z.enum(Jl),Zl=(e=>(e.Reported="reported",e.Derived="derived",e))(Zl||{}),Sne=U.z.enum(Zl),ec=(e=>(e.UmaOptimisticOracle="UMA_OO",e.Chainlink="CHAINLINK",e.Eoa="EOA",e))(ec||{}),Pne=U.z.enum(ec),E$=U.z.number().int().min(0).transform(String).pipe(yn),Ene=U.z.object({question_id:vo.optional(),condition_id:xe.optional(),status:Ane,extended_review:U.z.boolean(),was_disputed:U.z.boolean(),new_version_q:U.z.boolean(),proposed_price:R.optional(),reproposed_price:R.optional(),price:R.optional(),transaction_hash:U.z.preprocess(Gn,et.nullable()),log_index:U.z.preprocess(Gn,U.z.string().regex(/^\d+$/).transform(Number).nullable()),last_update_timestamp:Xi,market_type:Tne.optional(),payouts:U.z.tuple([E$,E$]).optional(),resolution_source:Sne.optional(),reporter:Pne.optional(),was_arbitrated:U.z.boolean().optional(),resolved_block:U.z.number().int().min(0).optional(),resolved_at:oe.optional()}).transform(e=>{let t={status:e.status,extendedReview:e.extended_review,wasDisputed:e.was_disputed,questionRulesUpdated:e.new_version_q,transactionHash:e.transaction_hash,logIndex:e.log_index,lastUpdatedAt:e.last_update_timestamp};return e.question_id!==void 0&&(t.questionId=e.question_id),e.condition_id!==void 0&&(t.conditionId=e.condition_id),e.proposed_price!==void 0&&e.proposed_price!=="69"&&(t.proposedPrice=e.proposed_price),e.reproposed_price!==void 0&&e.reproposed_price!=="69"&&(t.reproposedPrice=e.reproposed_price),e.price!==void 0&&e.price!=="69"&&(t.price=e.price),e.market_type!==void 0&&(t.marketType=e.market_type),e.payouts!==void 0&&(t.payouts=e.payouts),e.resolution_source!==void 0&&(t.resolutionSource=e.resolution_source),e.reporter!==void 0&&(t.reporter=e.reporter),e.was_arbitrated!==void 0&&(t.wasArbitrated=e.was_arbitrated),e.resolved_block!==void 0&&(t.resolvedBlock=e.resolved_block),e.resolved_at!==void 0&&(t.resolvedAt=e.resolved_at),t}),o4=si(U.z.array(Ene))});var Pe,Od,s4,f0,i4,_r,JCe,Rne,Ld,a4,Ine,l4,_ne,Cne,Nne,One,Lne,c4,QC,u4,d4,p4=L(()=>{"use strict";xo();Pe=require("zod"),Od=(e=>(e.SUBMITTED="SUBMITTED",e.REGISTRY_PENDING="REGISTRY_PENDING",e.REGISTERED="REGISTERED",e.FAILED="FAILED",e.SUPERSEDED="SUPERSEDED",e.REPAIR_REQUIRED="REPAIR_REQUIRED",e))(Od||{}),s4=Pe.z.object({status:Pe.z.enum(Od),transactionHash:et.nullish().transform(e=>e??null),transactionId:ea}),f0=(e=>(e.PENDING="PENDING",e.FENCED="FENCED",e.SWEPT="SWEPT",e.CHAIN_SUBMITTED="CHAIN_SUBMITTED",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED",e))(f0||{}),i4=Pe.z.object({status:Pe.z.enum(f0),transactionId:ea}),_r=(e=>(e.SAFE="SAFE",e.PROXY="PROXY",e.SAFE_CREATE="SAFE-CREATE",e.WALLET="WALLET",e.WALLET_CREATE="WALLET-CREATE",e))(_r||{}),JCe=Pe.z.enum(_r),Rne=Pe.z.enum(["PROXY","SAFE","SAFE-CREATE"]),Ld=(e=>(e.STATE_NEW="STATE_NEW",e.STATE_EXECUTED="STATE_EXECUTED",e.STATE_MINED="STATE_MINED",e.STATE_CONFIRMED="STATE_CONFIRMED",e.STATE_INVALID="STATE_INVALID",e.STATE_FAILED="STATE_FAILED",e))(Ld||{}),a4=Pe.z.enum(Ld),Ine=Pe.z.object({baseGas:Pe.z.string().optional(),gasLimit:Pe.z.string().optional(),gasPrice:Pe.z.string().optional(),gasToken:J.optional(),operation:Pe.z.string().optional(),payment:Pe.z.string().optional(),paymentReceiver:J.optional(),paymentToken:J.optional(),refundReceiver:J.optional(),relay:J.optional(),relayHub:J.optional(),relayerFee:Pe.z.string().optional(),safeTxnGas:Pe.z.string().optional()}),l4=Pe.z.object({address:J,nonce:Pe.z.string().min(1)}),_ne=Pe.z.object({data:Pe.z.string().min(1),from:J,metadata:Pe.z.string().optional(),nonce:Pe.z.string().min(1).optional(),proxyWallet:J,signature:Pe.z.string().min(1),signatureParams:Ine,to:J,type:Rne,value:Pe.z.string().optional()}),Cne=Pe.z.object({data:Pe.z.string().min(1),target:J,value:Pe.z.string().min(1)}),Nne=Pe.z.object({calls:Pe.z.array(Cne).min(1),deadline:Pe.z.string().min(1),depositWallet:J}),One=Pe.z.object({depositWalletParams:Nne,from:J,metadata:Pe.z.string().optional(),nonce:Pe.z.string().min(1),signature:Pe.z.string().min(1),to:J,type:Pe.z.literal("WALLET")}),Lne=Pe.z.object({from:J,metadata:Pe.z.string().optional(),to:J,type:Pe.z.literal("WALLET-CREATE")}),c4=Pe.z.union([_ne,One,Lne]),QC=Pe.z.object({state:a4,transactionHash:et.nullish().transform(e=>e??null),transactionID:ea}).transform(({transactionHash:e,transactionID:t,...n})=>({...n,transactionHash:e??null,transactionId:t})),u4=Pe.z.object({deployed:Pe.z.boolean()}),d4=Pe.z.object({error_msg:Pe.z.string().nullish(),state:a4,transaction_hash:Pe.z.union([Pe.z.literal(""),et]).transform(e=>e===""?null:e),transaction_id:ea}).transform(({error_msg:e,transaction_hash:t,transaction_id:n,...r})=>({...r,errorMsg:e??null,transactionHash:t??null,transactionId:n}))});var te,Nn,Eo,cs,us,Qr,Cr,JC,ZC,Dne,Une,Bne,Mne,m4,Fne,qne,Hne,$ne,Vne,jne,zne,Wne,Gne,Kne,Yne,h4,mn,li,ci,Ro,f4,Qne,Xne,Jne,Zne,ere,g4,eN,tN,Dd,tre,nre,XC,rre,y4,b4,w4,g0=L(()=>{"use strict";RC();xo();te=require("zod");Tl();Nn=(e=>(e.Buy="BUY",e.Sell="SELL",e))(Nn||{}),Eo=(e=>(e.Yes="YES",e.No="NO",e))(Eo||{}),cs=(e=>(e.Confirm="CONFIRM",e.Decline="DECLINE",e))(cs||{}),us=(e=>(e.Matched="MATCHED",e.Mined="MINED",e.Confirmed="CONFIRMED",e.Retrying="RETRYING",e.Failed="FAILED",e))(us||{}),Qr=(e=>(e.Notional="notional",e.Shares="shares",e))(Qr||{}),Cr=(e=>(e.AddressMismatch="ADDRESS_MISMATCH",e.AllowanceValidationFailed="ALLOWANCE_VALIDATION_FAILED",e.BalanceValidationFailed="BALANCE_VALIDATION_FAILED",e.ContradictoryLegs="CONTRADICTORY_LEGS",e.ExpiredRfq="EXPIRED_RFQ",e.InvalidAcceptance="INVALID_ACCEPTANCE",e.InvalidConfirmation="INVALID_CONFIRMATION",e.InvalidExecutionResult="INVALID_EXECUTION_RESULT",e.InvalidIdentity="INVALID_IDENTITY",e.InvalidMessage="INVALID_MESSAGE",e.InvalidOrderSide="INVALID_ORDER_SIDE",e.InvalidQuote="INVALID_QUOTE",e.InvalidRfq="INVALID_RFQ",e.InvalidRfqState="INVALID_RFQ_STATE",e.InvalidRole="INVALID_ROLE",e.InvalidSignature="INVALID_SIGNATURE",e.InvalidSignatureType="INVALID_SIGNATURE_TYPE",e.InternalError="INTERNAL_ERROR",e.LegMetadataUnavailable="LEG_METADATA_UNAVAILABLE",e.MakerAlreadyResponded="MAKER_ALREADY_RESPONDED",e.MakerDeclined="MAKER_DECLINED",e.MakerNotRequired="MAKER_NOT_REQUIRED",e.MakerQuoteLimited="MAKER_QUOTE_LIMITED",e.MissingMakerAddressInQuote="MISSING_MAKER_ADDRESS_IN_QUOTE",e.MissingMakerAmountInSignedOrder="MISSING_MAKER_AMOUNT_IN_SIGNED_ORDER",e.MissingMakerInSignedOrder="MISSING_MAKER_IN_SIGNED_ORDER",e.MissingQuoteId="MISSING_QUOTE_ID",e.MissingRfqId="MISSING_RFQ_ID",e.MissingSaltInSignedOrder="MISSING_SALT_IN_SIGNED_ORDER",e.MissingSignatureInSignedOrder="MISSING_SIGNATURE_IN_SIGNED_ORDER",e.MissingSignerAddressInQuote="MISSING_SIGNER_ADDRESS_IN_QUOTE",e.MissingSignerInSignedOrder="MISSING_SIGNER_IN_SIGNED_ORDER",e.MissingTakerAmountInSignedOrder="MISSING_TAKER_AMOUNT_IN_SIGNED_ORDER",e.MissingTimestampInSignedOrder="MISSING_TIMESTAMP_IN_SIGNED_ORDER",e.MissingTokenIdInSignedOrder="MISSING_TOKEN_ID_IN_SIGNED_ORDER",e.NoQuotes="NO_QUOTES",e.OrderSideOrTokenDoesNotMatchRequest="ORDER_SIDE_OR_TOKEN_DOES_NOT_MATCH_REQUEST",e.PreExecutionBalanceReservationFailed="PRE_EXECUTION_BALANCE_RESERVATION_FAILED",e.PriceE6NotPositive="PRICE_E6_NOT_POSITIVE",e.QuoteMismatch="QUOTE_MISMATCH",e.QuoteUnavailable="QUOTE_UNAVAILABLE",e.QuotedPriceAboveSafetyThreshold="QUOTED_PRICE_ABOVE_SAFETY_THRESHOLD",e.QuotedPriceOutOfRange="QUOTED_PRICE_OUT_OF_RANGE",e.RateLimited="RATE_LIMITED",e.RequestFailed="REQUEST_FAILED",e.ServiceUnavailable="SERVICE_UNAVAILABLE",e.SignedOrderMakerAmountNotPositive="SIGNED_ORDER_MAKER_AMOUNT_NOT_POSITIVE",e.SignedOrderMakerDoesNotMatchAuth="SIGNED_ORDER_MAKER_DOES_NOT_MATCH_AUTH",e.SignedOrderPriceWorseThanQuote="SIGNED_ORDER_PRICE_WORSE_THAN_QUOTE",e.SignedOrderSignatureTypeDoesNotMatchAuth="SIGNED_ORDER_SIGNATURE_TYPE_DOES_NOT_MATCH_AUTH",e.SignedOrderSignerDoesNotMatchAuth="SIGNED_ORDER_SIGNER_DOES_NOT_MATCH_AUTH",e.SignedOrderSizeDoesNotCoverQuote="SIGNED_ORDER_SIZE_DOES_NOT_COVER_QUOTE",e.SignedOrderTakerAmountNotPositive="SIGNED_ORDER_TAKER_AMOUNT_NOT_POSITIVE",e.SizeE6NotPositive="SIZE_E6_NOT_POSITIVE",e.SizeTooLarge="SIZE_TOO_LARGE",e.SubmissionWindowClosed="SUBMISSION_WINDOW_CLOSED",e.TradeSubmissionFailed="TRADE_SUBMISSION_FAILED",e.Unauthenticated="UNAUTHENTICATED",e.UnauthorizedRole="UNAUTHORIZED_ROLE",e.UnknownRfq="UNKNOWN_RFQ",e))(Cr||{}),JC=te.z.enum(Nn),ZC=te.z.literal("YES"),Dne=te.z.enum(cs),Une=te.z.enum(us),Bne=te.z.string().transform(e=>e),Mne=te.z.object({id:Ji,condition_id:xe,position_ids:te.z.array(Xe),pending:te.z.boolean(),slug:te.z.string(),title:te.z.string(),outcomes:te.z.array(te.z.string()),outcome_prices:te.z.array(R),image:te.z.string(),volume:te.z.number(),tags:te.z.array(te.z.string())}).superRefine((e,t)=>{e.outcomes.length!==2&&t.addIssue({code:"custom",message:`Expected binary combo market outcomes, received ${e.outcomes.length}.`,path:["outcomes"]}),e.position_ids.length!==e.outcomes.length&&t.addIssue({code:"custom",message:"Expected position_ids and outcomes to have matching lengths.",path:["position_ids"]}),e.outcome_prices.length!==e.outcomes.length&&t.addIssue({code:"custom",message:"Expected outcome_prices and outcomes to have matching lengths.",path:["outcome_prices"]})}).transform(e=>({conditionId:e.condition_id,id:e.id,image:e.image,pending:e.pending,outcomes:{yes:{label:e.outcomes[0],positionId:e.position_ids[0],price:e.outcome_prices[0]},no:{label:e.outcomes[1],positionId:e.position_ids[1],price:e.outcome_prices[1]}},slug:e.slug,tags:e.tags,title:e.title,volume:e.volume})),m4=te.z.object({markets:te.z.array(Mne),next_cursor:ye.nullish()}).transform(e=>({markets:e.markets,nextCursor:e.next_cursor??void 0})),Fne=te.z.discriminatedUnion("unit",[te.z.object({unit:te.z.literal("notional"),value_e6:yn}),te.z.object({unit:te.z.literal("shares"),value_e6:yn})]).transform(e=>({unit:e.unit,value:e.value_e6})),qne=(e=>(e.Auth="auth",e.QuoteRequest="RFQ_REQUEST",e.QuoteAck="ACK_RFQ_QUOTE",e.QuoteCancelAck="ACK_RFQ_QUOTE_CANCEL",e.ConfirmationRequest="RFQ_CONFIRMATION_REQUEST",e.ConfirmationAck="ACK_RFQ_CONFIRMATION_RESPONSE",e.ExecutionUpdate="RFQ_EXECUTION_UPDATE",e.Trade="RFQ_TRADE",e.Error="RFQ_ERROR",e))(qne||{}),Hne=te.z.object({type:te.z.literal("auth"),success:te.z.boolean(),address:J.optional(),role:te.z.string().optional(),error:te.z.string().optional()}),$ne=te.z.object({type:te.z.literal("RFQ_REQUEST"),rfq_id:ar,requestor_public_id:Ew,leg_position_ids:te.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:JC,side:ZC,requested_size:Fne,submission_deadline:pe}).transform(e=>({conditionId:e.condition_id,direction:e.direction,legPositionIds:e.leg_position_ids,noPositionId:e.no_position_id,requestorPublicId:e.requestor_public_id,requestedSize:e.requested_size,rfqId:e.rfq_id,side:e.side,submissionDeadline:e.submission_deadline,type:"quote_request",yesPositionId:e.yes_position_id})),Vne=te.z.object({type:te.z.literal("ACK_RFQ_QUOTE"),rfq_id:ar,quote_id:Zi}).transform(e=>({quoteId:e.quote_id,rfqId:e.rfq_id,type:"quote_ack"})),jne=te.z.object({type:te.z.literal("ACK_RFQ_QUOTE_CANCEL"),rfq_id:ar,quote_id:Zi}).transform(e=>({quoteId:e.quote_id,rfqId:e.rfq_id,type:"quote_cancel_ack"})),zne=te.z.object({type:te.z.literal("RFQ_CONFIRMATION_REQUEST"),rfq_id:ar,quote_id:Zi,signer_address:J,maker_address:J,signature_type:EC,leg_position_ids:te.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:JC,side:ZC,fill_size_e6:yn,price_e6:yn,confirm_by:pe}).transform(e=>({conditionId:e.condition_id,confirmBy:e.confirm_by,direction:e.direction,fillSize:e.fill_size_e6,legPositionIds:e.leg_position_ids,makerAddress:e.maker_address,noPositionId:e.no_position_id,price:e.price_e6,quoteId:e.quote_id,rfqId:e.rfq_id,side:e.side,signatureType:e.signature_type,signerAddress:e.signer_address,type:"confirmation_request",yesPositionId:e.yes_position_id})),Wne=te.z.object({type:te.z.literal("ACK_RFQ_CONFIRMATION_RESPONSE"),rfq_id:ar,quote_id:Zi,decision:Dne}).transform(e=>({decision:e.decision,quoteId:e.quote_id,rfqId:e.rfq_id,type:"confirmation_ack"})),Gne=te.z.object({type:te.z.literal("RFQ_EXECUTION_UPDATE"),rfq_id:ar,status:Une,tx_hash:et.optional()}).transform(e=>({rfqId:e.rfq_id,status:e.status,...e.tx_hash===void 0?{}:{txHash:e.tx_hash},type:"execution_update"})),Kne=te.z.object({type:te.z.literal("RFQ_TRADE"),rfq_id:ar,requester_id:Ew,condition_id:Zt,leg_position_ids:te.z.array(Xe),direction:JC,side:ZC,price_e6:yn,size_e6:yn,executed_at:pe}).transform(e=>({conditionId:e.condition_id,direction:e.direction,executedAt:e.executed_at,legPositionIds:e.leg_position_ids,price:e.price_e6,requesterId:e.requester_id,rfqId:e.rfq_id,side:e.side,size:e.size_e6,type:"trade"})),Yne=te.z.object({type:te.z.literal("RFQ_ERROR"),error_id:te.z.string().optional(),request_type:te.z.string().optional(),rfq_id:ar.optional(),quote_id:Zi.optional(),code:Bne,error:te.z.string(),request:te.z.unknown().optional()}).transform(e=>({code:e.code,errorId:e.error_id,message:e.error,quoteId:e.quote_id,requestType:e.request_type,rfqId:e.rfq_id,type:"rfq_error"})),h4=te.z.discriminatedUnion("type",[Hne,$ne,Vne,jne,zne,Wne,Gne,Kne,Yne]),mn=(e=>(e.AwaitingRequesterAcceptance="AWAITING_REQUESTER_ACCEPTANCE",e.AwaitingMakerConfirmation="AWAITING_MAKER_CONFIRMATION",e.Executing="EXECUTING",e.Filled="FILLED",e.Failed="FAILED",e.Expired="EXPIRED",e.Canceled="CANCELED",e))(mn||{}),li=(e=>(e.InvalidJson="INVALID_JSON",e.InvalidMessage="INVALID_MESSAGE",e.InvalidRole="INVALID_ROLE",e.UnauthorizedRole="UNAUTHORIZED_ROLE",e.Unauthenticated="UNAUTHENTICATED",e.AddressMismatch="ADDRESS_MISMATCH",e.InvalidRfq="INVALID_RFQ",e.ContradictoryLegs="CONTRADICTORY_LEGS",e.LegMetadataUnavailable="LEG_METADATA_UNAVAILABLE",e.InvalidAcceptance="INVALID_ACCEPTANCE",e.InvalidQuote="INVALID_QUOTE",e.InvalidSignature="INVALID_SIGNATURE",e.InvalidIdentity="INVALID_IDENTITY",e.UnknownRfq="UNKNOWN_RFQ",e.ExpiredRfq="EXPIRED_RFQ",e.InvalidRfqState="INVALID_RFQ_STATE",e.QuoteMismatch="QUOTE_MISMATCH",e.SubmissionWindowClosed="SUBMISSION_WINDOW_CLOSED",e.ServiceUnavailable="SERVICE_UNAVAILABLE",e.PreExecutionBalanceReservationFailed="PRE_EXECUTION_BALANCE_RESERVATION_FAILED",e.BalanceValidationFailed="BALANCE_VALIDATION_FAILED",e.AllowanceValidationFailed="ALLOWANCE_VALIDATION_FAILED",e.TradeSubmissionFailed="TRADE_SUBMISSION_FAILED",e.RequestFailed="REQUEST_FAILED",e))(li||{}),ci=(e=>(e.NoQuotes="NO_QUOTES",e.SizeTooLarge="SIZE_TOO_LARGE",e))(ci||{}),Ro=(e=>(e.MakerDeclined="MAKER_DECLINED",e.AcceptanceWindowExpired="ACCEPTANCE_WINDOW_EXPIRED",e.ExecutionFailed="EXECUTION_FAILED",e))(Ro||{}),f4=te.z.object({code:te.z.string().transform(e=>e),message:te.z.string()}).transform(e=>({code:e.code,message:e.message})),Qne=te.z.object({quote_id:Zi,blended_price_e6:yn,maker_amount_e6:yn,taker_amount_e6:yn,total_required_e6:yn,net_receive_e6:yn.optional()}).transform(e=>({blendedPrice:e.blended_price_e6,makerAmount:e.maker_amount_e6,quoteId:e.quote_id,takerAmount:e.taker_amount_e6,totalRequired:e.total_required_e6,...e.net_receive_e6===void 0?{}:{netReceive:e.net_receive_e6}})),Xne=te.z.object({unit:te.z.enum(Qr),value_e6:te.z.string().regex(/^\d+$/).transform(e=>BigInt(e).toString())}).transform(e=>({unit:e.unit,valueE6:e.value_e6})),Jne=te.z.object({rfq_id:ar,leg_position_ids:te.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:te.z.enum(Nn),side:te.z.enum(Eo),requested_size:Xne}).transform(e=>({conditionId:e.condition_id,direction:e.direction,legPositionIds:e.leg_position_ids,noPositionId:e.no_position_id,requestedSize:e.requested_size,rfqId:e.rfq_id,side:e.side,yesPositionId:e.yes_position_id})),Zne=te.z.object({rfq_id:ar,status:te.z.literal("AWAITING_REQUESTER_ACCEPTANCE"),expires_at:pe,builder_code:bo,request:Jne,quote:Qne}).transform(e=>({builderCode:e.builder_code,expiresAt:e.expires_at,quote:e.quote,request:e.request,rfqId:e.rfq_id,status:e.status})),ere=te.z.object({rfq_id:ar,status:te.z.enum(["FAILED","EXPIRED","CANCELED"]),error:f4.optional()}).transform(e=>({rfqId:e.rfq_id,status:e.status,...e.error===void 0?{}:{error:e.error}})),g4=te.z.union([Zne,ere]),eN=te.z.object({rfq_id:ar,status:te.z.union([te.z.enum(mn),te.z.enum(us)]),taker_order_hash:te.z.string().optional(),tx_hash:et.optional(),error:f4.optional()}).transform(e=>({rfqId:e.rfq_id,status:e.status,...e.taker_order_hash===void 0?{}:{takerOrderHash:e.taker_order_hash},...e.tx_hash===void 0?{}:{txHash:e.tx_hash},...e.error===void 0?{}:{error:e.error}})),tN=te.z.string().transform(e=>zn(e)),Dd=(e=>(e.Split="split",e.Merge="merge",e.Redeem="redeem",e.SplitOnCondition="split_on_condition",e.MergeOnCondition="merge_on_condition",e.SplitOnEvent="split_on_event",e.MergeOnEvent="merge_on_event",e.ConvertOnEvent="convert_on_event",e.Extract="extract",e.Inject="inject",e.ConvertToYesBasket="convert_to_yes_basket",e.MergeFromYesBasket="merge_from_yes_basket",e.Compress="compress",e))(Dd||{}),tre=te.z.string().transform(e=>e),nre=te.z.object({kind:tre,condition_id:Zt.optional(),event_id:Gt.optional(),position_id:Xe.optional(),condition_index:te.z.number().int().nonnegative().optional().default(0),amount:yn}).transform(e=>({amount:e.amount,conditionId:e.condition_id,conditionIndex:e.condition_index,eventId:e.event_id,kind:e.kind,positionId:e.position_id})),XC=te.z.object({position_id:Xe,amount:yn}).transform(e=>({amount:e.amount,positionId:e.position_id})),rre=te.z.object({consumed:te.z.array(XC),created:te.z.array(XC)}).transform(e=>({consumed:e.consumed,created:e.created})),y4=te.z.object({to:J,data:tN}).transform(e=>({data:e.data,to:e.to})),b4=te.z.looseObject({planHash:tN,chainId:te.z.number().int(),wallet:J,routerCall:y4}),w4=te.z.object({plan_hash:tN,chain_id:te.z.number().int(),wallet:J,block_number:te.z.string().regex(/^\d+$/).transform(BigInt),starting_pusd:R,net_pusd_out:R,final_pusd:R,operations:te.z.array(nre),operation_count:te.z.number().int(),truncated:te.z.boolean(),estimated_cost:te.z.number(),required_pusd_input:R,required_positions:te.z.array(XC),position_summary:rre.optional(),candidate_position_ids:te.z.array(Xe),router_call:y4}).transform(e=>({blockNumber:e.block_number,candidatePositionIds:e.candidate_position_ids,chainId:e.chain_id,estimatedCost:e.estimated_cost,finalPusd:e.final_pusd,netPusdOut:e.net_pusd_out,operationCount:e.operation_count,operations:e.operations,planHash:e.plan_hash,positionSummary:e.position_summary??{consumed:[],created:[]},requiredPositions:e.required_positions,requiredPusdInput:e.required_pusd_input,routerCall:e.router_call,startingPusd:e.starting_pusd,truncated:e.truncated,wallet:e.wallet}))});var tc,v4,nN,ore,k4,rN=L(()=>{"use strict";AC();xo();tc=require("zod"),v4=tc.z.number().int().transform(e=>e===0?null:pd(e)),nN=tc.z.object({status:tc.z.literal("ok"),deadline:v4}),ore=tc.z.object({deadline:v4,triggered:tc.z.number().int().nonnegative(),daily_limit:tc.z.number().int().nonnegative(),next_reset:pe}).transform(e=>({deadline:e.deadline,triggered:e.triggered,dailyLimit:e.daily_limit,nextReset:e.next_reset})),k4=ore});function x4(e){let t=e.length,n=0,r=0;for(;r<t;){let o=e.charCodeAt(r++);if((o&4294967168)===0){n++;continue}else if((o&4294965248)===0)n+=2;else{if(o>=55296&&o<=56319&&r<t){let s=e.charCodeAt(r);(s&64512)===56320&&(++r,o=((o&1023)<<10)+(s&1023)+65536)}(o&4294901760)===0?n+=3:n+=4}}return n}function sre(e,t,n){let r=e.length,o=n,s=0;for(;s<r;){let i=e.charCodeAt(s++);if((i&4294967168)===0){t[o++]=i;continue}else if((i&4294965248)===0)t[o++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&s<r){let a=e.charCodeAt(s);(a&64512)===56320&&(++s,i=((i&1023)<<10)+(a&1023)+65536)}(i&4294901760)===0?(t[o++]=i>>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=i&63|128}}function lre(e,t,n){ire.encodeInto(e,t.subarray(n))}function A4(e,t,n){e.length>are?lre(e,t,n):sre(e,t,n)}var ire,are,uNe,T4=L(()=>{"use strict";ire=new TextEncoder,are=50;uNe=new TextDecoder});var nc,S4=L(()=>{"use strict";nc=class{type;data;constructor(t,n){this.type=t,this.data=n}}});var y0,P4=L(()=>{"use strict";y0=class e extends Error{constructor(t){super(t);let n=Object.create(e.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}});function E4(e,t,n){let r=n/4294967296,o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function b0(e,t,n){let r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function R4(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}var oN=L(()=>{"use strict"});function pre({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=dre)if(t===0&&e<=ure){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e),n}else{let n=e/4294967296,r=e&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,t<<2|n&3),s.setUint32(4,r),o}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),b0(r,4,e),n}}function mre(e){let t=e.getTime(),n=Math.floor(t/1e3),r=(t-n*1e3)*1e6,o=Math.floor(r/1e9);return{sec:n+o,nsec:r-o*1e9}}function hre(e){if(e instanceof Date){let t=mre(e);return pre(t)}else return null}function fre(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let n=t.getUint32(0),r=t.getUint32(4),o=(n&3)*4294967296+r,s=n>>>2;return{sec:o,nsec:s}}case 12:{let n=R4(t,4),r=t.getUint32(0);return{sec:n,nsec:r}}default:throw new y0(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function gre(e){let t=fre(e);return new Date(t.sec*1e3+t.nsec/1e6)}var cre,ure,dre,I4,_4=L(()=>{"use strict";P4();oN();cre=-1,ure=4294967296-1,dre=17179869184-1;I4={type:cre,encode:hre,decode:gre}});var w0,C4=L(()=>{"use strict";S4();_4();w0=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(I4)}register({type:t,encode:n,decode:r}){if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{let o=-1-t;this.builtInEncoders[o]=n,this.builtInDecoders[o]=r}}tryToEncode(t,n){for(let r=0;r<this.builtInEncoders.length;r++){let o=this.builtInEncoders[r];if(o!=null){let s=o(t,n);if(s!=null){let i=-1-r;return new nc(i,s)}}}for(let r=0;r<this.encoders.length;r++){let o=this.encoders[r];if(o!=null){let s=o(t,n);if(s!=null){let i=r;return new nc(i,s)}}}return t instanceof nc?t:null}decode(t,n,r){let o=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return o?o(t,n,r):new nc(n,t)}}});function yre(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function N4(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):yre(e)?new Uint8Array(e):Uint8Array.from(e)}var O4=L(()=>{"use strict"});var bre,wre,v0,L4=L(()=>{"use strict";T4();C4();oN();O4();bre=100,wre=2048,v0=class e{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??w0.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??bre,this.initialBufferSize=t?.initialBufferSize??wre,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,n)}ensureBufferSizeToWrite(t){let n=this.pos+t;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(t){let n=new ArrayBuffer(t),r=new Uint8Array(n),o=new DataView(n);r.set(this.bytes),this.view=o,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(t){t===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let r=x4(t);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),A4(t,this.bytes,this.pos),this.pos+=r}encodeObject(t,n){let r=this.extensionCodec.tryToEncode(t,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(t))this.encodeArray(t,n);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let n=t.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let r=N4(t);this.writeU8a(r)}encodeArray(t,n){let r=t.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let o of t)this.doEncode(o,n+1)}countWithoutUndefined(t,n){let r=0;for(let o of n)t[o]!==void 0&&r++;return r}encodeMap(t,n){let r=Object.keys(t);this.sortKeys&&r.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(t,r):r.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let s of r){let i=t[s];this.ignoreUndefined&&i===void 0||(this.encodeString(s),this.doEncode(i,n+1))}}encodeExtension(t){if(typeof t.data=="function"){let r=t.data(this.pos+6),o=r.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(t.type),this.writeU8a(r);return}let n=t.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let n=t.length;this.ensureBufferSizeToWrite(n),this.bytes.set(t,this.pos),this.pos+=n}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),E4(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),b0(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}});function sN(e,t){return new v0(t).encodeSharedRef(e)}var D4=L(()=>{"use strict";L4()});var U4=L(()=>{"use strict";D4()});function ui(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}var iN=L(()=>{"use strict"});var k0,Ud,B4=L(()=>{"use strict";k0=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Ud=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new k0(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let n=this.head;this.head=n.next=new k0(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let n=this.tail.next;this.tail.next=null,this.tail=n,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}});function Bd(e={}){return vre(n=>{let r=n.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},e)}function vre(e,t){t=t??{};let n=t.onEnd,r=new Ud,o,s,i,a=ui(),l=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((y,w)=>{s=v=>{s=null,r.push(v);try{y(e(r))}catch(x){w(x)}return o}}):e(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ui()})}},c=y=>s!=null?s(y):(r.push(y),o),u=y=>(r=new Ud,s!=null?s({error:y}):(r.push({error:y}),o)),d=y=>{if(i)return o;if(t?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:y})},p=y=>i?o:(i=!0,y!=null?u(y):c({done:!0})),m=()=>(r=new Ud,p(),{done:!0}),g=y=>(p(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:l,return:m,throw:g,push:d,end:p,get readableLength(){return r.size},onEmpty:async y=>{let w=y?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let v,x;w!=null&&(v=new Promise((k,S)=>{x=()=>{S(new aN)},w.addEventListener("abort",x)}));try{await Promise.race([a.promise,v])}finally{x!=null&&w!=null&&w?.removeEventListener("abort",x)}}},n==null)return o;let f=o;return o={[Symbol.asyncIterator](){return this},next(){return f.next()},throw(y){return f.throw(y),n!=null&&(n(y),n=void 0),{done:!0}},return(){return f.return(),n!=null&&(n(),n=void 0),{done:!0}},push:d,end(y){return f.end(y),n!=null&&(n(y),n=void 0),o},get readableLength(){return f.readableLength},onEmpty:y=>f.onEmpty(y)},o}var aN,lN=L(()=>{"use strict";iN();B4();aN=class extends Error{type;code;constructor(t,n){super(t??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}});function kre(e){return e.reason}function M4(e,t,n){if(t==null||e==null)return e;let r=n?.translateError??kre;if(t.aborted)return e.catch(()=>{}),Promise.reject(r(t));let o;return Promise.race([e,new Promise((s,i)=>{o=()=>{i(r(t))},t.addEventListener("abort",o)})]).finally(()=>{o!=null&&t.removeEventListener("abort",o)})}var F4=L(()=>{"use strict"});function q4(){return new cN}var cN,H4=L(()=>{"use strict";iN();F4();cN=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ui(),this.haveNext=ui()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ui(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,n){await this._push(t,n)}async end(t,n){t!=null?await this.throw(t):await this._push(void 0,n)}async _push(t,n){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ui(),await M4(this.readNext.promise,n?.signal,n)}}});function $4(e){return e[Symbol.asyncIterator]!=null}async function xre(e,t,n){try{await Promise.all(e.map(async r=>{for(;;){let{value:o,done:s}=await r.next();if(s===!0)break;await t.push(o,{signal:n}),n.throwIfAborted()}})),await t.end(void 0,{signal:n})}catch(r){await t.end(r,{signal:n}).catch(()=>{})}}async function*Are(e){let t=new AbortController,n=q4(),r=e.map(o=>$4(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());xre(r,n,t.signal).catch(()=>{});try{yield*n}finally{t.abort();for(let o of r)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*Tre(e){for(let t of e)yield*t}function Sre(...e){let t=[];for(let n of e)$4(n)||t.push(n);return t.length===e.length?Tre(t):Are(e)}var V4,j4=L(()=>{"use strict";H4();V4=Sre});function F(e,t){let n=t.safeParse(e);if(n.success)return n.data;throw E.fromZodError(n.error)}function Fe(e,t,n=[]){function r(){return{async firstPage(){return{items:n,hasMore:!1}},from(){return r()},async*[Symbol.asyncIterator](){}}}function o(s=t){return{async firstPage(){return X(e(s))},from(i){return i===void 0?r():o(i)},async*[Symbol.asyncIterator](){let i=s;for(;;){let a=await X(e(i));if(yield a,!a.hasMore||a.limitReached)return;i=a.nextCursor}}}}return o()}function di(e){return Pre(JSON.stringify(e))}function Io(e,t,n="Invalid pagination cursor"){try{return t.parse(JSON.parse(k6(e)))}catch(r){throw new E(n,{cause:r})}}function v6(e){try{return JSON.parse(k6(e))}catch{return}}function Pre(e){return btoa(String.fromCharCode(...new TextEncoder().encode(e)))}function k6(e){return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}function aa(e){return di(x6.parse(e))}function Md(e,t,n={}){return e===void 0?{offset:0,pageSize:t}:A6(Io(e,h.z.unknown()),n)}function A6(e,t={}){let n=x6.safeParse(e);if(!n.success)throw new E("Invalid pagination cursor",{cause:n.error});let r=n.data;if(t.maxPageSize!==void 0&&r.pageSize>t.maxPageSize)throw new E(`Pagination cursor page size must be at most ${t.maxPageSize}`);if(t.maxOffset!==void 0&&r.offset>t.maxOffset)throw new Ol(`Pagination reached this listing's supported depth limit (${t.maxOffset}); whether more items exist cannot be established.`);return r}function T6(e,t){return di({kind:"keyset",fingerprint:P6(t),cursor:e})}function S6(e,t){if(!Rre(e))return;let n=Ere.safeParse(e);if(!n.success)throw new E("Invalid pagination cursor",{cause:n.error});if(t===void 0||n.data.fingerprint!==P6(t))throw new E("Pagination cursor was created for a different query");return n.data.cursor}function Rre(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="keyset"}function P6(e){return JSON.stringify(gN(e))}function gN(e){return Array.isArray(e)?e.map(gN):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>[t,gN(n)])):e}function z(e){return function(t){return _n.fromPromise(t.json(),()=>new C(`Received non-JSON response from ${t.url}`)).andThen(n=>_re(t.url,e,n))}}function Ire(e){return _n.fromPromise(e.blob(),()=>new C(`Received unreadable binary response from ${e.url}`))}function _re(e,t,n){let r=t.safeParse(n);return r.success?go(r.data):Sr(C.fromZodError(r.error,{endpoint:e}))}function Cre(e){if(!(e instanceof O)||!E6(e.cause))return!1;let t=[e.cause.message,Nre(e.cause.data)].join(" ").toLowerCase();return(e.cause.code===3||e.cause.code===-32e3||e.cause.code===-32003||e.cause.code===-32015||e.cause.code===-32603)&&(t.includes("execution reverted")||t.includes("revert")||t.includes("invalid opcode"))}function z4(e){return!R6(e)||e.jsonrpc!=="2.0"?!1:"error"in e?E6(e.error):"result"in e}function E6(e){return R6(e)&&typeof e.code=="number"&&typeof e.message=="string"}function R6(e){return typeof e=="object"&&e!==null}function I6(e){return/^0x[a-fA-F0-9]*$/.test(e)}function W4(e,t="eth_call"){if(typeof e!="string"||!I6(e))throw new C(`Expected JSON-RPC ${t} result to be a hex string`);return e}function G4(e){return`0x${e.toString(16)}`}function Nre(e){if(e===void 0)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function _6(e,t,n){let r=eoe(e,t,n);return{signer:t,wallet:n,...r}}function pi(e){switch(e){case Se.EOA:return Rr.EOA;case Se.POLY_PROXY:return Rr.POLY_PROXY;case Se.GNOSIS_SAFE:return Rr.POLY_GNOSIS_SAFE;case Se.DEPOSIT_WALLET:return Rr.POLY_1271}}function oc(e){let t=pi(e.walletType);return{maker:e.wallet,signatureType:t,signer:t===Rr.POLY_1271?e.wallet:e.signer}}function N0(e,t){return e.signerType==="OWNER"?t:Dre(e.signer,t)}function Dre(e,t){let n=zn(`0x${e.slice(2).padStart(64,"0")}`),r=zt.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes"}],[n,Ore,t]);return eq(`${r}${Lre.slice(2)}`)}function Bre(e){let t=Ure.replace("%s",e.proxyFactory.slice(2).toLowerCase()).replace("%s",e.proxyImplementation.slice(2).toLowerCase());return zn(Je.keccak256(`0x${t}`))}function Mre(e,t){return Be(ho.fromCreate2({bytecodeHash:Bre(t),from:t.proxyFactory,salt:Je.keccak256(zt.encodePacked(["address"],[e]))}))}function Fre(e,t){return Be(ho.fromCreate2({bytecodeHash:t.safeInitCodeHash,from:t.safeFactory,salt:Je.keccak256(zt.encode([{name:"address",type:"address"}],[e]))}))}function O0(e,t){let n=zn(`0x${e.slice(2).padStart(64,"0")}`),r=zt.encode([{type:"address"},{type:"bytes32"}],[t.depositWalletFactory,n]);return Be(ho.fromCreate2({bytecodeHash:Kre(t.depositWalletImplementation,r),from:t.depositWalletFactory,salt:Je.keccak256(r)}))}function Af(e,t){let n=zn(`0x${e.slice(2).padStart(64,"0")}`),r=zt.encode([{type:"address"},{type:"bytes32"}],[t.depositWalletFactory,n]);return Be(ho.fromCreate2({bytecodeHash:Yre(t.depositWalletBeacon,r),from:t.depositWalletFactory,salt:Je.keccak256(r)}))}function Kre(e,t){let n=BigInt((t.length-2)/2),r=$re+(n<<56n);return zn(Je.keccak256(we.concat(we.fromNumber(r,{size:10}),we.fromHex(e),we.fromHex("0x6009"),we.fromHex(Hre),we.fromHex(qre),we.fromHex(t)),{as:"Hex"}))}function Yre(e,t){let n=BigInt((t.length-2)/2),r=Wre+(n<<56n);return zn(Je.keccak256(we.concat(we.fromNumber(r,{size:10}),we.fromHex(e),we.fromHex(zre),we.fromHex(jre),we.fromHex(Vre),we.fromHex(t)),{as:"Hex"}))}async function Qre(e,t){try{let n=await e.ethCall({to:t,data:Gre});return Zre(n)}catch(n){if(Cre(n))return ts;throw n}}async function Xre(e,t){let n=await Qre(e,t);return!Wt(n,ts)}async function Jre(e,t,n){return await Xre(e,n.depositWalletFactory)?Af(t,n):O0(t,n)}function Zre(e){return e.length<66?ts:Be(`0x${e.slice(-40)}`)}function eoe(e,t,n){if(Wt(n,t))return{signerType:"OWNER",walletType:Se.EOA};let r=e.walletDerivation;return Wt(n,Af(t,r))?{signerType:"OWNER",walletType:Se.DEPOSIT_WALLET}:Wt(n,O0(t,r))?{signerType:"OWNER",walletType:Se.DEPOSIT_WALLET}:Wt(n,Fre(t,r))?{signerType:"OWNER",walletType:Se.GNOSIS_SAFE}:Wt(n,Mre(t,r))?{signerType:"OWNER",walletType:Se.POLY_PROXY}:{signerType:"SESSION_KEY",walletType:Se.DEPOSIT_WALLET}}function Nr(e){return h.z.union([h.z.object({...e,assetId:C6,tokenId:h.z.never().optional()}),h.z.object({...e,assetId:h.z.never().optional(),tokenId:h.z.string()})])}function Fd(e){return h.z.union([h.z.object({...e,assetId:C6.optional(),tokenId:h.z.never().optional()}),h.z.object({...e,assetId:h.z.never().optional(),tokenId:h.z.string().optional()})])}function ve(e,t){if(noe(t))return roe(e,t.exceptions);let n=new URLSearchParams;for(let[r,o]of Object.entries(t)){let s=e[r];if(s!==void 0){if(NN(s)){for(let i of s)n.append(o,la(i));continue}n.append(o,la(s))}}return n}function Ee(e={}){return{format:"snake_case",exceptions:e}}function toe(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0){if(Array.isArray(r)){t.append(n,r.map(la).join(","));continue}t.append(n,la(r))}return t}function ca(e,t){return h.z.array(e).min(1).transform(n=>[...new Map(n.map(r=>[r.toLowerCase(),r])).values()]).refine(n=>n.length<=t,`At most ${t} distinct ids`)}function tn(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let o=O6(n);if(NN(r)){t.append(o,r.map(la).join(","));continue}t.append(o,la(r))}return t}function noe(e){return"format"in e}function roe(e,t){let n=new URLSearchParams;for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=t[r]??O6(r);if(NN(o)){for(let i of o)n.append(s,la(i));continue}n.append(s,la(o))}return n}function NN(e){return Array.isArray(e)}function O6(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function la(e){return String(e)}async function U0(e){return(await X(e.secureClob.get("/auth/ban-status/closed-only").andThen(z(c3)))).closedOnly}function M0(e,t){let n=F(t,soe),{cursor:r}=n;return Fe(o=>e.secureClob.get("/data/orders",{params:ve({assetId:n.assetId??n.tokenId,id:n.id,market:n.market,nextCursor:o},Ee({assetId:"asset_id"}))}).andThen(z(u3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function q0(e,t){let n=F(t,ioe);return X(e.secureClob.get(`/data/order/${n.orderId}`).andThen(z(IC)))}function Tf(e,t){let n=F(t,loe),{cursor:r}=n;return Fe(o=>e.secureClob.get("/data/trades",{params:ve({after:n.after,assetId:n.assetId??n.tokenId,before:n.before,id:n.id,makerAddress:n.makerAddress,market:n.market,nextCursor:o},Ee({assetId:"asset_id"}))}).andThen(z(d3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function V0(e){let t=pi(e.account.walletType);return X(e.secureClob.get("/notifications",{params:ve({signatureType:t},Ee())}).andThen(z(M3)))}async function z0(e,t){let n=F(t,coe),r=pi(e.account.walletType),o=ve({ids:n.ids.join(","),signatureType:r},Ee());await X(e.secureClob.del("/notifications",{params:o}))}async function W0(e,t){let n=F(t,uoe),r=pi(e.account.walletType);return X(e.secureClob.get("/balance-allowance",{params:ve({assetType:n.assetType,tokenId:n.assetId??n.tokenId,signatureType:r},Ee())}).andThen(z(m3)))}async function ON(e,t){let n=F(t,doe),r=pi(e.account.walletType),o=ve({assetType:n.assetType,tokenId:n.assetId??n.tokenId,signatureType:r},Ee());return await X(e.secureClob.get("/balance-allowance/update",{params:o})),W0(e,n)}async function K0(e,t){let n=F(t,poe);return(await X(e.secureClob.get("/order-scoring",{params:ve(n,Ee())}).andThen(z(h3)))).scoring}async function Q0(e,t){let n=F(t,moe).orderIds;return X(e.secureClob.post("/orders-scoring",{json:n}).andThen(z(f3)))}function J0(e,t){let{cursor:n,...r}=F(t,B6),o=pi(e.account.walletType);return Fe(s=>e.secureClob.get("/rewards/user",{params:ve({...r,nextCursor:s,signatureType:o},Ee())}).andThen(z(g3)).map(i=>({items:i.data,hasMore:i.nextCursor!==Yn,nextCursor:i.nextCursor===Yn?void 0:i.nextCursor})),n)}async function ev(e,t){let n=F(t,B6),r=pi(e.account.walletType);return X(e.secureClob.get("/rewards/user/total",{params:ve({...n,signatureType:r},Ee())}).andThen(z(y3)))}function nv(e,t){let{cursor:n,...r}=F(t,hoe),o=pi(e.account.walletType);return Fe(s=>e.secureClob.get("/rewards/user/markets",{params:ve({...r,nextCursor:s,signatureType:o},Ee())}).andThen(z(w3)).map(i=>({items:i.data,hasMore:i.nextCursor!==Yn,nextCursor:i.nextCursor===Yn?void 0:i.nextCursor})),n)}async function ov(e){let t=pi(e.account.walletType);return X(e.secureClob.get("/rewards/user/percentages",{params:ve({signatureType:t},Ee())}).andThen(z(b3)))}function nn(e,t={}){let{retries:n=2,maxDelaySeconds:r=5,sleep:o=ns}=t;function s(i){return e().orElse(a=>{if(!(a instanceof $)||i<=0)return Al(a);let l=a.retryAfter??1;return l>r?Al(a):_n.fromSafePromise(o(l*1e3).catch(()=>{})).andThen(()=>s(i-1))})}return s(n)}function iv(e,t={}){let{cursor:n,pageSize:r,window:o,...s}=F(t,foe);return Fe(i=>nn(()=>e.data.get("/v2/trades",{params:tn({...s,...o,limit:r,cursor:i})})).andThen(z(V$)),n)}function Sf(e,t){let{cursor:n,pageSize:r,window:o,...s}=F(t,goe);return Fe(i=>nn(()=>e.data.get("/v2/activity",{params:tn({...s,...o,excludeDepositsWithdrawals:!1,limit:r,cursor:i})})).andThen(z(j$)),n)}function Pf(e,t){let{cursor:n,pageSize:r,...o}=F(t,yoe);return Fe(s=>nn(()=>e.data.get("/v2/activity/combos",{params:tn({...o,limit:r,cursor:s})})).andThen(z(z$)),n)}function yf(e,t,n){if(n<0n)throw new E("Approval amount must be non-negative");if(n>lr)throw new E("Approval amount exceeds uint256 range");return{data:Boe(t,n),to:e}}function DN(e,t,n){return{data:_e.encodeData(M6,[t,n]),to:e}}function UN(e){return _e.decodeResult(M6,e)}function bf(e,t,n){return{data:Moe(t,n),to:e}}function BN(e,t,n){return{data:_e.encodeData(F6,[t,n]),to:e}}function MN(e){return _e.decodeResult(F6,e)}function FN(e,t,n){return{data:_e.encodeData(q6,[t,ps(BigInt(n),"Position ID")]),to:e}}function qN(e){return _e.decodeResult(q6,e)}function Ef(e,t,n){return{data:_e.encodeData(H6,[n.map(()=>t),n.map(r=>ps(BigInt(r),"id"))]),to:e}}function Rf(e){return _e.decodeResult(H6,e)}function S0(e,t,n){if(n<0n)throw new E("Transfer amount must be non-negative");if(n>lr)throw new E("Transfer amount exceeds uint256 range");return{data:Foe(t,n),to:e}}function HN(e,t,n){return{data:_e.encodeData(Aoe,[t,ps(n,"Session key expiry")]),to:e}}function $N(e,t){return{data:_e.encodeData(Toe,[t]),to:e}}function VN(e,t,n,r){if(n<=0n)throw new E("Perps deposit amount must be positive");return{data:_e.encodeData(Soe,[t,ps(n,"Perps deposit amount"),r]),to:e}}function jN(e,t,n,r){return{data:qoe(t,n,r),to:e}}function zN(e,t,n,r){return{data:Hoe(t,n,r),to:e}}function WN(e,t,n){return{data:$oe(t,n),to:e}}function cv(e,t,n){return{data:_e.encodeData(_oe,[GN(t),ps(n,"Split amount")]),to:e}}function uv(e,t,n){return{data:_e.encodeData(Coe,[GN(t),ps(n,"Merge amount")]),to:e}}function wf(e,t,n,r){return{data:_e.encodeData(Noe,[GN(t),BigInt(Voe(n)),ps(r,"Redeem amount")]),to:e}}function dv(e,t){return{data:_e.encodeData(Ooe,[t.map(n=>ps(n,"Leg position ID"))]),to:e}}function Boe(e,t){return ge(t>=0n,"Approval amount must be non-negative"),_e.encodeData(koe,[e,t])}function Moe(e,t){return _e.encodeData(Poe,[e,t])}function Foe(e,t){return _e.encodeData(xoe,[e,t])}function qoe(e,t,n){return _e.encodeData(Eoe,[e,LN,t,$6,ps(n,"Split amount")])}function Hoe(e,t,n){return _e.encodeData(Roe,[e,LN,t,$6,ps(n,"Merge amount")])}function $oe(e,t){return _e.encodeData(Ioe,[e,LN,t,Uoe])}function ps(e,t){if(e<0n)throw new E(`${t} must be non-negative`);if(e>lr)throw new E(`${t} exceeds uint256 range`);return e}function GN(e){if(woe.test(e))return e.toLowerCase();if(voe.test(e)){let t=e.toLowerCase();if(t.endsWith("00")||t.endsWith("01"))return t.slice(0,boe)}throw new E("Protocol v2 condition ID must be bytes31, or bytes32 with a binary outcome byte")}function Voe(e){if(e!==0&&e!==1)throw new E("Protocol v2 outcome index must be 0 or 1");return e}function KN(e){return _e.encodeData(Doe,[e.map(t=>({typeCode:1,to:t.to,value:t.value??0n,data:t.data}))])}function YN(e){let t=e.map(n=>joe(n));return _e.encodeData(Loe,[t.length===0?"0x":zt.encodePacked(Array.from({length:t.length},()=>"bytes"),t)])}function joe(e){let t=e.value??0n;return zt.encodePacked(["uint8","address","uint256","uint256","bytes"],[0,e.to,t,BigInt((e.data.length-2)/2),e.data])}function bn(e,t="Expected a TransactionHandle"){return ge(typeof e=="object"&&e!==null&&"transactionHash"in e&&"transactionId"in e&&"wait"in e&&typeof e.wait=="function",t),e}function e8(e){return async function(t){let n=await t.next();for(;!n.done;)try{switch(n.value.kind){case"requestAddress":n=await t.next(await e.getAddress());break;case"signAuthMessage":n=await t.next(await e.signTypedData(n.value.payload));break}}catch(r){n=await t.throw(r)}return n.value}}function wn(e){return async function(t){let n=await t.next();for(;!n.done;)try{switch(n.value.kind){case"requestAddress":n=await t.next(await e.getAddress());break;case"signGaslessTypedData":case"signOrder":n=await t.next(await e.signTypedData(n.value.payload));break;case"signGaslessMessage":n=await t.next(await e.signMessage(n.value.payload));break;case"sendErc20ApprovalTransaction":case"sendErc1155ApprovalForAllTransaction":case"sendErc20TransferTransaction":case"sendPerpsDepositTransaction":case"sendMergePositionsTransaction":case"sendRedeemPositionsTransaction":case"sendSplitPositionTransaction":n=await t.next(await e.sendTransaction(n.value.request));break}}catch(r){n=await t.throw(r)}return n.value}}function QN(){return{kind:"requestAddress"}}function Qn(e,t){return{chainId:e,...t}}async function If(e,t){let n=F(t,Joe);return X(e.relayer.get("/v1/account/transactions/params",{params:ve(n,{address:"address",type:"type"})}).andThen(z(l4)))}async function _f(e,t){let n=await tse(e,t);return n.type===Se.EOA?!1:X(e.relayer.get("/deployed",{params:ve({address:n.wallet,type:n.type===Se.DEPOSIT_WALLET?_r.WALLET:void 0},{address:"address",type:"type"})}).andThen(z(u4)).map(({deployed:r})=>r))}async function tse(e,t){if(t!==void 0)return F(t,ese);if(!e.isSecureClient())throw new E("Gasless readiness inference requires a secure client. Pass a wallet and type when using a public client.");return e.account.walletType!==Se.EOA?{wallet:e.account.wallet,type:e.account.walletType}:{wallet:await Jre(e.rpc,e.account.signer,e.environment.walletDerivation),type:Se.DEPOSIT_WALLET}}async function pv(e){return ge(e.supportsGasless,"Deposit Wallet deployment requires a Relayer API Key or Builder API Key in the client configuration."),vf(e,{from:e.account.signer,metadata:"Deploy Deposit Wallet",to:e.environment.walletDerivation.depositWalletFactory,type:_r.WALLET_CREATE})}async function XN(e,t){let n=F(t,Zoe);return X(e.relayer.get(`/v1/account/transactions/${n.transactionId}`).andThen(z(d4)))}async function Or(e,t){let n=F(t,rse);return ge(e.supportsGasless,"Gasless transactions require a Relayer API Key or Builder API Key in the client configuration."),ge(e.account.walletType===Se.GNOSIS_SAFE||e.account.walletType===Se.POLY_PROXY||e.account.walletType===Se.DEPOSIT_WALLET,"Gasless transaction preparation supports Deposit Wallet, Safe-backed, and proxy-backed accounts"),async function*(){let r=Be(yield QN());ge(r===e.account.signer,"Wallet client address does not match the authenticated signer");for(let o=0;o<=K4;o+=1)try{switch(e.account.walletType){case Se.POLY_PROXY:return yield*ose(e,n);case Se.DEPOSIT_WALLET:return yield*sse(e,n);case Se.GNOSIS_SAFE:return yield*ise(e,n)}ge(!1,"Unsupported wallet type for gasless transaction")}catch(s){if(!yv(s)||o===K4)throw s;await ns(e.environment.relayerPollFrequencyMs)}ge(!1,"Expected gasless transaction retry loop to return")}.call(null)}async function*ose(e,t){let n=yield*mv(e,t.calls,t.metadata);return vf(e,n)}async function*mv(e,t,n){let r=await If(e,{address:e.account.signer,type:_r.PROXY}),o=e.environment.walletDerivation.proxyFactory,s=KN(t),i="0",a="0",l=(await e.rpc.ethEstimateGas({data:s,from:e.account.signer,to:o})).toString(),c=e.environment.contracts.relayHub,u=r.address,d=use(e.account.signer,o,s,i,a,l,r.nonce,c,u),p=rs(yield a8(d));return{data:s,from:e.account.signer,...n!==void 0&&{metadata:n},nonce:r.nonce,proxyWallet:e.account.wallet,signature:p,signatureParams:{gasLimit:l,gasPrice:a,relay:u,relayHub:c,relayerFee:i},to:o,type:_r.PROXY}}function hv(e){return!(e instanceof O)||e.status!==400?void 0:/batch nonce\s+\d+\s+does not match on-chain nonce\s+(\d+)/i.exec(e.message)?.[1]}async function*sse(e,t){let n=yield*qd(e,t.calls,t.metadata);try{return await vf(e,n)}catch(r){let o=hv(r);if(o===void 0)throw r;let s=yield*fv(e,n,t.calls,o);return vf(e,s)}}async function*qd(e,t,n){let r=await If(e,{address:e.account.signer,type:_r.WALLET}),o=t.map(s8),s=`${Math.floor(Date.now()/1e3)+Yoe}`,i=N0(e.account,rs(yield l8(i8({calls:o,chainId:e.environment.chainId,deadline:s,nonce:r.nonce,wallet:e.account.wallet}))));return{depositWalletParams:{calls:o,deadline:s,depositWallet:e.account.wallet},from:e.account.signer,...n!==void 0&&{metadata:n},nonce:r.nonce,signature:i,to:e.environment.walletDerivation.depositWalletFactory,type:_r.WALLET}}async function*fv(e,t,n,r){let o=N0(e.account,rs(yield l8(i8({calls:n.map(s8),chainId:e.environment.chainId,deadline:t.depositWalletParams.deadline,nonce:r,wallet:e.account.wallet}))));return{...t,nonce:r,signature:o}}async function*ise(e,t){let n=yield*gv(e,t.calls,t.metadata);return vf(e,n)}async function*gv(e,t,n){let r=await If(e,{address:e.account.signer,type:_r.SAFE}),o=ase(t,e.environment.contracts.safeMultisend),s=cse({chainId:e.environment.chainId,data:o.data,nonce:r.nonce,operation:o.operation,safeAddress:e.account.wallet,to:o.to,value:o.value}),i=rs(yield a8(zn(fo.getSignPayload(s))));return{data:o.data,from:e.account.signer,...n!==void 0&&{metadata:n},nonce:r.nonce,proxyWallet:e.account.wallet,signature:dse(i),signatureParams:lse(o.operation),to:o.to,type:_r.SAFE,value:o.value>0n?`${o.value}`:void 0}}async function vf(e,t){let n=F(t,c4),r=await X(e.relayer.post("/submit",{json:n}).andThen(z(QC)));return new Cf(e,r)}function yv(e){if(e instanceof $)return!0;if(!(e instanceof O)||e.status!==400)return!1;if(/wallet busy/i.test(e.message)&&/active action/i.test(e.message)||/wallet has in-flight action/i.test(e.message))return!0;let t=/batch nonce\s+(\d+)\s+does not match on-chain nonce\s+(\d+)/i.exec(e.message);if(t===null)return!1;let n=t[1],r=t[2];return n===void 0||r===void 0?!1:BigInt(n)<BigInt(r)}function s8(e){return{data:e.data,target:e.to,value:`${e.value??0n}`}}function i8(e){let t={chainId:e.chainId,name:Goe,verifyingContract:e.wallet,version:Koe};return{domain:t,message:{calls:e.calls.map(n=>({data:n.data,target:n.target,value:BigInt(n.value)})),deadline:BigInt(e.deadline),nonce:BigInt(e.nonce),wallet:e.wallet},primaryType:"Batch",types:{Batch:Xoe,Call:Qoe,EIP712Domain:fo.extractEip712DomainTypes(t)}}}function ase(e,t){if(e.length===1){let[n]=e;return{data:n.data,operation:0,to:n.to,value:n.value??0n}}return{data:YN(e),operation:1,to:t,value:0n}}function lse(e){return{baseGas:"0",gasPrice:"0",gasToken:ts,operation:`${e}`,refundReceiver:ts,safeTxnGas:"0"}}function cse(e){return{domain:{chainId:e.chainId,verifyingContract:e.safeAddress},message:{baseGas:0n,data:e.data,gasPrice:0n,gasToken:ts,nonce:BigInt(e.nonce),operation:e.operation,refundReceiver:ts,safeTxGas:0n,to:e.to,value:e.value},primaryType:"SafeTx",types:{EIP712Domain:zoe,SafeTx:Woe}}}function a8(e){return{kind:"signGaslessMessage",payload:e}}function l8(e){return{kind:"signGaslessTypedData",payload:e}}function use(e,t,n,r,o,s,i,a,l){return zn(Je.keccak256(we.concat(we.fromString("rlx:"),we.fromHex(e),we.fromHex(t),we.fromHex(n),we.fromNumber(BigInt(r),{size:32}),we.fromNumber(BigInt(o),{size:32}),we.fromNumber(BigInt(s),{size:32}),we.fromNumber(BigInt(i),{size:32}),we.fromHex(a),we.fromHex(l)),{as:"Hex"}))}function dse(e){let t=e.slice(2),n=Number.parseInt(t.slice(128,130),16),r=n===0||n===1?n+31:n===27||n===28?n+4:n;return zn(`0x${t.slice(0,128)}${r.toString(16).padStart(2,"0")}`)}async function JN(e,t){let n=F(t,pse),r=n.amount==="max"?lr:n.amount;return async function*(){return e.account.walletType===Se.EOA?bn(yield h8(Qn(e.environment.chainId,yf(n.tokenAddress,n.spenderAddress,r)))):yield*await Or(e,{calls:[yf(n.tokenAddress,n.spenderAddress,r)],metadata:n.metadata??`Approve ${n.amount} of ${n.tokenAddress} to ${n.spenderAddress}`})}.call(null)}function Nf(e,t){return JN(e,t).then(wn(e.signer))}async function ZN(e,t){let n=F(t,mse);return async function*(){return e.account.walletType===Se.EOA?bn(yield f8(Qn(e.environment.chainId,bf(n.tokenAddress,n.operatorAddress,n.approved)))):yield*await Or(e,{calls:[bf(n.tokenAddress,n.operatorAddress,n.approved)],metadata:n.metadata??`${n.approved?"Approve":"Revoke"} ${n.operatorAddress} on ${n.tokenAddress}`})}.call(null)}function Of(e,t){return ZN(e,t).then(wn(e.signer))}async function Lf(e,t){let{user:n}=F(t,hse),r=await m8(e,n);return{isFullyApproved:r.erc20.length===0&&r.erc1155.length===0,missing:r}}async function eO(e){let t=await m8(e,e.account.wallet),n=t.erc20.map(o=>yf(o.tokenAddress,o.spenderAddress,o.amount)),r=t.erc1155.map(o=>bf(o.tokenAddress,o.operatorAddress,!0));return async function*(){if(!(n.length===0&&r.length===0)){if(e.account.walletType===Se.EOA){for(let o of n)await bn(yield h8(Qn(e.environment.chainId,o))).wait();for(let o of r)await bn(yield f8(Qn(e.environment.chainId,o))).wait();return}await(yield*await Or(e,{calls:[...n,...r],metadata:"Trading setup approvals"})).wait()}}.call(null)}function xv(e){return eO(e).then(wn(e.signer)).then(()=>{})}async function m8(e,t){let n=fse(e),r=[...n.erc20.map(a=>DN(a.tokenAddress,t,a.spenderAddress)),...n.erc1155.map(a=>BN(a.tokenAddress,t,a.operatorAddress))],o=await e.rpc.ethCallBatch(r),s=o.slice(0,n.erc20.length),i=o.slice(n.erc20.length);try{return{erc20:n.erc20.filter((a,l)=>UN(s[l])<a.amount),erc1155:n.erc1155.filter((a,l)=>!MN(i[l]))}}catch(a){throw new C("Expected JSON-RPC approval checks to return ABI-encoded values",{cause:a})}}function fse(e){let{contracts:t}=e.environment;return{erc20:[{amount:lr,spenderAddress:t.standardExchange,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.negRiskExchange,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.collateralAdapter,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.negRiskCollateralAdapter,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.protocolV2Router,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.exchangeV3,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.perpsDepositContract,tokenAddress:t.collateralToken}],erc1155:[{operatorAddress:t.standardExchange,tokenAddress:t.conditionalTokens},{operatorAddress:t.negRiskExchange,tokenAddress:t.conditionalTokens},{operatorAddress:t.collateralAdapter,tokenAddress:t.conditionalTokens},{operatorAddress:t.negRiskCollateralAdapter,tokenAddress:t.conditionalTokens},{operatorAddress:t.autoRedeemOperator,tokenAddress:t.conditionalTokens},{operatorAddress:t.binaryModule,tokenAddress:t.conditionalTokens},{operatorAddress:t.negRiskModule,tokenAddress:t.conditionalTokens},{operatorAddress:t.protocolV2Router,tokenAddress:t.positionManager},{operatorAddress:t.exchangeV3,tokenAddress:t.positionManager},{operatorAddress:t.autoRedeemOperator,tokenAddress:t.positionManager}]}}function h8(e){return{kind:"sendErc20ApprovalTransaction",request:e}}function f8(e){return{kind:"sendErc1155ApprovalForAllTransaction",request:e}}async function tO(e,t){return X(e.clob.post("/auth/api-key",{headers:E8(t)}).andThen(z(_C)))}async function nO(e,t){return X(e.clob.get("/auth/derive-api-key",{headers:E8(t)}).andThen(z(_C)))}async function Av(e,t){try{return await tO(e,t)}catch(n){if(!(n instanceof O)||n.status!==400)throw n}return nO(e,t)}async function Tv(e){return(await X(e.secureClob.get("/auth/api-keys").andThen(z(v3)))).apiKeys}async function Sv(e){await X(e.secureClob.del("/auth/api-key").andThen(z(h.z.literal("OK"))))}async function x8(e){return X(e.secureClob.post("/auth/builder-api-key").andThen(z(k3)))}async function T8(e){return X(e.secureClob.get("/auth/builder-api-key").andThen(z(x3)))}async function P8(e){await X(e.clob.del("/auth/builder-api-key").andThen(z(h.z.literal("OK"))))}function E8(e){return{POLY_ADDRESS:e.address,POLY_NONCE:`${e.nonce}`,POLY_SIGNATURE:e.signature,POLY_TIMESTAMP:`${e.timestamp}`}}function Ev(e,t){let n=F(t,yse),{cursor:r}=n;return Fe(o=>e.clob.get("/builder/trades",{params:ve({after:n.after,assetId:n.assetId??n.tokenId,before:n.before,builderCode:n.builderCode,id:n.id,market:n.market,nextCursor:o},Ee({assetId:"asset_id",builderCode:"builder_code"}))}).andThen(z(A3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function Iv(e,t){let n=F(t,bse);return(await X(e.clob.get("/midpoint",{params:sc(n)}).andThen(z(P3)))).mid}async function Cv(e,t){let n=F(t,wse);return X(e.clob.post("midpoints",{json:Xv(n)}).andThen(z(E3)))}async function I8(e,t){let n=F(t,vse);return(await X(e.clob.get("/tick-size",{params:sc(n)}).andThen(z(W3)))).minimumTickSize}async function C8(e,t){let n=F(t,kse);return(await X(e.clob.get("/neg-risk",{params:sc(n)}).andThen(z(U3)))).negRisk}async function rO(e,t){let n=F(t,xse);return X(e.clob.get(`/markets-by-token/${n.assetId??n.tokenId}`).andThen(z(L3)))}async function oO(e,t){let n=F(t,Ase);return X(e.clob.get(`/clob-markets/${n.conditionId}`).andThen(z(D3)))}async function sO(e,t){let n=F(t,Tse);return X(e.clob.get(`/fees/builder-fees/${n.builderCode}`).andThen(z(T3)).mapErr(r=>r instanceof O&&r.status===404?new E(`Unknown builder code: ${n.builderCode}`,{cause:r}):r))}async function Ov(e,t){let n=F(t,Sse);return(await X(e.clob.get("/price",{params:sc(n)}).andThen(z(R3)))).price}async function Dv(e,t){let n=F(t,Pse);return X(e.clob.post("prices",{json:Dse(n)}).andThen(z(I3)))}async function Hd(e,t){let n=F(t,Ese);return X(e.clob.get("/book",{params:sc(n)}).andThen(z(q3)))}async function Mv(e,t){let n=F(t,Rse);return X(e.clob.post("books",{json:Xv(n)}).andThen(z(H3)))}async function qv(e,t){let n=F(t,Ise);return(await X(e.clob.get("/spread",{params:sc(n)}).andThen(z(_3)))).spread}async function $v(e,t){let n=F(t,_se);return X(e.clob.post("spreads",{json:Xv(n)}).andThen(z(C3)))}async function jv(e,t){let n=F(t,Cse);return X(e.clob.get("/last-trade-price",{params:sc(n)}).andThen(z(N3)))}async function Wv(e,t){let n=F(t,Nse);return X(e.clob.post("last-trades-prices",{json:Xv(n)}).andThen(z(O3)))}function Kv(e,t={}){let{cursor:n,...r}=F(t,Ose);return Fe(o=>e.clob.get("/rewards/markets/current",{params:ve({...r,nextCursor:o},Ee())}).andThen(z(V3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),n)}function Qv(e,t){let{cursor:n,...r}=F(t,Lse);return Fe(o=>e.clob.get(`rewards/markets/${r.conditionId}`,{params:ve({nextCursor:o,sponsored:r.sponsored},Ee())}).andThen(z(j3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),n)}function Xv(e){return e.map(t=>({token_id:t.assetId??t.tokenId}))}function Dse(e){return e.map(t=>({token_id:t.assetId??t.tokenId,side:t.side}))}function sc(e){let{assetId:t,tokenId:n,...r}=e;return ve({...r,tokenId:e.assetId??e.tokenId},Ee())}async function Zv(e){return B8(e),X(e.combos.post("/v1/collateral-return/plan",{json:{wallet:e.account.wallet},timeout:D8}).andThen(z(w4)))}async function iO(e,t){let{plan:n}=F(t,Use);if(ge(e.supportsGasless,"Collateral return execution requires a Relayer API Key or Builder API Key in the client configuration."),B8(e),!Wt(n.wallet,e.account.wallet))throw new E("The collateral return plan was created for a different wallet than the authenticated account.");if(n.chainId!==e.environment.chainId)throw new E(`The collateral return plan was created for chain ${n.chainId}, but the client is configured for chain ${e.environment.chainId}.`);return async function*(){let r=[{data:n.routerCall.data,to:n.routerCall.to,value:0n}];for(let o=0;o<=Y4;o+=1)try{let s=yield*Bse(e,r);try{return await Q4(e,n.planHash,s)}catch(i){let a=hv(i);if(a===void 0||s.type!==_r.WALLET)throw i;let l=yield*fv(e,s,r,a);return await Q4(e,n.planHash,l)}}catch(s){if(!yv(s)||o===Y4)throw s;await ns(e.environment.relayerPollFrequencyMs)}ge(!1,"Expected collateral return submit retry loop to return")}.call(null)}function tk(e,t){return iO(e,t).then(wn(e.signer))}function B8(e){ge(e.account.walletType===Se.DEPOSIT_WALLET||e.account.walletType===Se.GNOSIS_SAFE||e.account.walletType===Se.POLY_PROXY,"Collateral return supports Deposit Wallet, Safe Wallet, and Proxy Wallet accounts")}function Bse(e,t){switch(e.account.walletType){case Se.GNOSIS_SAFE:return gv(e,t,uN);case Se.POLY_PROXY:return mv(e,t,uN);default:return qd(e,t,uN)}}async function Q4(e,t,n){let r=await X(e.combos.post("/v1/collateral-return/submit",{json:{envelope:n,plan_hash:t},timeout:D8}).andThen(z(QC)));return new Cf(e,r)}function $se(e){if(e.holdersOnly===!0||e.getPositions===!0)return;if(e.order===void 0)return{ascending:!1,order:"createdAt",parentEntityId:e.parentEntityId,parentEntityType:e.parentEntityType};let t=Hse.safeParse(e.order);if(t.success)return{ascending:e.ascending??!0,order:t.data,parentEntityId:e.parentEntityId,parentEntityType:e.parentEntityType}}function rk(e,t){let{cursor:n,pageSize:r,...o}=F(t,Mse),s=$se(o);return Fe(i=>{if(i===void 0)return s===void 0?X4(e,o,{offset:0,pageSize:r}):J4(e,s,r);let a=v6(i);if(a===void 0)throw new E("Invalid pagination cursor");let l=S6(a,s);return l===void 0||s===void 0?X4(e,o,A6(a,M8)):J4(e,s,r,l)},n)}function X4(e,t,n){return e.gamma.get("/comments",{params:ve({ascending:t.ascending,getPositions:t.getPositions,holdersOnly:t.holdersOnly,limit:n.pageSize,offset:n.offset,order:t.order,parentEntityId:t.parentEntityId,parentEntityType:t.parentEntityType},Ee())}).andThen(z(Hh)).map(r=>{let o=r.filter(s=>s.parentCommentID==null).length>=n.pageSize;return{items:r,hasMore:o,limitReached:o&&n.offset+n.pageSize>lO,nextCursor:o?aa({offset:n.offset+n.pageSize,pageSize:n.pageSize}):void 0}})}function J4(e,t,n,r){return e.gamma.get("/comments/keyset",{params:ve({afterCursor:r,ascending:t.ascending,limit:n,order:t.order,parentEntityId:t.parentEntityId,parentEntityType:t.parentEntityType},Ee())}).andThen(z(k_)).map(o=>({items:o.items,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor===void 0?void 0:T6(o.nextCursor,t)}))}async function sk(e,t){let n=F(t,Fse);return X(e.gamma.get(`comments/${n.id}`,{params:ve({getPositions:n.getPositions},Ee())}).andThen(z(Hh)))}function ak(e,t){let{address:n,cursor:r,pageSize:o,...s}=F(t,qse);return Fe(i=>{let a=Md(i,o,M8);return e.gamma.get(`comments/user_address/${n}`,{params:ve({ascending:s.ascending,limit:a.pageSize,offset:a.offset,order:s.order},Ee())}).andThen(z(Hh)).map(l=>{let c=l.length>=a.pageSize;return{items:l,hasMore:c,limitReached:c&&a.offset+a.pageSize>lO,nextCursor:c?aa({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},r)}function F8(e,t){let n;try{n=new URL(e)}catch(a){throw new E("Expected a valid Polymarket URL.",{cause:a})}if(n.protocol!=="https:"||n.hostname!=="polymarket.com"&&n.hostname!=="www.polymarket.com")throw new E("Expected a valid Polymarket URL.");let[r,o,...s]=n.pathname.split("/").filter(Boolean),i=s[0];if(t==="market"&&r==="event"&&o!==void 0&&s.length<=1)return i??o;if(r!==t||o===void 0||s.length>0)throw new E(`Expected a Polymarket ${t} URL.`);return o}function ck(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,Vse);return Fe(s=>e.gamma.get("/events/keyset",{params:Xse({...o,pageSize:r,cursor:s===void 0?void 0:Wse(s,o)})}).andThen(z(b_)).map(i=>({items:i.items,hasMore:i.nextCursor!==void 0,nextCursor:i.nextCursor===void 0?void 0:T6(i.nextCursor,o)})),n)}function Wse(e,t){let n=v6(e);return n===void 0?e:S6(n,t)??e}async function dk(e,t){let n=F(t,jse);if("id"in n)return X(e.gamma.get(`events/${n.id}`,{params:Jse(n)}).andThen(z(ei)));let r="url"in n?F8(n.url,"event"):n.slug;return X(e.gamma.get(`events/slug/${r}`,{params:Zse(n)}).andThen(z(ei)))}async function mk(e,t){let n=F(t,zse);return X(e.gamma.get(`events/${n.id}/tags`).andThen(z(w_)))}async function fk(e,t){let{conditionIds:n,eventIds:r,questionId:o}=F(t,Yse);return X(nn(()=>e.data.get("/v2/resolutions",{params:tn({questionId:o,condition:n,eventId:r})})).andThen(z(o4)))}async function yk(e,t){let{eventIds:n}=F(t,Qse);return X(nn(()=>e.data.get("/v2/live-volume",{params:tn({eventId:n})})).andThen(z(Q$)))}function Xse(e){return ve(e,Ee({cursor:"after_cursor",excludeTagIds:"exclude_tag_id",gameIds:"game_id",ids:"id",pageSize:"limit",seriesIds:"series_id",tagIds:"tag_id"}))}function Jse(e){return ve({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},Ee())}function Zse(e){return ve({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},Ee())}function wk(e,t={}){let{cursor:n,pageSize:r,window:o}=F(t,eie);return Fe(s=>nn(()=>e.data.get("/v2/builders/leaderboard",{params:tn({timePeriod:o,limit:r,cursor:s})})).andThen(z(Z$)),n)}async function kk(e,t={}){let{interval:n,bucketLimit:r}=F(t,tie);return X(nn(()=>e.data.get("/v2/builders/volume",{params:tn({interval:n,limit:r})})).andThen(z(e4)))}function Ak(e,t={}){let{category:n,cursor:r,pageSize:o,sortBy:s,window:i}=F(t,nie);return Fe(a=>nn(()=>e.data.get("/v2/leaderboard",{params:tn({category:n,cursor:a,limit:o,sortBy:s,timePeriod:i})})).andThen(z(t4)),r)}async function Df(e,t){let{category:n,user:r,window:o}=F(t,rie);return X(nn(()=>e.data.get("/v2/leaderboard",{params:tn({category:n,timePeriod:o,user:r})})).andThen(z(n4)))}function Pk(e,t={}){let{category:n,cursor:r,pageSize:o,window:s}=F(t,oie);return Fe(i=>nn(()=>e.data.get("/v2/biggest-winners",{params:tn({category:n,cursor:i,limit:o,timePeriod:s})})).andThen(z(r4)),r)}function Ek(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,sie);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/market-clarifications",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(z(G3)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?aa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}function Uf(e,t={}){let n=F(t,iie);return Fe(r=>e.gamma.get("/markets/keyset",{params:kie({...n,cursor:r??n.cursor})}).andThen(z(d_)).map(o=>({items:o.items,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor})),n.cursor)}function _k(e,t={}){let n=F(t,pie);return Fe(r=>e.rfq.get("/v1/rfq/combo-markets",{params:xie({...n,cursor:r??n.cursor})}).andThen(z(m4)).map(o=>({items:o.markets,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor})),n.cursor)}async function Nk(e,t){let n=F(t,uie);return"id"in n?Aie(e,n):"url"in n?Z4(e,{includeTag:n.includeTag,locale:n.locale,slug:F8(n.url,"market")}):Z4(e,n)}async function Lk(e,t){let n=F(t,die);return X(e.gamma.get(`markets/${n.id}/tags`).andThen(z(p_)))}function Uk(e,t){let{conditionIds:n,cursor:r,includePnl:o,minBalance:s,pageSize:i}=F(t,mie);return Fe(a=>nn(()=>e.data.get("/v2/holders",{params:tn({condition:n,limit:i,cursor:a,includePnl:o,minBalance:s})})).andThen(z(K$)),r)}function Mk(e,t){let{assetId:n,cursor:r,pageSize:o,...s}=F(t,wie);return Fe(i=>nn(()=>e.data.get("/v2/prices-history",{params:tn({...s,tokenId:n,limit:o,cursor:i})})).andThen(z(G$)),r)}async function qk(e,t={}){let{conditionIds:n}=F(t,vie);return X(nn(()=>e.data.get("/v2/oi",{params:tn({condition:n})})).andThen(z(Y$)))}function kie(e){return ve(e,Ee({cursor:"after_cursor",ids:"id",pageSize:"limit"}))}function xie(e){return ve({cursor:e.cursor,exclude:e.exclude?.join(","),pageSize:e.pageSize},{cursor:"cursor",exclude:"exclude",pageSize:"limit"})}async function Z4(e,t){return X(e.gamma.get(`markets/slug/${t.slug}`,{params:ve({includeTag:t.includeTag,locale:t.locale},Ee())}).andThen(z(Cw)))}async function Aie(e,t){return X(e.gamma.get(`markets/${t.id}`,{params:ve({includeTag:t.includeTag,locale:t.locale},Ee())}).andThen(z(Cw)))}function uO(e){if(!(e instanceof O))return e;let t=Tie(e);return t===void 0?e:new O(e.message,{cause:e,...e.code!==void 0?{code:e.code}:{},restriction:t,...e.retryAfter!==void 0?{retryAfter:e.retryAfter}:{},status:e.status})}function Tie(e){if(e.status===425)return"restarting";if(e.status===503&&e.code==="post_only_mode")return"post_only"}async function $k(e,t){let n=F(t,Sie);return Yk(e,"/order",{orderID:n.orderId})}async function jk(e,t){let n=F(t,Pie);return Yk(e,"/orders",n.orderIds)}async function Wk(e){return Yk(e,"/cancel-all")}async function Kk(e,t){let n=F(t,Rie);return Yk(e,"/cancel-market-orders",{asset_id:n.assetId??n.tokenId,market:n.market})}async function Yk(e,t,n){return X(e.secureClob.del(t,{json:n,rateLimitBucket:"cancel"}).mapErr(uO).andThen(z(S3)))}async function Xk(e,t){let n=F(t,Iie),r=n.side===Ue.BUY?n.amount:n.shares;return dO(e,{amount:r,assetId:n.assetId,orderType:n.orderType,side:n.side})}async function dO(e,t){let n=await Hd(e,{assetId:t.assetId});return Jk({amount:t.amount,orderBook:n,orderType:t.orderType,side:t.side})}function Jk(e){let{orderBook:t}=e,n=e.side===Ue.BUY?Cie(t.asks,e.amount,e.orderType):Nie(t.bids,e.amount,e.orderType);return ge(_ie(n,t.tickSize),`Resolved market price fell outside the valid range for tick size ${t.tickSize}.`),n}function _ie(e,t){return e>=t&&e<=1-t}function Cie(e,t,n){if(e.length===0)throw new So("No resting liquidity.");let r=0;for(let s=e.length-1;s>=0;s-=1){let i=e[s];if(i!==void 0&&(r+=Number.parseFloat(i.size)*Number.parseFloat(i.price),r>=t))return Number.parseFloat(i.price)}if(n===cn.FOK)throw new So("Insufficient liquidity for full fill.");let o=e[0];return Number.parseFloat(o.price)}function Nie(e,t,n){if(e.length===0)throw new So("No resting liquidity.");let r=0;for(let s=e.length-1;s>=0;s-=1){let i=e[s];if(i!==void 0&&(r+=Number.parseFloat(i.size),r>=t))return Number.parseFloat(i.price)}if(n===cn.FOK)throw new So("Insufficient liquidity for full fill.");let o=e[0];return Number.parseFloat(o.price)}function $d(e){return async function(t){F(t,j8);let n=z8(e,t);return X(e.secureClob.post("/order",{json:n,rateLimitBucket:"order"}).mapErr(uO).andThen(z(NC)))}}function tx(e){return async function(t){F(t,Die);let n=t.map(r=>z8(e,r));return X(e.secureClob.post("/orders",{json:n,rateLimitBucket:"order"}).mapErr(uO).andThen(z($3)))}}function z8(e,t){return ge(t.postOnly!==!0||t.orderType===cn.GTC||t.orderType===cn.GTD,"Post-only orders are only supported for GTC and GTD order types."),{deferExec:!1,order:{builder:t.builder,expiration:`${t.expiration}`,maker:t.maker,makerAmount:t.makerAmount,metadata:t.metadata,salt:Number(BigInt(t.salt)),side:t.side,signature:t.signature,signatureType:t.signatureType,signer:t.signer,takerAmount:t.takerAmount,timestamp:t.timestamp,tokenId:t.tokenId},orderType:t.orderType,owner:e.credentials.key,...t.postOnly===!0?{postOnly:!0}:{}}}function Uie(e){try{let t=BigInt(e);return t>=0n&&t<=Oie}catch{return!1}}function K8(e){let t=zt.encode([{name:"legs",type:"uint256[]"}],[e]),n=Je.keccak256(zt.encode([{name:"moduleId",type:"uint256"},{name:"data",type:"bytes"}],[G8,t])),r=VI(`0x03${n.slice(34)}0000000000000000000000000000`);return{conditionId:r,positionIds:[BigInt(`${r}00`).toString(),BigInt(`${r}01`).toString()]}}function Y8(e){if(e.length===0||e.length>n6)throw new E(`Combo legs must include 1 to ${n6} position IDs`);let t=e.map(n=>{let r=pO(n),o=r.toString(16).padStart(W8*2,"0"),s=Number.parseInt(o.slice(0,2),16),i=Number.parseInt(o.slice(-2),16);if(s!==1&&s!==2||i>1)throw new E("Combo legs must be binary or neg-risk YES/NO position IDs");return{value:r,conditionId:o.slice(0,-2)}});t.sort((n,r)=>n.value<r.value?-1:n.value>r.value?1:0);for(let n=1;n<t.length;n+=1){let r=t[n-1],o=t[n];if(r===void 0||o===void 0)throw new E("Invalid combo leg set");if(r.value===o.value)throw new E("Combo legs must not contain duplicate position IDs");if(r.conditionId===o.conditionId)throw new E("Combo legs must not contain both outcomes for the same condition")}return t.map(n=>n.value)}function nx(e){try{return(pO(e)&qie)===0n}catch{return!1}}function Hie(e){let t=pO(e).toString(16).padStart(W8*2,"0"),n=BigInt(`0x${t.slice(0,2)}`),r=Number.parseInt(t.slice(-2),16);if(n!==Bie&&n!==Mie&&n!==G8)throw new E("Position ID must use a supported protocol v2 module");if(r!==0&&r!==1)throw new E("Protocol v2 position ID must be a YES/NO position ID");return{conditionId:_h(`0x${t.slice(0,-2)}`),outcomeIndex:r}}function pO(e){let t=e.trim(),n;if(t.length===0)throw new E("Position ID must be a uint256 value");try{n=BigInt(t)}catch{throw new E("Position ID must be a uint256 value")}if(n<0n||n>Fie)throw new E("Position ID must be a uint256 value");return n}function Q8(e){let t=e*Number(rc),n=Math.round(t),r=Vie*Math.max(1,Math.abs(t)),o=Math.abs(t-n)<=r?n:Math.trunc(t);return BigInt(o)}function bN(e){let t=Math.round(e*Number(rc)),n=t/Number(rc);if(!Number.isSafeInteger(t)||Math.abs(e-n)>$ie)throw new E("has unsupported precision.");return BigInt(t)}function X8(e){return Number(e)/Number(rc)}function mO(e){return ge(Number.isInteger(e)&&e>=0&&e<=dN,`Decimal places must be an integer between 0 and ${dN}.`),10n**BigInt(dN-e)}function hO(e,t,n,r){ge(e>=0n,"Value must be non-negative."),ge(t>=0n,"Multiplier must be non-negative."),ge(n>0n,"Denominator must be positive.");let o=e*t,s=o/n;return r==="up"&&o%n!==0n?s+1n:s}function J8(e,t,n){let r=mO(t);return hO(e,1n,r,n)*r}function Z8(e){switch(e){case .1:return{amount:3,size:2};case .01:return{amount:4,size:2};case .005:return{amount:5,size:2};case .0025:return{amount:6,size:2};case .001:return{amount:5,size:2};case 1e-4:return{amount:6,size:2}}ge(!1,`Unsupported tick size: ${e}`)}function e5(e,t){let n=bN(e),r=bN(t);if(n<r||n>rc-r)throw new E(`must be between ${t} and ${1-t} for tick size ${t}.`);if(n%r!==0n)throw new E(`${e} must be a multiple of tick size ${t}.`);return n}function jie(e,t){return t?e.environment.contracts.negRiskExchange:e.environment.contracts.standardExchange}function Bf(e,t,n){return nx(t)?e.environment.contracts.exchangeV3:jie(e,n)}function wN(e,t,n,r){let o=mO(n);return hO(e,t,rc*o,r)*o}function zie(e,t,n,r){let o=mO(n);return hO(e,rc,t*o,r)*o}function Wie(e){let t=Z8(e.tickSize),n=J8(Q8(e.size),t.size,"down");return e.side===Ue.BUY?{offeredAmount:wN(n,e.price,t.amount,"down"),requestedAmount:n}:{offeredAmount:n,requestedAmount:wN(n,e.price,t.amount,"down")}}function Gie(e){let t=Z8(e.tickSize),n=J8(Q8(e.amount),t.size,"down"),r=e.protectPrice?"up":"down";return e.side===Ue.BUY?{offeredAmount:n,requestedAmount:zie(n,e.price,t.amount,r)}:{offeredAmount:n,requestedAmount:wN(n,e.price,t.amount,r)}}function x0(e,t,n,r){let o=e.get(t);if(o!==void 0&&(o.expiresAt===void 0||o.expiresAt>Date.now()))return o.promise;let s={promise:r()};return s.promise.then(()=>{s.expiresAt=Date.now()+n},()=>{e.get(t)===s&&e.delete(t)}),e.set(t,s),s.promise}function r6(e,t=vN){return{expiresAt:Date.now()+t,promise:Promise.resolve(e)}}function rx(e,t){return fO(e).resolveMarket(t)}function kN(e,t){return fO(e).fetchCurrentMarket(t)}function Yie(e,t){return fO(e).resolveBuilderTakerFeeRate(t)}function fO(e){let t=o6.get(e);if(t!==void 0)return t;let n=new Kie({fetchBuilderTakerFeeRate:async r=>(await sO(e,{builderCode:r})).taker,fetchMarket:r=>oO(e,{conditionId:r}),resolveCondition:r=>rO(e,{assetId:r})});return o6.set(e,n),n}async function Jie(e,t){let n=await Zie(e,{assetId:t.assetId,price:t.price}),r=Wie({price:n.price,side:t.side,size:t.size,tickSize:n.tickSize});return{assetId:t.assetId,builderCode:t.builderCode,chainId:e.environment.chainId,exchangeAddress:n.exchangeAddress,expiration:t.expiration??0,funderAddress:n.funderAddress,offeredAmount:r.offeredAmount,orderType:t.expiration===void 0?cn.GTC:cn.GTD,side:t.side,signer:n.signerAddress,requestedAmount:r.requestedAmount}}async function Zie(e,t){let n=await rx(e,t.assetId);try{return i6(e,t,n)}catch(r){if(!(r instanceof E))throw r;let o=await kN(e,t.assetId);return i6(e,t,o)}}function i6(e,t,n){let r=eae(t.price,n.tickSize);return{exchangeAddress:Bf(e,t.assetId,n.negRisk),funderAddress:e.account.wallet,price:r,signerAddress:e.account.signer,tickSize:n.tickSize}}function eae(e,t){try{return e5(e,t)}catch(n){throw n instanceof E?new E(`Price ${n.message}`,{cause:n}):n}}async function nae(e,t){let n=await rae(e,t,t.assetId),r=Gie({amount:n.resolvedAmount,price:n.price,protectPrice:r5(t),side:t.side,tickSize:n.tickSize});return{assetId:t.assetId,builderCode:t.builderCode,chainId:e.environment.chainId,exchangeAddress:n.exchangeAddress,expiration:0,funderAddress:n.funderAddress,offeredAmount:r.offeredAmount,orderType:t.orderType,side:t.side,signer:n.signerAddress,requestedAmount:r.requestedAmount}}async function rae(e,t,n){return r5(t)?oae(e,t,n):sae(e,t,n)}async function oae(e,t,n){let r=t.side===Ue.BUY?t.amount:t.shares;if(t.side===Ue.BUY&&t.maxSpend!==void 0){let{builderTakerFeeRate:s,market:i}=await o5(e,n,t.builderCode);try{return c6(e,t,n,r,s,t.maxSpend,i)}catch(a){if(!(a instanceof E))throw a;let l=await kN(e,n);return c6(e,t,n,r,s,t.maxSpend,l)}}let o=await rx(e,n);try{return u6(e,t,n,r,o)}catch(s){if(!(s instanceof E))throw s;let i=await kN(e,n);return u6(e,t,n,r,i)}}function c6(e,t,n,r,o,s,i){let a=n5(t,i.tickSize),l=X8(a);return{exchangeAddress:Bf(e,n,i.negRisk),funderAddress:e.account.wallet,price:a,resolvedAmount:s5({amount:r,builderTakerFeeRate:o,maxSpend:s,platformFeeExponent:i.feeInfo.exponent,platformFeeRate:i.feeInfo.rate,price:l}),signerAddress:e.account.signer,tickSize:i.tickSize}}function u6(e,t,n,r,o){let s=n5(t,o.tickSize);return{exchangeAddress:Bf(e,n,o.negRisk),funderAddress:e.account.wallet,price:s,resolvedAmount:r,signerAddress:e.account.signer,tickSize:o.tickSize}}async function sae(e,t,n){let r=t.side===Ue.BUY?t.amount:t.shares,o=t.side===Ue.BUY&&t.maxSpend!==void 0?o5(e,n,t.builderCode):void 0,[s,i]=await Promise.all([Hd(e,{assetId:n}),o]);if(s.assetId!==n)throw new C(`Order book returned asset ${s.assetId} for requested asset ${n}.`);let a=bN(Jk({amount:r,orderBook:s,orderType:t.orderType,side:t.side}));return{exchangeAddress:Bf(e,n,s.negRisk),funderAddress:e.account.wallet,price:a,resolvedAmount:iae(t,r,X8(a),i),signerAddress:e.account.signer,tickSize:s.tickSize}}function iae(e,t,n,r){return e.side!==Ue.BUY||e.maxSpend===void 0||r===void 0?t:s5({amount:t,builderTakerFeeRate:r.builderTakerFeeRate,maxSpend:e.maxSpend,platformFeeExponent:r.market.feeInfo.exponent,platformFeeRate:r.market.feeInfo.rate,price:n})}function n5(e,t){return e.side===Ue.BUY?(ge(e.maxPrice!==void 0,"Protected BUY market order requires maxPrice."),d6("maxPrice",e.maxPrice,t)):(ge(e.minPrice!==void 0,"Protected SELL market order requires minPrice."),d6("minPrice",e.minPrice,t))}function d6(e,t,n){try{return e5(t,n)}catch(r){throw r instanceof E?new E(`${e} ${r.message}`,{cause:r}):r}}function r5(e){return e.side===Ue.BUY&&e.maxPrice!==void 0||e.side===Ue.SELL&&e.minPrice!==void 0}async function o5(e,t,n){let[r,o]=await Promise.all([rx(e,t),Yie(e,n)]);return{builderTakerFeeRate:o,market:r}}function s5(e){let t=e.platformFeeRate*(e.price*(1-e.price))**e.platformFeeExponent,n=e.amount/e.price*t,r=e.amount+n+e.amount*e.builderTakerFeeRate;return e.maxSpend<=r?e.maxSpend/(1+t/e.price+e.builderTakerFeeRate):e.amount}function ox(e){let t=mae(e.domain,e.order);return e.order.signatureType!==Rr.POLY_1271?t:{domain:p5(e.domain),message:{chainId:e.domain.chainId,contents:t.message,name:aae,salt:xN,verifyingContract:e.order.signer,version:lae},primaryType:"TypedDataSign",types:{EIP712Domain:a5,Order:l5,TypedDataSign:pae}}}function sx(e){if(e.order.signatureType!==Rr.POLY_1271)return e.signature;let t=we.toHex(we.fromString(AN)),n=AN.length.toString(16).padStart(4,"0");return ZF(`0x${e.signature.slice(2)}${hae(e.domain).slice(2)}${fae(e.order).slice(2)}${t.slice(2)}${n}`)}function gO(e){return{chainId:e.chainId,exchange:e.exchange,protocolVersion:"3"}}function c5(e,t,n){return e===Ue.SELL?n.toString():((t*n+999999n)/1000000n).toString()}function u5(e,t,n){return e===Ue.SELL?(t*n/1000000n).toString():n.toString()}function d5(e){return{builder:e.builder??xN,maker:e.maker,makerAmount:BigInt(e.makerAmount),metadata:e.metadata??xN,salt:BigInt(e.salt),side:ix(e.side),signatureType:e.signatureType,signer:e.signer,takerAmount:BigInt(e.takerAmount),timestamp:BigInt(e.timestamp),tokenId:BigInt(e.tokenId)}}function mae(e,t){return{domain:p5(e),message:d5(t),primaryType:"Order",types:{EIP712Domain:a5,Order:l5}}}function p5(e){return{chainId:e.chainId,name:i5,verifyingContract:e.exchange,version:e.protocolVersion}}function hae(e){return zn(Je.keccak256(zt.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"address"}],[uae,dae,gae(e.protocolVersion),BigInt(e.chainId),e.exchange]),{as:"Hex"}))}function fae(e){let t=d5(e);return zn(Je.keccak256(zt.encode([{type:"bytes32"},{type:"uint256"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},{type:"uint8"},{type:"uint8"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"}],[cae,t.salt,t.maker,t.signer,t.tokenId,t.makerAmount,t.takerAmount,t.side,t.signatureType,t.timestamp,t.metadata,t.builder]),{as:"Hex"}))}function gae(e){return zn(Je.keccak256(we.fromString(e),{as:"Hex"}))}function ix(e){return e===0||e===1?e:e===Ue.BUY?0:1}function m5(e,t){let n=oc(t);return{builder:e.builderCode??p6,chainId:e.chainId,exchangeAddress:e.exchangeAddress,expiration:e.expiration,maker:n.maker,makerAmount:e.offeredAmount.toString(),metadata:p6,orderType:e.orderType,protocolVersion:nx(e.assetId)?"3":"2",salt:yae().toString(),side:e.side,signatureType:n.signatureType,signer:n.signer,takerAmount:e.requestedAmount.toString(),timestamp:Date.now().toString(),tokenId:e.assetId}}function h5(e,t){let{chainId:n,exchangeAddress:r,protocolVersion:o,...s}=e;return{...s,signature:t}}function yae(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)&(1n<<53n)-1n}function f5(e){return ox({domain:y5(e),order:e})}function g5(e,t){return sx({domain:y5(e),order:e,signature:t})}function y5(e){return{chainId:e.chainId,exchange:e.exchangeAddress,protocolVersion:e.protocolVersion}}function ax(e){return{kind:"signOrder",payload:e}}async function lx(e,t){let n=F(t,tae);return async function*(){let r=await nae(e,n),o=m5(r,e.account),s=rs(yield ax(f5(o)));return h5(o,N0(e.account,g5(o,s)))}.call(null)}async function cx(e,t){let n=F(t,Xie);return async function*(){let r=await Jie(e,n),o=m5(r,e.account),s=rs(yield ax(f5(o))),i=h5(o,N0(e.account,g5(o,s)));return n.postOnly===!0?{...i,postOnly:!0}:i}.call(null)}async function w5(e,t){return x5(e,lx(e,t))}async function k5(e,t){return x5(e,cx(e,t))}async function x5(e,t){let n=await t;return async function*(){let r=yield*n;return $d(e)(r)}.call(null)}function xae(e){return e.status===Qi.Confirmed||e.status===Qi.Failed}function m6(e){return e.status===Qi.Failed}async function dx(e,t,n){let{timeoutMs:r=wae}=F(n,kae),o=[...new Set(t.tradeIds)];if(o.length===0)return[...t.transactionsHashes];let s=new Map,i=Date.now()+r;for(;s.size<o.length;){let l=o.filter(u=>!s.has(u)),c=await Promise.all(l.map(u=>Tf(e,{id:u}).firstPage()));for(let u of c)for(let d of u.items)o.includes(d.id)&&xae(d)&&s.set(d.id,d);if(s.size===o.length)break;if(Date.now()>=i){let u=o.filter(d=>!s.has(d));throw new tt(`Timed out waiting for trades to settle: ${u.join(", ")}`)}await ns(bae)}let a=[...s.values()];if(a.every(m6))throw new en(`Every fill of order ${t.orderId} failed execution: ${o.join(", ")}`);return[...new Set(a.filter(l=>!m6(l)).map(l=>l.transactionHash))].map(l=>et.parse(l))}function A5(e,t){return e===Ue.BUY?sa.COLLATERAL:nx(t)?sa.CONDITIONAL_V2:sa.CONDITIONAL}async function Aae(e,t){let n=A5(t.side,t.assetId),{allowances:r}=await W0(e,t.side===Ue.BUY?{assetType:n}:{assetType:n,assetId:t.assetId});return Tae(r,t.spenderAddress)}function Tae(e,t){return Object.entries(e).find(([n])=>Wt(n,t))?.[1]??0n}function Mf(e,t){return lx(e,t).then(wn(e.signer))}function hx(e,t){return Mf(e,t).then(n=>T5(e,n))}function Ff(e,t){return cx(e,t).then(wn(e.signer))}function yx(e,t){return Ff(e,t).then(n=>T5(e,n))}async function T5(e,t){let n=$d(e);try{return await n(t)}catch(r){if(!Pae(r))throw r;let o=await Sae(e,t,n);if(o===void 0)throw r;return o}}async function Sae(e,t,n){return await Eae(e,t)?n(t):void 0}function Pae(e){return e instanceof O&&e.status===400&&e.message.includes("allowance is not enough")}async function Eae(e,t){let n=t.tokenId,r=await rx(e,n),o=Bf(e,n,r.negRisk),s=BigInt(t.makerAmount);return await Aae(e,{assetId:n,spenderAddress:o,side:t.side})>=s?!1:(await(t.side===Ue.BUY?await Nf(e,{amount:"max",spenderAddress:o,tokenAddress:e.environment.contracts.collateralToken}):await Of(e,{operatorAddress:o,tokenAddress:nx(n)?e.environment.contracts.positionManager:e.environment.contracts.conditionalTokens})).wait(),await ON(e,{assetType:A5(t.side,n),tokenId:t.side===Ue.SELL?n:void 0}),!0)}function Rae(e){let t=fo.getSignPayload(wO(e));return rs(rw.toHex(ad.sign({payload:t,privateKey:e.privateKey})))}function wO(e){let t={chainId:e.chainId,name:"Polymarket",version:"1"};return{domain:t,message:{data:Je.keccak256(sN(S5(e.op)),{as:"Hex"}),salt:BigInt(e.salt),ts:BigInt(e.timestamp)},primaryType:"Op",types:{EIP712Domain:fo.extractEip712DomainTypes(t),Op:[{name:"data",type:"bytes32"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}]}}}function S5(e){return Array.isArray(e)?e.filter(t=>t!==void 0).map(S5):e}function qf(){let[e]=crypto.getRandomValues(new Uint32Array(1));return ge(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}function h6(e,t){let[n,r=""]=e.split("."),[o,s=""]=t.split("."),i=Math.max(r.length,s.length),a=BigInt(`${n}${r.padEnd(i,"0")}`),l=BigInt(`${o}${s.padEnd(i,"0")}`);return a<l?e:t}async function wx(e,t){let n=F(t,_ae);return X(e.perps.get("/v1/info/builder",{params:ve(n,Ee())}).andThen(z(Jh)))}async function Nae(e,t,n){let r=F(n,P5);if(r.builderAddress===void 0)throw new E("A builder address is required when the session has no builder attribution.");let o=Oae(await t.fetchBuilderApprovals({builder:r.builderAddress}),r.builderAddress),s={...F({builder:r.builderAddress,maxFeeRate:r.maxFeeRate,approvalVersion:o},Cae),chainId:e.environment.chainId,salt:qf(),timestamp:Date.now()},i;try{i=await e.signer.signTypedData(Lae(s))}catch(a){throw ue.fromError(a,"Could not sign builder consent")}return X(e.perps.post("/v1/account/builder-approvals",{json:Dae(s,i)}).andThen(z(zw)))}function Oae(e,t){return(e.find(n=>n.builder.toLowerCase()===t.toLowerCase())?.approvalVersion??0)+1}function Lae(e){return wO({chainId:e.chainId,op:["approveBuilder",[e.builder,e.maxFeeRate,e.approvalVersion]],salt:e.salt,timestamp:e.timestamp})}function Dae(e,t){return{op:{type:"approveBuilder",args:{builder:e.builder,max_fee_rate:e.maxFeeRate,approval_version:e.approvalVersion}},salt:e.salt,sig:t,ts:e.timestamp}}function Uae(e,t){let n=f6(e.get("Poly-RateLimit-Remaining"),/^-?\d+$/),r=f6(e.get("Poly-RateLimit-Reset"),/^\d+$/),o=Bae(e.get("Poly-RateLimit-Tier")),s=e.get("Poly-RateLimit-Warning")?.trim().toLowerCase()==="true";if(!(n===void 0&&r===void 0&&o===void 0&&!s))return{...t===void 0?{}:{bucket:t},remaining:n,reset:r,tier:o,warning:s}}function f6(e,t){let n=e?.trim();if(n===void 0||!t.test(n))return;let r=Number(n);return Number.isSafeInteger(r)?r:void 0}function Bae(e){if(!(e===null||e.trim()===""))return e}function Kae(e,t){if(t===void 0)return new WebSocket(e);try{let n=Reflect.construct(WebSocket,[e,{headers:t}]);if(n instanceof WebSocket)return n}catch(n){throw new _("WebSocket headers require a header-capable WebSocket implementation.",{cause:n})}throw new _("WebSocket headers require a header-capable WebSocket implementation.")}function Yae(e,t){let n=Math.min(t.baseMs*2**e,t.maxMs);return Math.random()*n}function Qae(e,t,n){let r=new Set(n.seenKeys),o=e.filter(l=>!r.has(String(l.transferId)));if(!t)return{items:o,hasMore:!1};let s=e.at(-1);if(s===void 0)throw new C("Perps internal-transfer history reported more records without a continuation timestamp.");let i=Math.min(n.endTimestamp,s.createdTimestamp+1);if(i===n.endTimestamp&&o.length===0)throw new C("Perps internal-transfer history cannot continue within a full millisecond without skipping records.");let a=new Set(i===n.endTimestamp?n.seenKeys:[]);for(let l of e)l.createdTimestamp>=i-1&&a.add(String(l.transferId));return{items:o,hasMore:!0,nextCursor:btoa(JSON.stringify({...n,endTimestamp:i,seenKeys:Array.from(a)}))}}async function Zae(e){return await X(e.get("/v1/account/balances").andThen(z(R_)))}async function ele(e){return await X(e.get("/v1/account/portfolio").andThen(z(__)))}async function tle(e){return await X(e.get("/v1/account/stats").andThen(z(I_)))}async function nle(e){return await X(e.get("/v1/account/auto-cancel").andThen(z(k4)))}async function ole(e,t){let n=F(t,rle);return await X(e.get("/v1/account/config",{params:Xr(n)}).andThen(z(O_)))}async function ile(e,t){let n=F(t,sle);return await X(e.get("/v1/account/open-orders",{params:Xr(n)}).andThen(z(wC)))}async function cle(e,t){let n=F(t,lle);return await X(e.get("/v1/account/orders",{params:Xr(n)}).andThen(z(bC)))}function dle(e,t={}){let n=F(t,ule);return Fe(r=>e.get("/v1/account/fills",{params:Xr({startTimestamp:n.start,endTimestamp:n.end,sort:n.sort,cursor:r??n.cursor})}).andThen(z(kC)).map(o=>{let s=o.data.at(-1);return!o.more||s===void 0?{items:o.data,hasMore:!1}:{items:o.data,hasMore:!0,nextCursor:String(s.tradeId)}}),n.cursor)}function fle(e,t={}){let{cursor:n,params:r}=F(t,hle);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps funding payment params."),s={kind:"perpsFundingPayments",seenKeys:[],...r}):s=Io(o,TO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/funding",{params:Xr(l)}).andThen(z(C_)).map(u=>{let d=u.data.filter(p=>!c.has(`${p.instrumentId}:${p.timestamp}:${p.funding}`));return SO({getKey:p=>`${p.instrumentId}:${p.timestamp}:${p.funding}`,getTimestamp:p=>p.timestamp,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function wle(e,t={}){let{cursor:n,params:r}=F(t,ble);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps deposit params."),s={kind:"perpsDeposits",seenKeys:[],...r}):s=Io(o,TO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/deposits",{params:Xr(l)}).andThen(z(V_)).map(u=>{let d=u.data.filter(p=>!c.has(p.hash));return SO({getKey:p=>p.hash,getTimestamp:Kle,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Ale(e,t={}){let{cursor:n,params:r}=F(t,xle);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps withdrawal params."),s={kind:"perpsWithdrawals",seenKeys:[],...r}):s=Io(o,TO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/withdrawals",{params:Xr(l)}).andThen(z(z_)).map(u=>{let d=u.data.filter(p=>!c.has(String(p.withdrawalId)));return SO({getKey:p=>String(p.withdrawalId),getTimestamp:Yle,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Rle(e,t={}){let{cursor:n,params:r}=F(t,Ele);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps internal-transfer params."),s={kind:"perpsInternalTransfers",seenKeys:[],...r}):s=Io(o,Sle,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s;return e.get("/v1/account/internal-transfers",{params:Xr(l)}).andThen(z(K_)).map(c=>Qae(c.data,c.more,s))},n)}function Nle(e,t){let{cursor:n,params:r}=F(t,Cle);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps equity history params."),s={kind:"perpsEquityHistory",...r}):s=Io(o,C5,"Invalid Perps account pagination cursor");let{kind:i,...a}=s;return e.get("/v1/account/equity",{params:Xr(a)}).andThen(z(L_)).map(l=>{let c=l.data.at(-1),u=l.more&&c!==void 0&&c.timestamp<s.endTimestamp;return{items:l.data,hasMore:u,nextCursor:u?di({...s,startTimestamp:c.timestamp+O5(s.interval)}):void 0}})},n)}function Ule(e,t){let{cursor:n,params:r}=F(t,Dle);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps PnL history params."),s={kind:"perpsPnlHistory",...r}):s=Io(o,C5,"Invalid Perps account pagination cursor");let{kind:i,...a}=s;return e.get("/v1/account/pnl",{params:Xr(a)}).andThen(z(D_)).map(l=>{let c=l.data.at(-1),u=l.more&&c!==void 0&&c.timestamp<s.endTimestamp;return{items:l.data,hasMore:u,nextCursor:u?di({...s,startTimestamp:c.timestamp+O5(s.interval)}):void 0}})},n)}function Hle(e,t={}){let{cursor:n,params:r}=F(t,qle);return Fe(o=>{let s;o===void 0?ge(r!==void 0,"Expected initial Perps notifications params."):s=Io(o,Ble,"Invalid Perps account pagination cursor");let i=s===void 0?r?.sinceSeq:s.sinceSeq,a=s===void 0?r?.limit:s.limit;return e.get("/v1/account/notifications",{params:Xr({cursor:s?.cursor,limit:a,sinceSeq:i})}).andThen(z(uC)).map(l=>{let c=l.has_more&&l.next_cursor!==null;return{items:l.items,hasMore:c,nextCursor:c&&l.next_cursor!==null?di({kind:"perpsNotifications",cursor:l.next_cursor,limit:a,sinceSeq:i}):void 0}})},n)}async function $le(e){return(await X(e.get("/v1/account/notifications",{params:Xr({limit:1})}).andThen(z(dC)))).unread}async function Wle(e,t){let n=F(t,zle),r=await X(e.post("/v1/account/notifications/read",{json:n}).andThen(z(pC)));if(r.status==="err")throw new O(r.error??"Perps notifications read request was rejected.",{status:200})}function Gle(e){return btoa(JSON.stringify({ts:e.timestamp,id:e.id})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function xx(e,t){let n=Date.now(),{end:r,start:o,...s}=e;return{...s,endTimestamp:r??n,startTimestamp:o??n-t}}function N5(e){return{endTimestamp:e.end??Date.now(),interval:e.interval,startTimestamp:e.start}}function Xr(e){return ve(e,Ee())}function Kle(e){return e.confirmedTimestamp??e.createdTimestamp}function Yle(e){return e.confirmedTimestamp??e.createdTimestamp}function SO(e){let t=e.responseData.at(-1),n=e.items.at(-1),r=(n===void 0?void 0:e.getTimestamp(n))??(t===void 0?void 0:e.getTimestamp(t)),o=e.responseMore&&r!==void 0&&r>e.state.startTimestamp;if(!o)return{items:e.items,hasMore:o};let s=n===void 0?r-1:r,i=new Set(e.state.endTimestamp===s?e.state.seenKeys:[]);for(let a of e.items)e.getTimestamp(a)===s&&i.add(e.getKey(a));return{items:e.items,hasMore:o,nextCursor:di({...e.state,endTimestamp:s,seenKeys:Array.from(i)})}}function O5(e){switch(e){case"1h":return 3600*1e3;case"4h":return 14400*1e3;case"1d":return P0;case"1w":return 7*P0}ge(!1,`Unsupported Perps account history interval: ${String(e)}`)}async function Xle(e,t){let n=F(t,Qle);return(await X(e.get("/v1/account/builder-approvals",{params:ve(n,Ee())}).andThen(z(F_)))).data}function Zle(e,t){let n=F(t,L5);return Fe(r=>e.get("/v1/account/builder-earnings",{params:r===void 0?ve(n,{start:"start_timestamp",end:"end_timestamp",asOfSequence:"as_of_sequence"}):new URLSearchParams({cursor:r})}).andThen(z(H_)).map(o=>{if(!o.more)return{items:o.data,hasMore:!1};if(o.cursor===void 0||o.cursor===r)throw new C("Builder earnings pagination did not return a new cursor");return{items:o.data,hasMore:!0,nextCursor:o.cursor}}))}async function ece(e,t){let n=F(t,L5);return X(e.get("/v1/account/builder-earnings-summary",{params:ve(n,{start:"start_timestamp",end:"end_timestamp",asOfSequence:"as_of_sequence"})}).andThen(z($_)))}async function ice(e,t){let n=F(t,sce),r=e.builderAttribution;return await e.executeCommand({op:["createOrders",n.orders.map(o=>RO(o,r))],expiresAt:n.expiresAt},h.z.array(sf))}function cce(e){return e.takeProfit!==void 0||e.stopLoss!==void 0}async function uce(e,t){if(cce(t))return await dce(e,t);let n=F(t,lce),r=e.builderAttribution,[,o]=await e.executeCommandWithEvent({op:["createOrders",[RO(n,r)]],expiresAt:n.expiresAt},D5,B5(n.clientOrderId));return{order:o.payload}}async function dce(e,t){let n=F(t,ace),r=e.builderAttribution,o=[RO(n,r)],s=n.side===Ue.SELL;n.takeProfit!==void 0&&o.push(I0({buy:s,instrumentId:n.instrumentId,kind:ra.TakeProfit,quantity:n.quantity,builderAttribution:r,trigger:n.takeProfit})),n.stopLoss!==void 0&&o.push(I0({buy:s,instrumentId:n.instrumentId,kind:ra.StopLoss,quantity:n.quantity,builderAttribution:r,trigger:n.stopLoss}));let[i,a]=await e.executeCommandWithEvent({op:["createOrders",o,vd.Order],expiresAt:n.expiresAt},D5,B5(n.clientOrderId)),l=1,c={};return n.takeProfit!==void 0&&(c.takeProfit=R0(Qs(i[l++],"Expected Perps take-profit acknowledgement."))),n.stopLoss!==void 0&&(c.stopLoss=R0(Qs(i[l],"Expected Perps stop-loss acknowledgement."))),{order:a.payload,tpSl:c}}async function hce(e,t){let n=F(t,mce),r=e.builderAttribution,o=Bce(await e.fetchPortfolio(),n.instrumentId),s=[];n.takeProfit!==void 0&&s.push(I0({buy:o,instrumentId:n.instrumentId,kind:ra.TakeProfit,quantity:"0",builderAttribution:r,trigger:n.takeProfit})),n.stopLoss!==void 0&&s.push(I0({buy:o,instrumentId:n.instrumentId,kind:ra.StopLoss,quantity:"0",builderAttribution:r,trigger:n.stopLoss}));let i=await e.executeCommand({op:["createOrders",s,vd.Position],expiresAt:n.expiresAt},h.z.array(sf));for(let c of i)if(c.status==="err")throw new O(c.error,{status:200});let a=0,l={};return n.takeProfit!==void 0&&(l.takeProfit=R0(Qs(i[a++],"Expected Perps take-profit acknowledgement."))),n.stopLoss!==void 0&&(l.stopLoss=R0(Qs(i[a],"Expected Perps stop-loss acknowledgement."))),{tpSl:l}}async function wce(e,t){let n=F(t,bce),[r]=n.orderId!==void 0?await PN(e,{orderIds:[n.orderId],expiresAt:n.expiresAt,retry:n.retry,signal:n.signal}):await PN(e,{clientOrderIds:[n.clientOrderId],expiresAt:n.expiresAt,retry:n.retry,signal:n.signal});return Qs(r,"Expected Perps cancel order result.")}async function PN(e,t){let n=F(t,vce);return n.orderIds!==void 0?await g6(n.orderIds,n,async r=>await e.executeCommand({op:["cancelOrders",r],expiresAt:n.expiresAt},h.z.array(Kw))):await g6(n.clientOrderIds,n,async r=>await e.executeCommand({op:["cancelOrdersCOID",r],expiresAt:n.expiresAt},h.z.array(Kw)))}async function g6(e,t,n){let r=t.retry===!1?1:t.retry.maxAttempts,o=t.retry===!1?Number.POSITIVE_INFINITY:Math.min(Date.now()+t.retry.maxElapsedMs,t.expiresAt??Number.POSITIVE_INFINITY),s=new Array(e.length),i=e.map((l,c)=>({identifier:l,resultIndex:c})),a=0;for(Tce(t.signal);i.length>0;){if(a>0){let u=o-Date.now(),d=xce(a);if(u<=0||d>=u||!await Ace(d,t.signal)||t.signal?.aborted||Date.now()>=o)break}let l;try{l=await n(i.map(({identifier:d})=>d));let u=kce(l);if(u!==void 0)throw new O(u,{status:200});if(l.length!==i.length)throw new C("Perps cancel response did not include one result per requested order.")}catch(u){throw a===0?u:new Jw("Perps cancellation retry failed.",{cause:u,results:s.map(d=>Qs(d,"Expected a previous Perps cancel result.")),pendingIndexes:i.map(({resultIndex:d})=>d)})}a+=1;let c=[];for(let[u,d]of l.entries()){let p=Qs(i[u],"Expected a pending Perps cancellation.");s[p.resultIndex]=d,a<r&&d.status==="err"&&d.error===Sd.OrderInFlight&&c.push(p)}i=c}return s.map(l=>Qs(l,"Expected a final Perps cancel result."))}function kce(e){let[t]=e;if(!(e.length!==1||t?.status!=="err"||t.orderId!==void 0||t.clientOrderId!==void 0))return t.error}function xce(e){let t=Math.min(fce*2**(e-1),gce);return Math.random()*t}function Ace(e,t){if(t?.aborted)return Promise.resolve(!1);if(e<=0)return Promise.resolve(!0);if(t===void 0)return new Promise(r=>gn(()=>r(!0),e));let n=t;return new Promise(r=>{let o=gn(()=>{n.removeEventListener("abort",s),r(!0)},e);function s(){clearTimeout(o),r(!1)}n.addEventListener("abort",s,{once:!0})})}function Tce(e){if(e?.aborted)throw Xw.fromReason(e.reason)}async function Pce(e,t){let n=F(t,Sce),r=["cancelAll",n.instrumentId===void 0?[]:[n.instrumentId]];await e.executeDeleteCommand({path:"/v1/trade/orders/all",op:r,responseSchema:fC,expiresAt:n.expiresAt})}async function _ce(e,t,n){let r=F(n,Rce),o=["autoCancel",[r.cancelAt]],s=t(o,r.expiresAt);await X(e.patch("/v1/trade/auto-cancel",{json:{...s,op:_0(o)}}).andThen(z(nN)).mapErr(i=>i instanceof O&&i.message.startsWith(`${Ice} (`)?new lf("Auto-cancel daily trigger limit reached.",{cause:i}):i))}async function Nce(e,t,n){let r=F(n,Cce),o=["autoCancel",[0]],s=t(o,r.expiresAt);await X(e.patch("/v1/trade/auto-cancel",{json:{...s,op:_0(o)}}).andThen(z(nN)))}async function Lce(e,t){let n=F(t,Oce);return await e.executeCommand({op:["updateLeverage",[n.instrumentId,n.leverage,n.crossMargin]]},gC)}async function Uce(e,t){let n=F(t,Dce),r=n.amount,o=await e.executeCommand({op:["updateMargin",[n.instrumentId,r]]},of);if(o.status==="err")throw new O(o.error,{status:200})}function U5(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16));return Er.parse(Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""))}function B5(e){return t=>t.type==="order"&&t.payload.clientOrderId===e}function R0(e){if(e.status==="err")throw new O(e.error,{status:200});return{orderId:e.orderId}}function Bce(e,t){let n=e.positions.find(o=>o.instrumentId===t),r=n===void 0?0:Mce(n.size);if(r===0)throw new E(`No open Perps position for instrument ${t}.`);return r<0}function Mce(e){let t=e.trim(),n=t.replace(/^[+-]/,"").replace(".","");return/^0*$/.test(n)?0:t.startsWith("-")?-1:1}function RO(e,t){return[e.instrumentId,e.side===Ue.BUY,e.price===void 0?void 0:e.price,e.quantity,e.timeInForce,e.postOnly??!1,e.reduceOnly===!0?!0:void 0,e.clientOrderId,void 0,void 0,t===void 0?void 0:[t.builderAddress,t.feeRate]]}function I0(e){return[e.instrumentId,e.buy,e.trigger.limitPrice===void 0?void 0:e.trigger.limitPrice,e.quantity,void 0,!1,!0,void 0,[e.trigger.limitPrice===void 0?!0:void 0,e.trigger.triggerPrice,e.kind],void 0,e.builderAttribution==null?void 0:[e.builderAttribution.builderAddress,e.builderAttribution.feeRate]]}function _0(e){let[t,n,r]=e;switch(t){case"createOrders":return Hce({args:n.map(Fce),type:t},r);case"cancelOrders":case"cancelOrdersCOID":return{type:t,args:n};case"autoCancel":{let[o]=n;return{type:t,args:{time:o}}}case"cancelAll":{let[o]=n;return{type:t,args:o===void 0?{}:{iid:o}}}case"updateLeverage":{let[o,s,i]=n;return{type:t,args:{cross:i,iid:o,lev:s}}}case"updateMargin":{let[o,s]=n;return{type:t,args:{amt:s,iid:o}}}default:ge(!1,`Unsupported Perps command: ${String(t)}`)}}function Fce(e){let t={iid:e[0],buy:e[1],po:e[5],qty:e[3]};return e[4]!==void 0&&(t.tif=e[4]),e[6]&&(t.ro=e[6]),e[2]!==void 0&&(t.p=e[2]),e[7]!==void 0&&(t.c=e[7]),e[8]!==void 0&&(t.tr=qce(e[8])),e[10]!==void 0&&(t.builder={address:e[10][0],fee_rate:e[10][1]}),t}function qce(e){let t={tpsl:e[2],trp:e[1]};return e[0]!==void 0&&(t.market=e[0]),t}function Hce(e,t){return t!==void 0&&(e.grp=t),e}function Gce(e){let t,n;return{promise:new Promise((r,o)=>{t=r,n=o}),reject:n,resolve:t,schema:e}}function Kce(e){return Array.isArray(e)?!1:IO(e)!==void 0}function IO(e){if(Array.isArray(e)){for(let n of e){let r=IO(n);if(r!==void 0)return r}return}if(typeof e!="object"||e===null)return;let t=e;if(t.status==="err")return{error:typeof t.error=="string"?t.error:"Perps command failed."}}function Yce(){let[e]=globalThis.crypto.getRandomValues(new Uint32Array(1));return ge(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}async function Qce(e,t){let{label:n,...r}=t,o=await e.signTransfer(r);return e.submitTransfer({...r,signature:o,...n===void 0?{}:{label:n}})}async function Cx(e,t){let n=F(t,Xce);return X(e.perps.get("/v1/info/instruments",{params:ve(n,Ee())}).andThen(z(Q_)))}async function Ox(e,t){let n=F(t,Jce),[r]=await Hf(e,n);if(r===void 0)throw new C(`Perps ticker ${n.instrumentId} was not returned by the API`);return r}async function Hf(e,t){let n=F(t,Zce),r=ve(n,Ee()),[o,s]=await Promise.all([X(e.perps.get("/v1/info/tickers",{params:r}).andThen(z(X_))),X(e.perps.get("/v1/info/statistics",{params:r}).andThen(z(Z_)))]),i=new Map(s.map(a=>[a.instrumentId,a]));return o.map(a=>{let l=i.get(a.instrumentId);return{...a,openPrice:l?.openPrice,volume24h:l?.volume}})}async function Ux(e,t){let n=F(t,tue);return X(e.perps.get("/v1/info/book",{params:ve(n,Ee())}).andThen(z(tC)))}function Mx(e,t){let{cursor:n,params:r}=F(t,oue);return Fe(o=>{let s=o===void 0?fue(r):bue(o);return e.perps.get("/v1/info/klines",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,interval:s.interval,startTimestamp:s.startTimestamp},Ee())}).andThen(z(lC)).map(i=>{let a=i.data.at(-1),l=i.more&&a!==void 0;return{items:i.data,hasMore:l,nextCursor:l?di({...s,startTimestamp:a.timestamp+kue(s.interval)}):void 0}})},n)}function qx(e,t){let{cursor:n,params:r}=F(t,aue);return Fe(o=>{let s=o===void 0?gue(r):wue(o);return e.perps.get("/v1/info/funding",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},Ee())}).andThen(z(iC)).map(i=>{let a=i.data.at(-1),l=i.more&&a!==void 0&&a.timestamp>s.startTimestamp;return{items:i.data,hasMore:l,nextCursor:l?di({...s,endTimestamp:a.timestamp-1}):void 0}})},n)}function $x(e,t){let{cursor:n,params:r}=F(t,uue);return Fe(o=>{let s=o===void 0?yue(r):vue(o),i=new Set(s.seenTradeIds);return e.perps.get("/v1/info/trades",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},Ee())}).andThen(z(sC)).map(a=>{let l=a.data.filter(m=>!i.has(m.tradeId)),c=a.data.at(-1),u=l.at(-1),d=u?.timestamp??c?.timestamp,p=a.more&&d!==void 0&&d>s.startTimestamp;return{items:l,hasMore:p,nextCursor:p?di({...s,endTimestamp:u===void 0?d-1:d,seenTradeIds:u===void 0?[]:xue(s,l,u)}):void 0}})},n)}async function jx(e){return(await X(e.perps.get("/v1/info/fees").andThen(z(aC)))).feeSchedule}function hue(e){let t=Date.now();return{endTimestamp:e.end??t,instrumentId:e.instrumentId,interval:e.interval,startTimestamp:e.start??t-F5}}function H5(e){let t=Date.now();return{endTimestamp:e.end??t,instrumentId:e.instrumentId,startTimestamp:e.start??t-F5}}function fue(e){return ge(e!==void 0,"Expected initial Perps candles params."),{kind:"perpsCandles",...e}}function gue(e){return ge(e!==void 0,"Expected initial Perps funding params."),{kind:"perpsFundingHistory",...e}}function yue(e){return ge(e!==void 0,"Expected initial Perps trades params."),{kind:"perpsTrades",seenTradeIds:[],...e}}function bue(e){return Io(e,due,"Invalid Perps pagination cursor")}function wue(e){return Io(e,pue,"Invalid Perps pagination cursor")}function vue(e){return Io(e,mue,"Invalid Perps pagination cursor")}function kue(e){switch(e){case"1s":return 1e3;case"1m":return 60*1e3;case"5m":return 300*1e3;case"15m":return 900*1e3;case"1h":return 3600*1e3;case"4h":return 14400*1e3;case"1d":return 1440*60*1e3;case"1w":return 10080*60*1e3}ge(!1,`Unsupported Perps kline interval: ${String(e)}`)}function xue(e,t,n){let r=new Set(e.endTimestamp===n.timestamp?e.seenTradeIds:[]);for(let o of t)o.timestamp===n.timestamp&&r.add(o.tradeId);return Array.from(r)}async function Qx(e,t={}){let n=F(t,Rue),r="credentials"in n?await Bue(e,n.credentials):await Uue(e,n);return e.webSockets.perpsSession.connect(r,n.builderAttribution,Nae.bind(null,e),n.includeBuilderFills)}async function Xx(e,t){let n=F(t,_ue),r={type:"deleteProxy",args:{proxy:n.proxy}},o=["deleteProxy",[n.proxy]],s=qf(),i=Date.now(),a=await z5(e,{salt:s,signedOp:o,timestamp:i}),l=await X(e.perps.del("/v1/account/proxy",{json:{op:r,salt:s,sig:a,ts:i}}).andThen(z(M_)));if(l.status==="err")throw new O(l.error??"Perps credentials revocation was rejected.",{status:200})}async function _O(e,t){let n=F(t,Cue),{contracts:r}=e.environment,o=VN(r.perpsDepositContract,r.collateralToken,n.amount,e.account.signer);return async function*(){return e.account.walletType===Se.EOA?bn(yield Wue(Qn(e.environment.chainId,o))):yield*await Or(e,{calls:[o],metadata:n.metadata??`Deposit ${n.amount} of ${r.collateralToken} to Perps`})}.call(null)}function Jx(e,t){return _O(e,t).then(wn(e.signer))}async function Zx(e,t){let n=F(t,Nue),r=Math.floor(Date.now()/1e3),o=qf(),s={type:"withdraw",args:{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:n.amount.toString(),to:e.account.wallet}},i=await Fue(e,{amount:n.amount,salt:o,timestamp:r}),a=await X(e.perps.post("/v1/account/withdraw",{json:{op:s,salt:o,sig:i,ts:r}}).andThen(z(W_)));if(a.status==="err")throw new O(a.error??"Perps withdrawal was rejected.",{status:200});if(a.withdrawalId===void 0)throw new C("Perps withdrawal response did not include a withdrawal ID.");return a.withdrawalId}async function eA(e,t){jue(e);let n=F(t,Due);if(Wt(n.recipient,e.account.signer))throw new E("Perps collateral cannot be transferred to the authenticated account.");return Qce({signTransfer({account:r,token:o,amount:s,recipient:i,salt:a,timestamp:l}){return z5(e,{salt:a,signedOp:["internalTransfer",[r,o,s,i]],timestamp:l})},async submitTransfer(r){let o={op:{type:"internalTransfer",args:{account:r.account,token:r.token,amount:r.amount,to:r.recipient}},salt:r.salt,sig:r.signature,ts:r.timestamp};return r.label!==void 0&&(o.label=r.label),(await X(e.perps.post("/v1/account/internal-transfer",{json:o}).andThen(z(Y_)))).transferId}},{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:n.amount,recipient:n.recipient,label:n.label,salt:qf(),timestamp:Date.now()})}async function Uue(e,t){let n=$ue(),r=W5(n),o=e.account.signer,s=Date.now()+t.expiresIn,i=Date.now(),a=qf(),l={args:{expiry:s,owner:o,proxy:r},type:"createProxy"},c=await Mue(e,{expiresAt:s,proxy:r,salt:a,timestamp:i}),u={op:l,salt:a,sig:c,ts:i};t.label!==void 0&&(u.label=t.label);let d=await X(e.perps.post("/v1/account/proxy",{json:u}).andThen(z(B_))),p={expiresAt:s,privateKey:n,proxy:r,secret:d.secret};return j5(e,p)}async function Bue(e,t){return Vue(t),j5(e,t)}async function j5(e,t){let n=await X(e.perps.get("/v1/account/credentials",{headers:zue(t)}).andThen(z(U_)));if(!Wt(n.address,e.account.signer))throw new C("Perps credentials belong to a different signer account.");let r=n.keys.find(o=>Wt(o.proxy,t.proxy));if(r===void 0)throw new C("Perps credentials were not returned by the API.");if(r.expiresAt<=Date.now())throw new C("Perps credentials are expired.");return{...t,expiresAt:r.expiresAt}}async function Mue(e,t){try{return await e.signer.signTypedData(Hue({chainId:e.environment.chainId,...t}))}catch(n){throw ue.fromError(n,"Could not sign the Perps proxy credentials request")}}async function z5(e,t){try{return await e.signer.signTypedData(wO({chainId:e.environment.chainId,op:t.signedOp,salt:t.salt,timestamp:t.timestamp}))}catch(n){throw ue.fromError(n,"Could not sign the Perps operation request")}}async function Fue(e,t){try{return await e.signer.signTypedData(que({account:e.account.signer,chainId:e.environment.chainId,contract:e.environment.contracts.perpsDepositContract,token:e.environment.contracts.collateralToken,to:e.account.wallet,...t}))}catch(n){throw ue.fromError(n,"Could not sign the Perps withdrawal request")}}function que(e){let t={chainId:e.chainId,name:"Polymarket",verifyingContract:e.contract,version:"1"};return{domain:t,message:{account:e.account,amount:e.amount,fee:0n,salt:e.salt,token:e.token,to:e.to,ts:e.timestamp},primaryType:"Withdraw",types:{EIP712Domain:fo.extractEip712DomainTypes(t),Withdraw:[{name:"account",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"to",type:"address"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}]}}}function Hue(e){let t={chainId:e.chainId,name:"Polymarket",version:"1"};return{domain:t,message:{addr:e.proxy,exp:e.expiresAt,salt:e.salt,ts:e.timestamp},primaryType:"CreateProxy",types:{CreateProxy:[{name:"addr",type:"address"},{name:"exp",type:"uint64"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}],EIP712Domain:fo.extractEip712DomainTypes(t)}}}function $ue(){return JF(ad.randomPrivateKey(),"Generated invalid Perps proxy key.")}function W5(e){return Be(Qo.fromPublicKey(ad.getPublicKey({privateKey:e})))}function Vue(e){let t=W5(e.privateKey);if(!Wt(t,e.proxy))throw new E("Perps credentials private key does not match the proxy address.")}function jue(e){if(e.account.signerType!=="OWNER")throw new E("Perps collateral transfers must be signed by the account owner.")}function zue(e){return{"POLYMARKET-PROXY":e.proxy,"POLYMARKET-SECRET":e.secret}}function Wue(e){return{kind:"sendPerpsDepositTransaction",request:e}}function $f(e,t){let{cursor:n,pageSize:r,window:o,...s}=F(t,Gue);return Fe(i=>nn(()=>e.data.get("/v2/positions",{params:tn({...s,...o,limit:r,cursor:i})})).andThen(z(U$)),n)}function Vf(e,t){let{cursor:n,pageSize:r,...o}=F(t,Que);return Fe(s=>nn(()=>e.data.get("/v2/positions/combos",{params:tn({...o,limit:r,cursor:s})})).andThen(z(H$)),n)}async function jf(e,t){let{conditionIds:n,...r}=F(t,Xue);return X(nn(()=>e.data.get("/v2/value",{params:tn({...r,condition:n})})).andThen(z(B$)))}async function zf(e,t){let n=F(t,Jue);return X(nn(()=>e.data.get("/v2/user-stats",{params:tn(n)})).andThen(z(M$)))}async function Wf(e,t){let n=F(t,Zue);return X(nn(()=>e.data.get("/v2/user-pnl",{params:tn(n)})).andThen(z(F$)))}async function Gf(e,t){let{window:n,...r}=F(t,ede);return X(nn(()=>e.data.get("/v2/user-volume",{params:tn({...r,...n})})).andThen(z(q$)))}async function Kf(e,t){let n=F(t,tde);return X(e.data.get("/v1/accounting/snapshot",{params:toe(n)}).andThen(Ire))}function nde(e,t){if(!Gr(e.conditionId))throw new C(`Missing condition ID for ${t}`);if(!Gr(e.version))throw new C(`Missing market version for ${t}`);let n=e.outcomes.yes.tokenId,r=e.outcomes.no.tokenId,o=e.outcomes.yes.positionId,s=e.outcomes.no.positionId;if(e.version===ta.V2){if(Gr(o)!==Gr(s))throw new C(`Incomplete market position IDs for ${t}`);if(!Gr(o)||!Gr(s))throw new C(`Missing market position IDs for ${t}`);return{marketId:e.id,conditionId:e.conditionId,protocol:"v2",outcomeIds:[o,s]}}if(Gr(n)!==Gr(r))throw new C(`Incomplete market token IDs for ${t}`);if(Gr(n)&&Gr(r)){if(!Gr(e.state.negRisk))throw new C(`Missing negative-risk flag for ${t}`);return{marketId:e.id,conditionId:e.conditionId,protocol:"ctf",negRisk:e.state.negRisk,outcomeIds:[n,r]}}throw new C(`Missing market token IDs for ${t}`)}async function cA(e,t){let n=F(t,G5),r=await DO(e,{conditionId:n.conditionId}),o=r.protocol==="ctf"?jN(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId,n.amount):cv(e.environment.contracts.protocolV2Router,r.conditionId,n.amount);return async function*(){return e.account.walletType===Se.EOA?bn(yield EN(Qn(e.environment.chainId,o))):yield*await Or(e,{calls:[o],metadata:n.metadata??`Split ${n.amount} positions for market ${r.marketId} (condition ${r.conditionId})`})}.call(null)}async function uA(e,t){let n=F(t,Y5),r=Y8(n.legs),o=dv(e.environment.contracts.combinatorialModule,r),s=K8(r),i=cv(e.environment.contracts.protocolV2Router,s.conditionId,n.amount);return async function*(){return e.account.walletType===Se.EOA?(await bn(yield EN(Qn(e.environment.chainId,o))).wait(),bn(yield EN(Qn(e.environment.chainId,i)))):yield*await Or(e,{calls:[o,i],metadata:n.metadata??`Split ${n.amount} combo positions for condition ${s.conditionId}`})}.call(null)}async function CO(e,t){let n=F(t,rde);return n.legs!==void 0?uA(e,n):cA(e,n)}function J5(e,t){return cA(e,t).then(wn(e.signer))}function eV(e,t){return uA(e,t).then(wn(e.signer))}function dA(e,t){return CO(e,t).then(wn(e.signer))}async function mA(e,t){let n=F(t,tV),r=await DO(e,{conditionId:n.conditionId}),o=Rf(await e.rpc.ethCall(Ef(r.positionErc1155Address,e.account.wallet,r.outcomeIds))),s=fV(r.conditionId,o,n.amount),i=r.protocol==="ctf"?zN(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId,s):uv(e.environment.contracts.protocolV2Router,r.conditionId,s);return async function*(){return e.account.walletType===Se.EOA?bn(yield RN(Qn(e.environment.chainId,i))):yield*await Or(e,{calls:[i],metadata:n.metadata??`Merge ${s} positions for market ${r.marketId} (condition ${r.conditionId})`})}.call(null)}async function hA(e,t){let n=F(t,rV),r=Y8(n.legs),o=dv(e.environment.contracts.combinatorialModule,r),s=K8(r),i=Rf(await e.rpc.ethCall(Ef(e.environment.contracts.positionManager,e.account.wallet,s.positionIds))),a=fV(s.conditionId,i,n.amount),l=uv(e.environment.contracts.protocolV2Router,s.conditionId,a);return async function*(){return e.account.walletType===Se.EOA?(await bn(yield RN(Qn(e.environment.chainId,o))).wait(),bn(yield RN(Qn(e.environment.chainId,l)))):yield*await Or(e,{calls:[o,l],metadata:n.metadata??`Merge ${a} combo positions for condition ${s.conditionId}`})}.call(null)}async function NO(e,t){let n=F(t,ode);return n.legs!==void 0?hA(e,n):mA(e,n)}function iV(e,t){return mA(e,t).then(wn(e.signer))}function lV(e,t){return hA(e,t).then(wn(e.signer))}function fA(e,t){return NO(e,t).then(wn(e.signer))}async function OO(e,t){let n=F(t,sde),r=await DO(e,n.conditionId!==void 0?{conditionId:n.conditionId,closed:!0}:{marketId:n.marketId,closed:!0}),o=await cde(e,r);return async function*(){return e.account.walletType===Se.EOA?yield*ade(e,o):yield*await Or(e,{calls:o,metadata:n.metadata??`Redeem positions for market ${r.marketId} (condition ${r.conditionId})`})}.call(null)}async function yA(e,t){let n=F(t,pV),r=Hie(n.positionId),o=qN(await e.rpc.ethCall(FN(e.environment.contracts.positionManager,e.account.wallet,n.positionId)));if(o===0n)throw new E("Position has no balance to redeem");let s=wf(e.environment.contracts.protocolV2Router,r.conditionId,r.outcomeIndex,o);return async function*(){return e.account.walletType===Se.EOA?bn(yield IN(Qn(e.environment.chainId,s))):yield*await Or(e,{calls:[s],metadata:n.metadata??`Redeem position ${n.positionId}`})}.call(null)}function hV(e,t){return yA(e,t)}async function LO(e,t){let n=F(t,ide);return n.positionId!==void 0?yA(e,n):OO(e,n)}function wA(e,t){return LO(e,t).then(wn(e.signer))}function EN(e){return{kind:"sendSplitPositionTransaction",request:e}}function RN(e){return{kind:"sendMergePositionsTransaction",request:e}}function IN(e){return{kind:"sendRedeemPositionsTransaction",request:e}}async function*ade(e,t){let[n,...r]=t;ge(n!==void 0,"Expected at least one redemption call");let o=n;for(let s of r)await bn(yield IN(Qn(e.environment.chainId,o))).wait(),o=s;return bn(yield IN(Qn(e.environment.chainId,o)))}async function DO(e,t){let n=t.conditionId!==void 0?`condition ${t.conditionId}`:`market ${t.marketId}`,r=await Uf(e,t.conditionId!==void 0?{conditionIds:[t.conditionId],closed:t.closed,pageSize:1}:{ids:[lde(t.marketId)],closed:t.closed,pageSize:1}).firstPage(),[o]=r.items;if(o===void 0)throw new E(`No market found for ${n}`);let s=nde(o,n);return s.protocol==="v2"?{...s,positionErc1155Address:e.environment.contracts.positionManager}:{...s,adapterAddress:s.negRisk?e.environment.contracts.negRiskCollateralAdapter:e.environment.contracts.collateralAdapter,positionErc1155Address:s.negRisk?e.environment.contracts.negRiskAdapter:e.environment.contracts.conditionalTokens}}function lde(e){let t=Number(e);if(!Number.isInteger(t))throw new E(`Market ID must be an integer, received ${e}`);return t}async function cde(e,t){if(t.protocol==="ctf")return[WN(t.adapterAddress,e.environment.contracts.collateralToken,t.conditionId)];let n=Rf(await e.rpc.ethCall(Ef(t.positionErc1155Address,e.account.wallet,t.outcomeIds)));if(n.length!==2)throw new C("Expected two position balances");let[r,o]=n;ge(r!==void 0,"Expected YES position balance"),ge(o!==void 0,"Expected NO position balance");let s=[];if(r>0n&&s.push(wf(e.environment.contracts.protocolV2Router,t.conditionId,0,r)),o>0n&&s.push(wf(e.environment.contracts.protocolV2Router,t.conditionId,1,o)),s.length===0)throw new E(`Market positions have no balance to redeem for condition ${t.conditionId}`);return s}function fV(e,t,n){let r=ude(t);if(r===0n)throw new E(`You have no complementary positions to merge for condition ${e}`);if(n==="max")return r;if(n>r)throw new E(`Requested merge amount ${n} exceeds the maximum mergeable amount ${r} for condition ${e}`);return n}function ude(e){if(e.length!==2)throw new C("Expected two position balances");let[t,n]=e;return ge(t!==void 0,"Expected YES position balance"),ge(n!==void 0,"Expected NO position balance"),t<n?t:n}async function kA(e,t){let n=F(t,dde);return X(e.gamma.get("/public-profile",{params:ve(n,Ee())}).andThen(z(K3)).orElse(r=>r instanceof O&&r.status===404?go(null):Sr(r)))}async function PA(e){return Yf(e),e.webSockets.rfqQuoter.connect()}function BO(e){return e instanceof O?new ms(e.message,{cause:e,code:gV(e.code),status:e.status}):e}function gV(e){return e!==void 0&&wde.has(e)?e:li.RequestFailed}function yV(e){if(!e.hasBuilderApiKey)throw new E("Combo RFQ requests require a Builder API Key in the client configuration, via builderApiKey(...) or remoteBuilderSigning(...).")}function vde(e,t){return BigInt(e)*1000000n+BigInt(t.padEnd(6,"0"))}async function RA(e,t){Yf(e);let n=F(t,kde);yV(e);let r=oc(e.account),o={direction:n.direction===Ue.BUY?Nn.Buy:Nn.Sell,leg_position_ids:n.legPositionIds,maker_address:r.maker,requested_size:n.direction===Ue.BUY?{unit:Qr.Notional,value_e6:n.amount}:{unit:Qr.Shares,value_e6:n.size},side:Eo.Yes,signature_type:r.signatureType,signer_address:r.signer},s=await X(e.builderGateway.post(UO,{json:o,timeout:pde}).andThen(z(g4)).mapErr(BO));if("quote"in s){xde(s,o);let i=s.request.direction===Nn.Buy?Ue.BUY:Ue.SELL,a={blendedPrice:s.quote.blendedPrice,builderCode:s.builderCode,expiresAt:s.expiresAt,makerAmount:s.quote.makerAmount,positionId:s.request.yesPositionId,quoteId:s.quote.quoteId,rfqId:s.rfqId,takerAmount:s.quote.takerAmount,totalRequired:s.quote.totalRequired};if(i===Ue.SELL){if(s.quote.netReceive===void 0)throw new C(`SELL quote for RFQ ${s.rfqId} omitted net sell proceeds.`);return{quote:{...a,direction:i,netReceive:s.quote.netReceive},rfqId:s.rfqId}}return{quote:{...a,direction:i},rfqId:s.rfqId}}return Ade(s)}function xde(e,t){let n=e.request,r=[];if(n.rfqId!==e.rfqId&&r.push("rfq_id"),n.direction!==t.direction&&r.push("direction"),n.side!==t.side&&r.push("side"),(n.legPositionIds.length!==t.leg_position_ids.length||n.legPositionIds.some((o,s)=>o!==t.leg_position_ids[s]))&&r.push("leg_position_ids"),(n.requestedSize.unit!==t.requested_size.unit||n.requestedSize.valueE6!==t.requested_size.value_e6)&&r.push("requested_size"),r.length>0)throw new C(`Builder RFQ response did not echo the submitted ${r.join(", ")}.`)}function Ade(e){switch(e.error?.code){case Cr.NoQuotes:return{quote:null,reason:ci.NoQuotes,rfqId:e.rfqId};case Cr.SizeTooLarge:return{quote:null,reason:ci.SizeTooLarge,rfqId:e.rfqId};default:throw new ms(e.error?.message??"The combo quote request failed.",{code:gV(e.error?.code),status:200,...e.error===void 0?{}:{cause:e.error}})}}async function _A(e,t){Yf(e);let n=F(t,Sde);yV(e);let r=gO({chainId:e.environment.chainId,exchange:e.environment.contracts.exchangeV3}),o=Rde(e,n),s=await _de(e,r,o),i={quote_id:n.quoteId,signed_order:s};function a(){return e.builderGateway.post(`${UO}/${encodeURIComponent(n.rfqId)}/accept`,{json:i,timeout:mde}).andThen(z(eN))}let l=await a();if(l.isErr()&&(l.error instanceof _||l.error instanceof C)&&(l=await a()),l.isErr()){let p=Pde(n.rfqId,l.error);if(p!==void 0)return p;throw BO(l.error)}let c=l.value,u=l.value.takerOrderHash,d=Date.now()+hde;for(;c.status===mn.AwaitingMakerConfirmation;){if(Date.now()>=d)throw new tt(`Timed out waiting for the acceptance outcome of RFQ ${n.rfqId}.`);await ns(fde),c=await LA(e,{rfqId:n.rfqId})}return c.status===mn.Failed||c.status===mn.Expired||c.status===mn.Canceled?{reason:Ede(c.status,c.error?.code),rfqId:c.rfqId,status:"failed",...c.error===void 0?{}:{error:c.error}}:{rfqId:c.rfqId,status:"executing",...u===void 0?{}:{takerOrderHash:u}}}function Pde(e,t){if(t instanceof O&&t.code===Cr.ExpiredRfq)return{error:{code:Cr.ExpiredRfq,message:t.message},reason:Ro.AcceptanceWindowExpired,rfqId:e,status:"failed"}}function Ede(e,t){return e===mn.Expired||t===Cr.ExpiredRfq?Ro.AcceptanceWindowExpired:t===Cr.MakerDeclined?Ro.MakerDeclined:Ro.ExecutionFailed}function Rde(e,t){let n=oc(e.account);return{builder:t.builderCode,maker:n.maker,makerAmount:t.makerAmount,metadata:bde,salt:Ide().toString(),side:ix(t.direction),signatureType:n.signatureType,signer:n.signer,takerAmount:t.takerAmount,timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.positionId}}function Ide(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)}async function _de(e,t,n){let r;try{r=await e.signer.signTypedData(ox({domain:t,order:n}))}catch(o){throw o instanceof bt?o:ue.fromError(o,"Could not sign the combo quote acceptance order.")}return{...n,signature:sx({domain:t,order:n,signature:r})}}async function NA(e,t){Yf(e);let n=F(t,Cde),r=n.timeoutMs??gde,o=n.pollingIntervalMs??yde,s=Date.now()+r;for(;;){let i=await LA(e,{rfqId:n.rfqId});if(i.status===mn.Filled||i.status===us.Confirmed){if(i.txHash===void 0)throw new C(`RFQ ${i.rfqId} reached ${i.status} without a transaction hash.`);return{rfqId:i.rfqId,status:mn.Filled,txHash:i.txHash}}if(i.status===mn.Failed||i.status===mn.Expired||i.status===mn.Canceled)return{rfqId:i.rfqId,status:i.status,...i.error===void 0?{}:{error:i.error}};if(Date.now()>=s)throw new tt(`Timed out after ${r}ms waiting for RFQ ${n.rfqId} to reach a terminal state.`);await ns(o)}}function LA(e,t){Yf(e);let n=F(t,Nde);return X(e.builderGateway.get(`${UO}/${encodeURIComponent(n.rfqId)}`).andThen(z(eN)).mapErr(BO))}function Yf(e){if(e.account.signerType==="SESSION_KEY")throw new E("Combos is not supported with Session Keys")}function UA(e,t){let{cursor:n,pageSize:r,...o}=F(t,Ode);return Fe(s=>{let i=Md(s,r,{maxOffset:b6});return e.gamma.get("/public-search",{params:ve({...o,limitPerType:i.pageSize,page:i.offset},Ee({excludeTagIds:"exclude_tag_id"}))}).andThen(z(Y3)).map(a=>({items:Lde(a),hasMore:a.pagination?.hasMore??!1,limitReached:(a.pagination?.hasMore??!1)&&i.offset+1>b6,totalCount:a.pagination?.totalResults??void 0,nextCursor:a.pagination?.hasMore?aa({offset:i.offset+1,pageSize:i.pageSize}):void 0}))},n??aa({offset:1,pageSize:r}),{events:[],profiles:[],tags:[]})}function Lde(e){return{events:e.events??[],profiles:e.profiles??[],tags:e.tags??[]}}function MA(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,Dde);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/series",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(z(X3)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?aa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function qA(e,t){let n=F(t,Ude);return X(e.gamma.get(`series/${n.id}`,{params:ve({locale:n.locale},Ee())}).andThen(z(UC)))}function bV(e){if(e.kind==="authorization"?e.status===Od.FAILED||e.status===Od.SUPERSEDED||e.status===Od.REPAIR_REQUIRED:e.status===f0.FAILED)throw new en(`Session-key ${e.kind} reached terminal status ${e.status}`)}async function Wd(e){MO(e);let t=await X(e.secureClob.get("/v1/user/session-signers").andThen(z(z3)));if(!Wt(t.wallet,e.account.wallet))throw new C(`Session-key response wallet ${t.wallet} does not match authenticated wallet ${e.account.wallet}`);return t.signers.map(n=>({address:Be(n.address.toLowerCase()),scopes:n.scopes,validUntil:n.validUntil}))}async function VA(e,t){if(MO(e),!e.hasBuilderApiKey)throw new E("Session-key authorization requires builder API-key authentication.");let n=F(t,Fde),r=Math.floor(Date.now()/1e3)+Mde,o=await wn(e.signer)(qd(e,[HN(e.account.wallet,n.address,BigInt(r))])),s={deadline:o.depositWalletParams.deadline,nonce:o.nonce,scopes:n.scopes,sessionSignerAddress:n.address,signature:o.signature,validUntil:`${r}`,walletAddress:e.account.wallet},i=await X(e.relayer.post("/v1/session-signers/authorizations",{headers:{"Idempotency-Key":n.idempotencyKey??globalThis.crypto.randomUUID()},json:s,timeout:wV}).andThen(z(s4)));bV({kind:"authorization",status:i.status});let a=await new Cf(e,i).wait();return{sessionKey:await $de(e,{address:n.address,scopes:n.scopes,validUntil:r}),transaction:a}}async function zA(e,t){if(MO(e),!e.supportsGasless)throw new E("Session-key revocation requires API-key authentication that supports gasless transactions.");let n=F(t,qde),r=await wn(e.signer)(qd(e,[$N(e.account.wallet,n.address)])),o={deadline:r.depositWalletParams.deadline,nonce:r.nonce,sessionSignerAddress:n.address,signature:r.signature,walletAddress:e.account.wallet},s=await X(e.relayer.post("/v1/session-signers/revocations",{headers:{"Idempotency-Key":n.idempotencyKey??globalThis.crypto.randomUUID()},json:o,timeout:wV}).andThen(z(i4)));bV({kind:"revocation",status:s.status}),await Hde(e,n.address)}async function Hde(e,t){for(let n=0;n<e.environment.relayerMaxPolls;n+=1){if(!(await Wd(e)).some(r=>Wt(r.address,t)))return;await ns(e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for session key ${t} to be revoked`)}async function $de(e,t){for(let n=0;n<e.environment.relayerMaxPolls;n+=1){let r=(await Wd(e)).find(o=>Wt(o.address,t.address)&&o.validUntil===t.validUntil&&Vde(o.scopes,t.scopes));if(r!==void 0)return r;await ns(e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for session key ${t.address} to become active`)}function Vde(e,t){let n=new Set(t);return new Set(e).size===n.size&&e.every(r=>n.has(r))}function MO(e){if(e.account.walletType!==Se.DEPOSIT_WALLET)throw new E("Session keys can only be managed for a Deposit Wallet.");if(e.account.signerType!=="OWNER")throw new E("Session keys can only be managed by the Deposit Wallet owner.")}async function GA(e){return X(e.gamma.get("/sports").andThen(z(g_)))}async function YA(e){return X(e.gamma.get("/sports/market-types").andThen(z(y_)))}function Wde(e){return F(e,zde)}async function Qf(e,t){let n=t.map(i=>{switch(F(i,Gde),i.topic){case"prices.crypto":case"prices.crypto.twap":case"prices.equity":if(!e.isSecureClient())throw new E("This subscription requires a secure client.");return Wde(i);case"prices.crypto.chainlink.twap":F(i,Kde);break;case"market":F(i,Yde);break}return i}),r=await Promise.allSettled(n.map(async i=>Qde(e,i))),o=r.flatMap(i=>i.status==="fulfilled"?[i.value]:[]),s=r.find(i=>i.status==="rejected");if(s?.status==="rejected")throw await Promise.allSettled(o.map(i=>i.close())),s.reason;return Xde(o)}function Qde(e,t){switch(t.topic){case"market":return e.webSockets.clobMarket.subscribe(t);case"sports":return e.webSockets.sports.subscribe(t);case"prices.crypto":case"prices.crypto.twap":case"prices.equity":if(!e.isSecureClient())throw new E("This subscription requires a secure client.");return e.webSockets.realtime.subscribe(t);case"comments":case"prices.crypto.binance":case"prices.crypto.chainlink":case"prices.crypto.chainlink.twap":case"prices.equity.pyth":return e.webSockets.rtds.subscribe(t);case"perps.trades":case"perps.bbo":case"perps.book":case"perps.candles":case"perps.tickers":case"perps.statistics":return e.webSockets.perpsSubscriptions.subscribe(t);case"user":return ge(e.isSecureClient(),"A 'user' subscription requires a secure client instance."),e.webSockets.clobUser.subscribe(t)}}function Xde(e){let t;async function n(){t===void 0&&(t=Promise.all(e.map(o=>o.close())).then(()=>{})),await t}let r=V4(...e);return{close:n,[Symbol.asyncIterator](){return r[Symbol.asyncIterator]()}}}function JA(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,Jde);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/tags",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(z(Q3)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?aa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function eT(e,t){let n=F(t,Zde);return"id"in n?X(e.gamma.get(`tags/${n.id}`,{params:ve({includeTemplate:n.includeTemplate,locale:n.locale},Ee())}).andThen(z(Id))):X(e.gamma.get(`tags/slug/${n.slug}`,{params:ve({locale:n.locale},Ee())}).andThen(z(Id)))}async function nT(e,t){if("id"in t){let r=F(t,epe);return X(e.gamma.get(`tags/${r.id}/related-tags`,{params:ve({omitEmpty:r.omitEmpty,status:r.status},Ee())}).andThen(z(LC)))}let n=F(t,tpe);return X(e.gamma.get(`tags/slug/${n.slug}/related-tags`).andThen(z(LC)))}async function oT(e,t){if("id"in t){let r=F(t,npe);return X(e.gamma.get(`tags/${r.id}/related-tags/tags`,{params:ve({locale:r.locale,omitEmpty:r.omitEmpty,status:r.status},Ee())}).andThen(z(DC)))}let n=F(t,rpe);return X(e.gamma.get(`tags/slug/${n.slug}/related-tags/tags`,{params:ve({locale:n.locale,omitEmpty:n.omitEmpty,status:n.status},Ee())}).andThen(z(DC)))}function iT(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,ope);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/teams",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee({providerId:"provider_id"}))}).andThen(z(f_)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?aa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function FO(e,t){let n=F(t,spe);return async function*(){return e.account.walletType===Se.EOA?bn(yield ipe(Qn(e.environment.chainId,S0(n.tokenAddress,n.recipientAddress,n.amount)))):yield*await Or(e,{calls:[S0(n.tokenAddress,n.recipientAddress,n.amount)],metadata:n.metadata??`Transfer ${n.amount} of ${n.tokenAddress} to ${n.recipientAddress}`})}.call(null)}function lT(e,t){return FO(e,t).then(wn(e.signer))}function ipe(e){return{kind:"sendErc20TransferTransaction",request:e}}var h,Ot,x6,Ere,_N,CN,Ore,Lre,Ure,qre,Hre,$re,Vre,jre,zre,Wre,Gre,C6,gf,L0,N6,D0,ooe,soe,B0,ioe,F0,aoe,loe,H0,$0,coe,j0,L6,uoe,D6,doe,U6,poe,G0,moe,Y0,B6,X0,Z0,hoe,tv,rv,foe,sv,goe,av,yoe,lv,boe,woe,voe,LN,koe,M6,xoe,Aoe,Toe,Soe,Poe,F6,q6,H6,Eoe,Roe,Ioe,_oe,Coe,Noe,Ooe,Loe,Doe,$6,Uoe,lr,V6,j6,z6,W6,G6,K6,Y6,Q6,X6,J6,Z6,zoe,Woe,Goe,Koe,Yoe,Qoe,Xoe,Joe,t8,Zoe,ese,n8,ur,K4,r8,nse,rse,o8,c8,Cf,pse,u8,bv,mse,d8,wv,p8,hse,vv,kv,g8,y8,b8,w8,v8,k8,A8,S8,gse,yse,Pv,bse,Rv,wse,_v,vse,R8,kse,_8,xse,N8,Ase,O8,Tse,L8,Sse,Nv,Pse,Lv,Ese,Uv,Rse,Bv,Ise,Fv,_se,Hv,Cse,Vv,Nse,zv,Ose,Gv,Lse,Yv,D8,Jv,Use,Y4,uN,U8,ek,aO,lO,M8,Mse,Fse,qse,nk,Hse,ok,ik,Vse,jse,zse,lk,uk,pk,Gse,Kse,Yse,hk,Qse,gk,eie,bk,tie,vk,cO,nie,xk,rie,Tk,oie,Sk,sie,q8,iie,aie,lie,cie,uie,die,Rk,pie,Ik,Ck,Ok,mie,Dk,hie,fie,yN,H8,$8,gie,yie,bie,wie,Bk,vie,Fk,Sie,Pie,Eie,Rie,Hk,Vk,zk,Gk,kf,xf,V8,e6,t6,Iie,Qk,Oie,Lie,j8,Die,Zk,ex,W8,Bie,Mie,G8,n6,Fie,qie,rc,$ie,dN,Vie,pN,vN,Kie,o6,Qie,s6,Xie,t5,a6,l6,tae,i5,aae,lae,xN,AN,cae,uae,dae,a5,l5,pae,p6,yO,bO,b5,v5,bae,wae,vae,kae,ux,px,mx,fx,gx,vO,Iae,_ae,bx,Cae,P5,vx,vn,Mae,Fae,qae,Hae,$ae,Vae,jae,kO,E5,R5,xO,I5,zae,Wae,Gae,ua,mi,P0,AO,cr,kx,_5,Xae,Jae,TO,C5,rle,sle,ale,lle,ule,ple,mle,hle,gle,yle,ble,vle,kle,xle,Tle,Sle,Ple,Ele,Ile,_le,Cle,Ole,Lle,Dle,Ble,Mle,Fle,qle,Vle,jle,zle,Qle,Ax,Jle,mN,L5,Tx,Sx,PO,tce,nce,rce,EO,A0,T0,oce,sce,ace,lce,D5,pce,mce,TN,SN,fce,gce,yce,E0,bce,vce,Sce,Ece,Rce,Px,Ice,Cce,Oce,Ex,Dce,Rx,$ce,hN,Vce,jce,zce,Wce,fN,Ix,M5,ic,ds,F5,Xce,_x,Jce,Nx,Zce,Lx,eue,tue,Dx,nue,rue,oue,Bx,q5,sue,iue,aue,lue,cue,Fx,uue,Hx,Vx,due,pue,mue,Aue,Tue,Sue,Pue,Eue,Rue,Iue,_ue,$5,Cue,Nue,Oue,Lue,Due,zx,Wx,V5,Gx,Kx,Yx,Gue,tA,Kue,Yue,Que,nA,Xue,rA,Jue,oA,Zue,sA,ede,iA,tde,aA,lA,G5,K5,Y5,Q5,rde,Vd,X5,Z5,pA,tV,nV,rV,oV,ode,jd,sV,aV,gA,cV,uV,sde,dV,pV,mV,ide,bA,dde,vA,ac,xA,lc,AA,cc,TA,SA,UO,pde,mde,hde,fde,gde,yde,bde,ms,wde,y6,C0,kde,EA,Tde,Sde,IA,Cde,CA,Nde,OA,zd,b6,Ode,DA,Dde,Ude,BA,FA,HA,Bde,Mde,wV,Fde,$A,qde,jA,WA,KA,jde,w6,vV,zde,QA,kV,Gde,Kde,Yde,Jde,Zde,epe,tpe,npe,rpe,XA,ZA,tT,rT,ope,sT,spe,xV,aT,cT=L(()=>{"use strict";Zw();cf();cf();OC();Tl();h=require("zod");o0();hw();P$();h0();h0();p4();g0();g0();rN();U4();Qw();lN();j4();Ot=h.z.number().int().positive();x6=h.z.strictObject({offset:h.z.number().int().min(0),pageSize:Ot});Ere=h.z.object({kind:h.z.literal("keyset"),fingerprint:h.z.string(),cursor:h.z.string().min(1)});_N=class{#e;constructor({url:e}){this.#e=e}async ethCall(e){let t=await this.#s({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.to,data:e.data},"latest"]});if("error"in t)throw new O(`JSON-RPC eth_call failed: ${t.error.message}`,{cause:t.error,status:200});if(typeof t.result!="string")throw new C("Expected JSON-RPC eth_call result to be a hex string");if(!I6(t.result))throw new C("Expected JSON-RPC eth_call result to be a hex string");return t.result}async ethCallBatch(e){return e.length===0?[]:this.#t(e)}async ethEstimateGas(e){let t={to:e.to};e.data!==void 0&&(t.data=e.data),e.from!==void 0&&(t.from=e.from),e.gasPrice!==void 0&&(t.gasPrice=G4(e.gasPrice)),e.value!==void 0&&(t.value=G4(e.value));let n=await this.#s({jsonrpc:"2.0",id:1,method:"eth_estimateGas",params:[t]});if("error"in n)throw new O(`JSON-RPC eth_estimateGas failed: ${n.error.message}`,{cause:n.error,status:200});return BigInt(W4(n.result,"eth_estimateGas"))}async#t(e){if(e.length===1)return[await this.ethCall(e[0])];try{return await this.#r(e)}catch(t){if(!(t instanceof O)||t.status<500)throw t;let n=Math.ceil(e.length/2),[r,o]=await Promise.all([this.#t(e.slice(0,n)),this.#t(e.slice(n))]);return[...r,...o]}}async#r(e){let t=await this.#n(e.map((r,o)=>({jsonrpc:"2.0",id:o+1,method:"eth_call",params:[{to:r.to,data:r.data},"latest"]}))),n=new Map;for(let r of t){if("error"in r&&r.id===null)throw new O(`JSON-RPC eth_call failed: ${r.error.message}`,{cause:r.error,status:200});r.id!==null&&n.set(r.id,r)}return e.map((r,o)=>{let s=o+1,i=n.get(s);if(i===void 0)throw new C("Expected JSON-RPC batch response for every request");if("error"in i)throw new O(`JSON-RPC eth_call failed: ${i.error.message}`,{cause:i.error,status:200});return W4(i.result)})}async#s(e){let t;try{t=await u0.post(this.#e,{json:e,throwHttpErrors:!1})}catch(r){throw _.fromError(r)}if(!t.ok)throw new O(`JSON-RPC request to ${this.#e} failed with status ${t.status}`,{status:t.status});let n;try{n=await t.json()}catch(r){throw new C("Expected JSON-RPC response body to be JSON",{cause:r})}if(!z4(n))throw new C("Unexpected JSON-RPC response shape");return n}async#n(e){let t;try{t=await u0.post(this.#e,{json:e,throwHttpErrors:!1})}catch(r){throw _.fromError(r)}if(!t.ok)throw new O(`JSON-RPC request to ${this.#e} failed with status ${t.status}`,{status:t.status});let n;try{n=await t.json()}catch(r){throw new C("Expected JSON-RPC response body to be JSON",{cause:r})}if(!Array.isArray(n)||!n.every(r=>z4(r)))throw new C("Unexpected JSON-RPC response shape");return n}};CN=(e=>(e.OWNER="OWNER",e.SESSION_KEY="SESSION_KEY",e))(CN||{}),Ore="0x0000000000000000000000000000000000000000000000000000000000000000",Lre="0x6492649264926492649264926492649264926492649264926492649264926492";Ure="3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000";qre="0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",Hre="0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",$re=0x61003d3d8160233d3973n;Vre="0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",jre="0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",zre="0x60195155f3363d3d373d3d363d602036600436635c60da",Wre=0x6100523d8160233d3973n,Gre="0x49493a4d";C6=h.z.string().transform(e=>e);gf=h.z.union([h.z.number().int().min(0),h.z.date()]).transform(e=>e instanceof Date?Math.floor(e.getTime()/1e3):e),L0=h.z.union([h.z.literal("full"),h.z.object({start:gf.optional(),end:gf.optional()}).refine(e=>!e.end||e.end>=(e.start??0),"end must not precede start")]).transform(e=>e==="full"?{start:1}:e),N6=Gt.refine(e=>/^[1-9]\d*$/.test(e)&&BigInt(e)<=2147483647n,"Expected a positive 32-bit event ID");D0=B($,O,ue,_,C);ooe=h.z.object({cursor:ye.optional(),id:h.z.string().optional(),market:h.z.string().optional()}),soe=Fd(ooe.shape).default({}),B0=B($,O,ue,_,C,E);ioe=h.z.object({orderId:h.z.string()}),F0=B($,O,ue,_,C,E);aoe={after:h.z.string().optional(),before:h.z.string().optional(),cursor:ye.optional(),id:h.z.string().optional(),makerAddress:h.z.string().optional(),market:h.z.string().optional()},loe=Fd(aoe).default({}),H0=B($,O,ue,_,C,E);$0=B($,O,ue,_,C),coe=h.z.object({ids:h.z.array(h.z.string()).min(1)});j0=B($,O,ue,_,C,E);L6=h.z.object({assetType:p3}),uoe=Fd(L6.shape),D6=B($,O,ue,_,C,E);doe=Fd(L6.shape),U6=B($,O,ue,_,C,E);poe=h.z.object({orderId:h.z.string()}),G0=B($,O,ue,_,C,E);moe=h.z.object({orderIds:h.z.array(h.z.string())}),Y0=B($,O,ue,_,C,E);B6=h.z.object({cursor:ye.optional(),date:h.z.string()}),X0=B($,O,ue,_,C,E);Z0=B($,O,ue,_,C,E);hoe=h.z.object({cursor:ye.optional(),date:h.z.string(),noCompetition:h.z.boolean().optional(),orderBy:h.z.string().optional(),pageSize:Ot.max(500).default(100),position:h.z.string().optional()}),tv=B($,O,ue,_,C,E);rv=B($,O,ue,_,C);foe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J.optional(),takerOnly:h.z.boolean().optional(),filterType:I$.optional(),filterAmount:h.z.number().min(0).optional(),conditionId:h.z.union([xe,ca(xe,20)]).optional(),eventId:h.z.array(Gt).min(1).optional(),side:Nt.optional(),window:L0.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),sv=B($,O,_,C,E);goe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([xe,ca(xe,20)]).optional(),eventId:h.z.array(Gt).min(1).optional(),type:h.z.array(KC).min(1).optional(),side:Nt.optional(),sortDirection:m0.optional(),window:L0.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),av=B($,O,_,C,E);yoe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([Zt,ca(Zt,20)]).optional()}),lv=B($,O,_,C,E);boe=64,woe=/^0x[0-9a-fA-F]{62}$/,voe=/^0x[0-9a-fA-F]{64}$/,LN="0x0000000000000000000000000000000000000000000000000000000000000000",koe=_e.from("function approve(address spender, uint256 amount)"),M6=_e.from("function allowance(address owner, address spender) view returns (uint256)"),xoe=_e.from("function transfer(address recipient, uint256 amount)"),Aoe=_e.from("function authorizeSessionSigner(address sessionSigner, uint256 validUntil)"),Toe=_e.from("function revokeSessionSigner(address sessionSigner)"),Soe=_e.from("function deposit(address token, uint256 amount, address to)"),Poe=_e.from("function setApprovalForAll(address operator, bool approved)"),F6=_e.from("function isApprovedForAll(address account, address operator) view returns (bool)"),q6=_e.from("function balanceOf(address account, uint256 id) view returns (uint256)"),H6=_e.from("function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])"),Eoe=_e.from("function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Roe=_e.from("function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Ioe=_e.from("function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)"),_oe=_e.from("function split(bytes31 conditionId, uint256 amount)"),Coe=_e.from("function merge(bytes31 conditionId, uint256 amount)"),Noe=_e.from("function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)"),Ooe=_e.from("function prepareCondition(uint256[] legs) returns (bytes31)"),Loe=_e.from("function multiSend(bytes)"),Doe=_e.from("function proxy((uint8 typeCode, address to, uint256 value, bytes data)[] calls) returns (bytes[])"),$6=[1n,2n],Uoe=[1n,2n],lr=(1n<<256n)-1n,V6=B(E);j6=B(E);z6=B(E);W6=B(E);G6=B(E);K6=B(E);Y6=B(E);Q6=B(E);X6=B(E);J6=B(E);Z6=B($,O,tt,en,_,C,E);B(bt,ue);B(bt,ue);zoe=[{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Woe=[{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"},{name:"operation",type:"uint8"},{name:"safeTxGas",type:"uint256"},{name:"baseGas",type:"uint256"},{name:"gasPrice",type:"uint256"},{name:"gasToken",type:"address"},{name:"refundReceiver",type:"address"},{name:"nonce",type:"uint256"}],Goe="DepositWallet",Koe="1",Yoe=600,Qoe=[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],Xoe=[{name:"wallet",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"calls",type:"Call[]"}],Joe=h.z.object({address:h.z.string(),type:h.z.enum(_r)}),t8=B($,O,_,C,E);Zoe=h.z.object({transactionId:ea}),ese=h.z.object({wallet:J,type:h.z.enum(Se)}),n8=B($,O,_,C,E);ur=h.z.string().max(500),K4=10,r8=B($,O,_,C,E);nse=h.z.object({data:h.z.custom(ln),to:J,value:h.z.bigint().optional()}),rse=h.z.object({calls:h.z.array(nse).min(1).transform(e=>XF(e)),metadata:ur}),o8=B($,O,_,C,E);c8=B($,O,_,C,E,tt,en),Cf=class{#e;transactionHash;transactionId;constructor(e,t){this.#e=e,this.transactionHash=t.transactionHash,this.transactionId=t.transactionId}async wait(){let e=0;for(;e<this.#e.environment.relayerMaxPolls;){let t=await XN(this.#e,{transactionId:this.transactionId});if(t.state===Ld.STATE_CONFIRMED){let n=t.transactionHash??this.transactionHash;if(n===null)throw new C("Expected submitted transaction to have a transaction hash once settled");return{transactionHash:n,transactionId:t.transactionId}}if(t.state===Ld.STATE_FAILED||t.state===Ld.STATE_INVALID)throw new en(t.errorMsg??`Transaction ${t.transactionId} reached terminal state ${t.state}`);e+=1,await ns(this.#e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for transaction ${this.transactionId} to settle`)}},pse=h.z.object({amount:h.z.union([h.z.bigint(),h.z.literal("max")]),metadata:ur.optional(),spenderAddress:J,tokenAddress:J}),u8=B(E);bv=B(bt,$,O,ue,_,C,E);mse=h.z.object({approved:h.z.boolean().default(!0),metadata:ur.optional(),operatorAddress:J,tokenAddress:J}),d8=B(E);wv=B(bt,$,O,ue,_,C,E);p8=B(O,_,C,E),hse=h.z.object({user:J}),vv=B(O,_,C,E);kv=B(bt,$,O,ue,tt,en,_,C,E);g8=B($,O,_,C);y8=B($,O,_,C);b8=B($,O,_,C);w8=B($,O,ue,_,C);v8=B($,O,ue,_,C);k8=B($,O,ue,_,C);A8=B($,O,ue,_,C);S8=B($,O,ue,_,C);gse=h.z.object({after:h.z.string().optional(),before:h.z.string().optional(),builderCode:bo,cursor:ye.optional(),id:h.z.string().optional(),market:h.z.string().optional()}),yse=Fd(gse.shape),Pv=B($,O,_,C,E);bse=Nr({}),Rv=B($,O,_,C,E);wse=h.z.array(Nr({})).min(1),_v=B($,O,_,C,E);vse=Nr({}),R8=B($,O,_,C,E);kse=Nr({}),_8=B($,O,_,C,E);xse=Nr({}),N8=B($,O,_,C,E);Ase=h.z.object({conditionId:xe}),O8=B($,O,_,C,E);Tse=h.z.object({builderCode:bo}),L8=B($,O,_,C,E);Sse=Nr({side:Nt}),Nv=B($,O,_,C,E);Pse=h.z.array(Nr({side:Nt})).min(1),Lv=B($,O,_,C,E);Ese=Nr({}),Uv=B($,O,_,C,E);Rse=h.z.array(Nr({})).min(1),Bv=B($,O,_,C,E);Ise=Nr({}),Fv=B($,O,_,C,E);_se=h.z.array(Nr({})).min(1),Hv=B($,O,_,C,E);Cse=Nr({}),Vv=B($,O,_,C,E);Nse=h.z.array(Nr({})).min(1),zv=B($,O,_,C,E);Ose=h.z.object({cursor:ye.optional(),sponsored:h.z.boolean().optional()}).default({}),Gv=B($,O,_,C,E);Lse=h.z.object({conditionId:xe,cursor:ye.optional(),sponsored:h.z.boolean().optional()}),Yv=B($,O,_,C,E);D8=2*6e4,Jv=B($,O,_,C);Use=h.z.object({plan:b4}),Y4=10,uN="Collateral return",U8=B(O,_,C,E);ek=B(bt,$,O,ue,_,C,E);aO=100,lO=200,M8={maxOffset:lO,maxPageSize:aO},Mse=h.z.object({ascending:h.z.boolean().optional(),cursor:ye.optional(),pageSize:Ot.max(aO).default(20),getPositions:h.z.boolean().optional(),holdersOnly:h.z.boolean().optional(),order:h.z.string().optional(),parentEntityId:h.z.union([Gt,Mh]),parentEntityType:Js}),Fse=h.z.object({getPositions:h.z.boolean().optional(),id:Xs}),qse=h.z.object({address:h.z.string(),ascending:h.z.boolean().optional(),cursor:ye.optional(),order:h.z.string().optional(),pageSize:Ot.max(aO).default(20)}),nk=B(Ol,$,O,_,C,E),Hse=h.z.enum(["id","createdAt"]);ok=B($,O,_,C,E);ik=B(Ol,$,O,_,C,E);Vse=h.z.object({ascending:h.z.boolean().optional(),closed:h.z.boolean().default(!1),cursor:ye.optional(),pageSize:Ot.optional(),cyom:h.z.boolean().optional(),endDateMax:oe.optional(),endDateMin:oe.optional(),ended:h.z.boolean().optional(),eventDate:Wn.optional(),eventWeek:h.z.number().int().optional(),excludeTagIds:h.z.array(h.z.number().int()).optional(),featured:h.z.boolean().optional(),featuredOrder:h.z.boolean().optional(),gameIds:h.z.array(h.z.number().int()).optional(),ids:h.z.array(h.z.number().int()).optional(),includeBestLines:h.z.boolean().optional(),includeChat:h.z.boolean().optional(),includeChildren:h.z.boolean().optional(),includeTemplate:h.z.boolean().optional(),liquidityMax:h.z.number().optional(),liquidityMin:h.z.number().optional(),live:h.z.boolean().optional(),locale:h.z.string().optional(),order:h.z.string().optional(),parentEventId:h.z.number().int().optional(),partnerSlug:h.z.string().optional(),recurrence:h.z.enum(["daily","weekly","monthly"]).optional(),relatedTags:h.z.boolean().optional(),seriesIds:h.z.array(h.z.number().int()).optional(),slug:h.z.array(h.z.string()).optional(),startDateMax:oe.optional(),startDateMin:oe.optional(),startTimeMax:oe.optional(),startTimeMin:oe.optional(),tagIds:h.z.array(h.z.number().int()).optional(),tagMatch:h.z.enum(["any","all"]).optional(),tagSlug:h.z.string().optional(),titleSearch:h.z.string().optional(),volumeMax:h.z.number().optional(),volumeMin:h.z.number().optional()}),jse=h.z.union([h.z.object({id:h.z.string(),includeBestLines:h.z.boolean().optional(),includeChat:h.z.boolean().optional(),includeTemplate:h.z.boolean().optional(),locale:h.z.string().optional()}),h.z.object({slug:h.z.string(),includeBestLines:h.z.boolean().optional(),includeChat:h.z.boolean().optional(),includeTemplate:h.z.boolean().optional(),locale:h.z.string().optional()}),h.z.object({url:h.z.string(),includeBestLines:h.z.boolean().optional(),includeChat:h.z.boolean().optional(),includeTemplate:h.z.boolean().optional(),locale:h.z.string().optional()})]),zse=h.z.object({id:h.z.string()}),lk=B($,O,_,C,E);uk=B($,O,_,C,E);pk=B($,O,_,C,E);Gse=h.z.array(ql).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct condition ids"),Kse=h.z.array(N6).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct event ids"),Yse=h.z.union([h.z.object({questionId:vo,conditionIds:h.z.never().optional(),eventIds:h.z.never().optional()}),h.z.object({questionId:h.z.never().optional(),conditionIds:Gse,eventIds:h.z.never().optional()}),h.z.object({questionId:h.z.never().optional(),conditionIds:h.z.never().optional(),eventIds:Kse})]),hk=B($,O,_,C,E);Qse=h.z.object({eventIds:h.z.array(N6).min(1).transform(e=>[...new Set(e)])}),gk=B($,O,_,C,E);eie=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),window:ff.optional()}),bk=B($,O,_,C,E);tie=h.z.object({interval:X$.optional(),bucketLimit:h.z.number().int().positive().max(90).optional()}),vk=B($,O,_,C,E);cO=h.z.string().min(1),nie=h.z.object({category:cO.optional(),cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),sortBy:J$.optional(),window:ff.optional()}),xk=B($,O,_,C,E);rie=h.z.object({category:cO.optional(),user:J,window:ff.optional()}),Tk=B($,O,_,C,E);oie=h.z.object({category:cO.optional(),cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),window:ff.optional()}),Sk=B($,O,_,C,E);sie=h.z.object({marketId:h.z.union([h.z.string(),h.z.array(h.z.string())]).optional(),eventId:h.z.union([h.z.string(),h.z.array(h.z.string())]).optional(),questionId:h.z.union([h.z.string(),h.z.array(h.z.string())]).optional(),state:h.z.union([h.z.enum(uf),h.z.array(h.z.enum(uf))]).optional(),showInFrontend:h.z.boolean().optional(),txHash:h.z.string().optional(),order:h.z.string().optional(),ascending:h.z.boolean().optional(),cursor:ye.optional(),pageSize:Ot.max(100).default(20)}),q8=B($,O,_,C,E);iie=h.z.object({ascending:h.z.boolean().optional(),closed:h.z.boolean().optional(),clobTokenIds:h.z.array(h.z.string()).optional(),cursor:ye.optional(),pageSize:Ot.optional(),conditionIds:h.z.array(xe).optional(),cyom:h.z.boolean().optional(),decimalized:h.z.boolean().optional(),endDateMax:oe.optional(),endDateMin:oe.optional(),gameId:h.z.string().optional(),ids:h.z.array(h.z.number().int()).optional(),includeTag:h.z.boolean().optional(),liquidityNumMax:h.z.number().optional(),liquidityNumMin:h.z.number().optional(),locale:h.z.string().optional(),order:h.z.string().optional(),positionIds:h.z.array(Xe).optional(),questionIds:h.z.array(h.z.string()).optional(),relatedTags:h.z.boolean().optional(),rfqEnabled:h.z.boolean().optional(),rewardsMinSize:h.z.number().optional(),slug:h.z.array(h.z.string()).optional(),sportsMarketTypes:h.z.array(h.z.string()).optional(),startDateMax:oe.optional(),startDateMin:oe.optional(),tagId:h.z.number().int().optional(),tagMatch:h.z.enum(["any","all"]).optional(),umaResolutionStatus:h.z.string().optional(),volumeNumMax:h.z.number().optional(),volumeNumMin:h.z.number().optional()}),aie=h.z.object({id:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),lie=h.z.object({slug:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),cie=h.z.object({url:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),uie=h.z.union([aie,lie,cie]),die=h.z.object({id:h.z.string()}),Rk=B($,O,_,C,E);pie=h.z.object({cursor:ye.optional(),pageSize:Ot.max(100).optional(),exclude:h.z.array(xe).optional()}),Ik=B($,O,_,C,E);Ck=B($,O,_,C,E);Ok=B($,O,_,C,E);mie=h.z.object({conditionIds:ca(ql,20),cursor:ye.optional(),includePnl:h.z.boolean().optional(),minBalance:h.z.number().nonnegative().optional(),pageSize:Ot.max(1e3).default(100)}).superRefine(({conditionIds:e,includePnl:t,pageSize:n},r)=>{t&&(e.length!==1&&r.addIssue({code:"custom",message:"includePnl requires exactly one conditionId",path:["conditionIds"]}),n>100&&r.addIssue({code:"custom",message:"includePnl supports pageSize at most 100",path:["pageSize"]}))}),Dk=B($,O,_,C,E);hie=360*60*60,fie=253402300799,yN=gf.pipe(h.z.number().int().positive().max(fie)),H8=h.z.string().min(1).pipe(Me),$8={assetId:H8,bucketSeconds:h.z.number().int().min(60).max(86400).optional(),cursor:ye.optional(),pageSize:Ot.max(1e4).default(1e4)},gie=h.z.object({...$8,interval:W$,start:h.z.never().optional(),end:h.z.never().optional(),asOf:h.z.never().optional()}).superRefine(({bucketSeconds:e,interval:t},n)=>{let r=t===Po.Max||t===Po.OneMonth?600:t===Po.OneWeek?300:60;e!==void 0&&e<r&&n.addIssue({code:"custom",message:`bucketSeconds must be at least ${r} for this interval`,path:["bucketSeconds"]})}),yie=h.z.object({...$8,start:yN,end:yN.optional(),interval:h.z.never().optional(),asOf:h.z.never().optional()}).superRefine(({end:e,start:t},n)=>{if(e!==void 0&&e<t){n.addIssue({code:"custom",message:"end must not precede start",path:["end"]});return}(e??Math.floor(Date.now()/1e3))-t>hie&&n.addIssue({code:"custom",message:"start to end must span at most 15 days",path:["end"]})}),bie=h.z.object({assetId:H8,asOf:yN,interval:h.z.never().optional(),start:h.z.never().optional(),end:h.z.never().optional(),bucketSeconds:h.z.never().optional(),cursor:h.z.never().optional(),pageSize:h.z.never().optional()}),wie=h.z.union([gie,yie,bie]),Bk=B($,O,_,C,E);vie=h.z.object({conditionIds:ca(ql,20).optional()}),Fk=B($,O,_,C,E);Sie=h.z.object({orderId:h.z.string()}),Pie=h.z.object({orderIds:h.z.array(h.z.string()).min(1).max(3e3)}),Eie=h.z.object({market:h.z.string().optional()}),Rie=Fd(Eie.shape).refine(e=>e.market!==void 0||e.assetId!==void 0||e.tokenId!==void 0,{message:"At least one of market or assetId is required.",path:["market"]}),Hk=B(O,$,ue,_,C,E);Vk=B(O,$,ue,_,C,E);zk=B(O,$,ue,_,C);Gk=B(O,$,ue,_,C,E);kf=h.z.object({assetId:Me,tokenId:h.z.never().optional()}),xf=h.z.object({assetId:h.z.never().optional(),tokenId:Me}),V8=h.z.object({orderType:h.z.union([h.z.literal(cn.FAK),h.z.literal(cn.FOK)]).default(cn.FOK)}),e6=V8.extend({side:h.z.literal(Ue.BUY),amount:ko}),t6=V8.extend({side:h.z.literal(Ue.SELL),shares:ko}),Iie=h.z.union([e6.extend(kf.shape),e6.extend(xf.shape),t6.extend(kf.shape),t6.extend(xf.shape)]).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t})),Qk=B(So,$,O,_,C,E);Oie=BigInt(Number.MAX_SAFE_INTEGER),Lie=h.z.string().refine(Uie,{message:"Order salt must be a non-negative JavaScript-safe integer."}),j8=h.z.looseObject({salt:Lie}),Die=h.z.array(j8).min(1).max(15),Zk=B($,O,ue,_,C,E),ex=B($,O,ue,_,C,E);W8=32,Bie=1n,Mie=2n,G8=3n,n6=50,Fie=(1n<<256n)-1n,qie=(1n<<64n)-1n<<40n;rc=1000000n,$ie=8*Number.EPSILON,dN=6,Vie=8*Number.EPSILON;pN=600*1e3,vN=Number.POSITIVE_INFINITY,Kie=class{#e;#t=new Map;#r=new Map;#s=new Map;constructor(e){this.#e=e}async resolveMarket(e){let t=await this.#n(e);return{feeInfo:t.feeInfo,negRisk:t.negRisk,tickSize:t.tickSize}}async resolveBuilderTakerFeeRate(e){return e===void 0?0:x0(this.#t,e,pN,()=>this.#e.fetchBuilderTakerFeeRate(e))}async fetchCurrentMarket(e){let t=await x0(this.#r,e,vN,()=>this.#e.resolveCondition(e)),n=await this.#i(t);return this.#o(e,t,n),this.#s.set(t,r6(n,pN)),{feeInfo:n.feeInfo,negRisk:n.negRisk,tickSize:n.tickSize}}async#n(e){let t=await x0(this.#r,e,vN,()=>this.#e.resolveCondition(e)),n=await x0(this.#s,t,pN,()=>this.#i(t));return this.#o(e,t,n),n}#o(e,t,n){if(!n.assetIds.has(e))throw this.#r.delete(e),this.#s.delete(t),new C(`Market ${t} does not include asset ${e}.`)}async#i(e){let t=await this.#e.fetchMarket(e),n=new Set(t.tokens.map(({assetId:r})=>r));for(let r of n)this.#r.set(r,r6(e));return{feeInfo:t.feeInfo,negRisk:t.negRisk,tickSize:t.tickSize,assetIds:n}}};o6=new WeakMap;Qie=180,s6=h.z.strictObject({price:ko,size:ko,side:Nt,builderCode:bo.optional(),postOnly:h.z.boolean().default(!1),expiration:h.z.number().int().nonnegative().optional()}),Xie=h.z.union([s6.extend(kf.shape),s6.extend(xf.shape)]).superRefine((e,t)=>{if(e.expiration!==void 0){let n=Math.floor(Date.now()/1e3)+Qie;e.expiration<n&&t.addIssue({code:"custom",message:"Expiration must be at least 3 minutes in the future.",path:["expiration"]})}}).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t}));t5=h.z.object({builderCode:bo.optional(),orderType:h.z.union([h.z.literal(cn.FAK),h.z.literal(cn.FOK)]).default(cn.FAK)}),a6=t5.extend({side:h.z.literal(Ue.BUY),amount:ko,maxSpend:ko.optional(),maxPrice:ko.optional()}),l6=t5.extend({side:h.z.literal(Ue.SELL),shares:ko,minPrice:ko.optional()}),tae=h.z.union([a6.extend(kf.shape),a6.extend(xf.shape),l6.extend(kf.shape),l6.extend(xf.shape)]).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t}));i5="Polymarket CTF Exchange",aae="DepositWallet",lae="1",xN="0x0000000000000000000000000000000000000000000000000000000000000000",AN="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",cae=Je.keccak256(we.fromString(AN),{as:"Hex"}),uae=Je.keccak256(we.fromString("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),{as:"Hex"}),dae=Je.keccak256(we.fromString(i5),{as:"Hex"}),a5=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],l5=[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"signer",type:"address"},{name:"tokenId",type:"uint256"},{name:"makerAmount",type:"uint256"},{name:"takerAmount",type:"uint256"},{name:"side",type:"uint8"},{name:"signatureType",type:"uint8"},{name:"timestamp",type:"uint256"},{name:"metadata",type:"bytes32"},{name:"builder",type:"bytes32"}],pae=[{name:"contents",type:"Order"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"}];p6="0x0000000000000000000000000000000000000000000000000000000000000000";yO=B(So,$,O,ue,_,C,E);bO=B($,O,ue,_,C,E);b5=yO;v5=bO;bae=250,wae=3e4,vae={timeoutMs:h.z.number().int().positive().optional()},kae=h.z.object(vae).default({}),ux=B($,O,ue,tt,en,_,C,E);px=B(bt,So,$,O,ue,_,C,E);mx=B(bt,So,$,O,ue,tt,en,_,C,E);fx=B(bt,$,O,ue,_,C,E);gx=B(bt,$,O,ue,tt,en,_,C,E);vO=h.z.string().regex(/^\d+(?:\.\d{1,28})?$/,"Expected a non-negative fixed-point fee rate with at most 28 fractional digits."),Iae=h.z.object({builderAddress:J,feeRate:vO});_ae=h.z.object({address:J}),bx=B($,O,_,C,E);Cae=h.z.strictObject({builder:J,maxFeeRate:vO,approvalVersion:h.z.number().int().positive().max(Number.MAX_SAFE_INTEGER)}),P5=h.z.strictObject({builderAddress:J.optional(),maxFeeRate:vO}),vx=B($,O,ue,_,C,E);vn=class{#e;#t;#r;#s;constructor({root:e,headers:t,resolveHeaders:n,onRateLimitUpdate:r}){this.#e=u0.create({prefixUrl:e,throwHttpErrors:!1}),this.#t=t,this.#r=n,this.#s=r}get(e,t={}){return this.#o("GET",e,t)}post(e,t={}){return this.#o("POST",e,t)}patch(e,t={}){return this.#o("PATCH",e,t)}del(e,t={}){return this.#o("DELETE",e,t)}#n(e){return e.startsWith("/")?e.slice(1):e}#o(e,t,n){return this.#c(this.#i(e,t,n),n.rateLimitBucket)}async#i(e,t,n){let r=this.#a(e,t,n),o=await this.#r?.(r),s=this.#l(this.#t,r.headers,o);return r.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json"),this.#e(this.#n(t),{body:r.body,headers:s,method:e,searchParams:r.params,...n.timeout!==void 0&&{timeout:n.timeout}})}#a(e,t,n){return{body:"json"in n?this.#u(n.json):void 0,headers:n.headers,json:"json"in n?n.json:void 0,method:e,params:"params"in n?n.params:void 0,path:t}}#u(e){if(e!==void 0)return JSON.stringify(e)}#l(...e){let t=new Headers;for(let n of e)if(n!==void 0)for(let[r,o]of new Headers(n).entries())t.set(r,o);return t}#c(e,t){return _n.fromPromise(e.then(async n=>{let r=Uae(n.headers,t);if(r!==void 0&&this.#p(r),n.ok)return n;let o=this.#d(n);if(n.status===429)throw new $(`Request to ${n.url} was rate limited`,{rateLimit:r,retryAfter:o});let{code:s,message:i,retryAfter:a}=await this.#m(n);throw new O(i,{code:s,retryAfter:o??a,status:n.status})}),n=>n instanceof $||n instanceof O?n:_.fromError(n))}#p(e){try{Promise.resolve(this.#s?.(e)).catch(()=>{})}catch{}}#d(e){let t=e.headers.get("retry-after");if(!(t===null||!/^\d+$/.test(t)))return Number(t)}async#m(e){let t=e.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")){let{error:n,code:r,retry_after_seconds:o}=await e.clone().json().catch(()=>({}));if(n){let s=typeof r=="string"&&r!==""?r:void 0,i=s===void 0&&e.status!==400&&typeof n=="string"&&/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/.test(n)?n:void 0,a=s??i;return{message:`${String(n)} (${e.url})`,...a!==void 0?{code:a}:{},...typeof o=="number"&&Number.isFinite(o)&&o>=0?{retryAfter:o}:{}}}}if(t?.includes("text/plain")){let n=await e.clone().text().then(r=>r.trim(),()=>"");if(n)return{message:`${n} (${e.url})`}}return e.headers.get("server")?.toLowerCase()?.includes("cloudflare")?{message:`Request to ${e.url} was blocked by Cloudflare with status ${e.status}`}:t?.includes("text/html")||t?.includes("application/xhtml+xml")?{message:`Request to ${e.url} failed with status ${e.status} and an unexpected HTML response body`}:{message:`Request to ${e.url} failed with status ${e.status} and unreadable response body`}}},Mae=1e4,Fae=3e4,qae=5e3,Hae=10*6e4,$ae=3e4,Vae=25e3,jae=65e3,kO=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e("PING")},Mae)}handleMessage(e){return e!=="PONG"?!1:(this.#e=Date.now(),!0)}isStale(e){return e-this.#e>Fae}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},E5=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e("PING")},qae)}handleMessage(){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>Hae}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},R5=class{#e=0;#t;start(e){this.#e=Date.now(),this.#t=e}stop(){this.#t=void 0}handleMessage(e){return e!=="ping"?!1:(this.#e=Date.now(),this.#t?.("pong"),!0)}isStale(e){return e-this.#e>$ae}},xO=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e(JSON.stringify({id:0,req:"post",op:{type:"ping"}}))},Vae)}handleMessage(){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>jae}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},I5=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>e('{"op":"ping"}'),3e4)}handleMessage(e){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>=9e4}stop(){clearInterval(this.#t),this.#t=void 0}},zae=5e3,Wae=250,Gae=3e4,ua=class{#e;#t=0;get isScheduled(){return this.#e!==void 0}schedule(e){if(this.#e!==void 0||!e.shouldReconnect())return;let t=e.delayPolicy?.(this.#t)??Yae(this.#t,{baseMs:Wae,maxMs:Gae});this.#t+=1,this.#e=gn(()=>{this.#e=void 0,this.#r(e)},t)}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0)}resetBackoff(){this.#t=0,this.stop()}async#r(e){if(e.shouldReconnect())try{await e.reconnect()}catch{this.schedule(e)}}},mi=class{#e;#t;#r;#s;#n;#o;#i;constructor(e={}){this.#e=e.heartbeat,this.#t=e.connectTimeoutMs,this.#r=e.closeTimeoutMs}connect(e){if(this.#n?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:!0});if(this.#c(),this.#o!==void 0)return this.#o;let t=this.#u(e).then(()=>({reusedOpenSocket:!1})).catch(n=>{throw this.#o===t&&(this.#o=void 0),n});return this.#o=t,t}send(e){return this.#a(JSON.stringify(e))}#a(e){return this.#n?.readyState!==WebSocket.OPEN?!1:(this.#n.send(e),!0)}async close(){this.#s?.();let e=await this.#m();this.#d(),!(e===void 0||e.readyState===WebSocket.CLOSED)&&await new Promise(t=>{let n=this.#r===void 0?void 0:gn(t,this.#r);e.addEventListener("close",()=>{clearTimeout(n),t()},{once:!0}),e.readyState!==WebSocket.CLOSING&&e.close()})}async#u(e){let t=await e.prepare?.();return new Promise((n,r)=>{let o=Kae(e.url,e.headers),s,i=()=>{o.removeEventListener("open",a),clearTimeout(s),this.#s=void 0,r(new _("WebSocket connection did not open.")),o.close()},a=()=>{clearTimeout(s),this.#s=void 0,o.removeEventListener("error",l),this.#l(o),this.#p(),e.onOpen(t),n(o)},l=c=>{clearTimeout(s),this.#s=void 0,o.removeEventListener("open",a),r(new _(`WebSocket connection failed: ${e.url}`,{cause:c}))};o.addEventListener("open",a,{once:!0}),this.#t!==void 0&&(this.#s=i,s=gn(i,this.#t)),o.addEventListener("error",l,{once:!0}),o.addEventListener("message",c=>{if(this.#n!==o)return;let u=String(c.data);if(this.#e?.handleMessage(u))return;let d;try{d=JSON.parse(u)}catch{return}e.onMessage(d)}),o.addEventListener("close",c=>{this.#n===o&&(this.#c(),e.onConnectionLost({code:c.code||1005,reason:c.reason??""}))}),o.addEventListener("error",()=>e.onError())})}#l(e){this.#n=e,this.#o=void 0}#c(){this.#d(),this.#n=void 0}#p(){this.#d();let e=this.#e;e!==void 0&&(e.start(t=>this.#a(t)),this.#i=ud(()=>{if(!e.isStale(Date.now()))return;let t=this.#n;t?.readyState===WebSocket.OPEN&&t.close()},zae))}#d(){this.#i!==void 0&&(clearInterval(this.#i),this.#i=void 0),this.#e?.stop()}async#m(){let e=this.#n,t=this.#o;return this.#n=void 0,this.#o=void 0,e!==void 0?e:t?.then(()=>this.#n,()=>{})}};P0=1440*60*1e3,AO=90*P0,cr=h.z.number().int().nonnegative(),kx=h.z.object({start:cr.optional(),end:cr.optional()}),_5=h.z.object({interval:$w,start:cr,end:cr.optional()}),Xae=h.z.enum(["perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),Jae=h.z.enum(["perpsEquityHistory","perpsPnlHistory"]),TO=h.z.object({kind:Xae,startTimestamp:cr,endTimestamp:cr,instrumentId:Ae.optional(),depositStatus:kd.optional(),withdrawalStatus:xd.optional(),hash:et.optional(),seenKeys:h.z.array(h.z.string())}),C5=h.z.object({kind:Jae,startTimestamp:cr,endTimestamp:cr,interval:$w});rle=h.z.object({instrumentId:Ae.optional()}).default({});sle=h.z.object({instrumentId:Ae.optional()}).default({});ale=h.z.object({orderId:Cn.optional(),clientOrderId:Er.optional(),instrumentId:Ae.optional(),start:cr.optional(),end:cr.optional()}).default({}),lle=ale.transform(({end:e,start:t,...n})=>({...n,endTimestamp:e,startTimestamp:t}));ule=h.z.object({start:cr.optional(),end:cr.optional(),sort:E_.optional(),cursor:ye.optional()});ple=kx.extend({cursor:ye.optional(),instrumentId:Ae.optional()}),mle=h.z.object({cursor:ye}),hle=h.z.union([ple.transform(({cursor:e,...t})=>({cursor:e,params:xx(t,P0)})),mle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);gle=kx.extend({cursor:ye.optional(),depositStatus:kd.optional(),hash:et.optional()}),yle=h.z.object({cursor:ye}),ble=h.z.union([gle.transform(({cursor:e,...t})=>({cursor:e,params:xx(t,AO)})),yle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);vle=kx.extend({cursor:ye.optional(),withdrawalStatus:xd.optional(),hash:et.optional()}),kle=h.z.object({cursor:ye}),xle=h.z.union([vle.transform(({cursor:e,...t})=>({cursor:e,params:xx(t,AO)})),kle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Tle=kx.extend({cursor:ye.optional()}),Sle=h.z.object({kind:h.z.literal("perpsInternalTransfers"),startTimestamp:cr,endTimestamp:cr,seenKeys:h.z.array(h.z.string())}),Ple=h.z.object({cursor:ye}),Ele=h.z.union([Tle.transform(({cursor:e,...t})=>({cursor:e,params:xx(t,AO)})),Ple.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Ile=_5.extend({cursor:ye.optional()}),_le=h.z.object({cursor:ye}),Cle=h.z.union([Ile.transform(({cursor:e,...t})=>({cursor:e,params:N5(t)})),_le.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Ole=_5.extend({cursor:ye.optional()}),Lle=h.z.object({cursor:ye}),Dle=h.z.union([Ole.transform(({cursor:e,...t})=>({cursor:e,params:N5(t)})),Lle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Ble=h.z.object({kind:h.z.literal("perpsNotifications"),cursor:h.z.string().min(1),sinceSeq:h.z.number().int().nonnegative().optional(),limit:h.z.number().int().positive().optional()}),Mle=h.z.object({sinceSeq:h.z.number().int().nonnegative().optional(),limit:h.z.number().int().positive().optional(),cursor:ye.optional()}),Fle=h.z.object({cursor:ye}),qle=h.z.union([Mle.transform(({cursor:e,...t})=>({cursor:e,params:t})),Fle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Vle=h.z.object({ids:h.z.array(h.z.string().min(1)).min(1)}),jle=h.z.object({upTo:h.z.object({id:h.z.string().min(1),timestamp:h.z.number().int().nonnegative()})}),zle=h.z.union([Vle.transform(({ids:e})=>({ids:e})),jle.transform(({upTo:e})=>({before:Gle(e)}))]);Qle=h.z.object({builder:J.optional()}).default({}),Ax=B($,O,_,C,E);Jle=2160*60*60*1e3,mN=h.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),L5=h.z.object({start:mN.optional(),end:mN.optional(),asOfSequence:mN.optional()}).refine(({start:e,end:t})=>e===void 0||t===void 0||e<=t,{message:"end must not precede start",path:["end"]}).refine(({start:e,end:t})=>e===void 0||t===void 0||t-e<=Jle,{message:"The reporting window must not exceed 90 days",path:["end"]}).default({}),Tx=B($,O,_,C,E);Sx=B($,O,_,C,E);PO=h.z.object({instrumentId:Ae,side:Nt,quantity:Ao,reduceOnly:h.z.boolean().default(!1),clientOrderId:Er.optional()}),tce=PO.extend({price:Ao,timeInForce:h.z.literal(ti.GTC),postOnly:h.z.boolean().default(!1)}),nce=PO.extend({price:Ao.optional(),timeInForce:h.z.literal(ti.IOC),postOnly:h.z.never().optional()}),rce=PO.extend({price:Ao.optional(),timeInForce:h.z.literal(ti.FOK),postOnly:h.z.never().optional()}),EO=h.z.discriminatedUnion("timeInForce",[tce,nce,rce]),A0=h.z.object({triggerPrice:Ao,limitPrice:Ao.optional()}),T0=h.z.object({triggerPrice:Ao}),oce=h.z.union([h.z.object({takeProfit:A0,stopLoss:A0.optional()}),h.z.object({takeProfit:A0.optional(),stopLoss:A0})]),sce=h.z.object({orders:h.z.array(EO).min(1),expiresAt:h.z.number().int().positive().optional()});ace=h.z.intersection(EO,h.z.intersection(oce,h.z.object({clientOrderId:Er.default(U5),expiresAt:h.z.number().int().positive().optional()}))),lce=h.z.intersection(EO,h.z.object({clientOrderId:Er.default(U5),expiresAt:h.z.number().int().positive().optional(),takeProfit:h.z.never().optional(),stopLoss:h.z.never().optional()})),D5=h.z.array(sf).min(1).refine(e=>e.every(t=>t.status==="ok"),"Expected successful Perps order acknowledgements.");pce=h.z.union([h.z.object({takeProfit:T0,stopLoss:T0.optional()}),h.z.object({takeProfit:T0.optional(),stopLoss:T0})]),mce=h.z.intersection(pce,h.z.object({instrumentId:Ae,expiresAt:h.z.number().int().positive().optional()}));TN=4,SN=2e3,fce=100,gce=1e3,yce=h.z.object({maxAttempts:h.z.number().int().positive().default(TN),maxElapsedMs:h.z.number().int().positive().default(SN)}).default({maxAttempts:TN,maxElapsedMs:SN}),E0=h.z.object({expiresAt:h.z.number().int().positive().optional(),retry:h.z.union([h.z.literal(!1),yce]).default({maxAttempts:TN,maxElapsedMs:SN}),signal:h.z.custom(e=>e instanceof AbortSignal,"Expected an AbortSignal.").optional()}),bce=h.z.union([E0.extend({orderId:Cn,clientOrderId:h.z.undefined().optional()}),E0.extend({clientOrderId:Er,orderId:h.z.undefined().optional()})]);vce=h.z.union([E0.extend({orderIds:h.z.array(Cn).min(1),clientOrderIds:h.z.undefined().optional()}),E0.extend({clientOrderIds:h.z.array(Er).min(1),orderIds:h.z.undefined().optional()})]);Sce=h.z.object({instrumentId:Ae.optional(),expiresAt:h.z.number().int().positive().optional()}).default({});Ece=5e3,Rce=h.z.object({cancelAt:h.z.number().int().positive(),expiresAt:h.z.number().int().positive().optional()}).superRefine((e,t)=>{let n=Date.now()+Ece;e.cancelAt<n&&t.addIssue({code:"custom",message:"cancelAt must be at least 5 seconds in the future.",path:["cancelAt"]})}),Px=B(lf,$,O,ue,_,C,E),Ice="auto_cancel_daily_limit_reached";Cce=h.z.object({expiresAt:h.z.number().int().positive().optional()}).default({});Oce=h.z.object({instrumentId:Ae,leverage:h.z.number().int().positive(),crossMargin:h.z.boolean()}),Ex=B(O,ue,_,E);Dce=h.z.object({instrumentId:Ae,amount:Ao}),Rx=B(O,ue,_,E);$ce=3e4,hN=3e4,Vce=2e3,jce=["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications","tpsl"],zce=new Set(["notifications","builderFills"]),Wce=h.z.object({id:h.z.number().int().positive().optional(),data:h.z.unknown().optional()}).passthrough(),fN=h.z.union([of,h.z.array(of)]).transform(e=>Array.isArray(e)?e.find(t=>t.status==="err")??e[0]:e),Ix=B($,O,ue,_,C,E),M5=class{credentials;#e;#t;#r;#s;#n;#o;#i=new mi({heartbeat:new xO});#a=Bd({objectMode:!0});#u=new Map;#l=new Set;#c=new ua;#p=new Map;#d;#m;#y=Promise.resolve();#h;#f=1;#g;constructor(e){this.#e=e.approveBuilderFee,this.#h=e.includeBuilderFills??!1,this.#m=e.builderAttribution===void 0||typeof e.builderAttribution=="string"?void 0:Object.freeze(F(e.builderAttribution,Iae)),this.#d=typeof e.builderAttribution=="string"?F(e.builderAttribution,J):this.#m?.builderAddress,this.#t=new vn({headers:e.headers,resolveHeaders:async()=>this.#T(),root:e.restUrl}),this.#r=e.chainId,this.credentials=e.credentials,this.#s=e.headers,this.#n=e.onClose,this.#o=e.wsUrl}get builderAttribution(){return this.#m}get closed(){return this.#g!==void 0}async connect(){if(this.#d!==void 0&&this.#m===void 0){let e=await X(this.#t.get("/v1/info/builder",{params:new URLSearchParams({address:this.#d})}).andThen(z(Jh)));if(!e.registered||!e.enabled||!e.admissionEnabled)throw new E("Builder attribution is not active for this builder address.");let t=(await this.fetchBuilderApprovals({builder:this.#d})).find(r=>r.builder.toLowerCase()===this.#d?.toLowerCase()),n=h6(e.maxFeeRate,t?.maxFeeRate??"0");this.#m=/[1-9]/.test(n)?Object.freeze({builderAddress:this.#d,feeRate:n}):void 0}await this.#x(!1)}async close(){this.#g===void 0&&(this.#g=this.#P()),await this.#g}[Symbol.asyncIterator](){return this.#a[Symbol.asyncIterator]()}async approveBuilderFee(e){let t=F(e,P5);return this.#b(()=>({...t,builderAddress:t.builderAddress===void 0?this.#d:t.builderAddress}))}async revokeBuilderFee(e){return this.#b(()=>{let t=e??this.#d;if(t===void 0)throw new E("A builder address is required when the session has no active builder attribution.");return{builderAddress:t,maxFeeRate:"0"}})}#b(e){let t=this.#y.catch(()=>{}).then(async()=>{if(this.closed)throw new _("Perps session closed.");if(this.#e===void 0)throw new E("Builder approval requires a session opened with a secure client.");let n=await this.#e(this,e());if(/^0+(?:\.0+)?$/.test(n.maxFeeRate))this.#d?.toLowerCase()===n.builder.toLowerCase()&&(this.#m=void 0,this.#d=void 0);else{let r=await X(this.#t.get("/v1/info/builder",{params:new URLSearchParams({address:n.builder})}).andThen(z(Jh)));this.#d=n.builder;let o=h6(r.maxFeeRate,n.maxFeeRate);this.#m=/[1-9]/.test(o)?Object.freeze({builderAddress:n.builder,feeRate:o}):void 0}return n});return this.#y=t,t}async fetchBuilderApprovals(e){return await Xle(this.#t,e)}listBuilderEarnings(e){return Zle(this.#t,e)}async fetchBuilderEarningsSummary(e){return await ece(this.#t,e)}async fetchBalances(){return await Zae(this.#t)}async fetchPortfolio(){return await ele(this.#t)}async fetchStats(){return await tle(this.#t)}async fetchAccountConfig(e){return await ole(this.#t,e)}async fetchAutoCancelStatus(){return await nle(this.#t)}async fetchOpenOrders(e){return await ile(this.#t,e)}async fetchOrders(e){return await cle(this.#t,e)}listFills(e={}){return dle(this.#t,e)}listFundingPayments(e={}){return fle(this.#t,e)}listDeposits(e={}){return wle(this.#t,e)}listInternalTransfers(e={}){return Rle(this.#t,e)}listWithdrawals(e={}){return Ale(this.#t,e)}listEquityHistory(e){return Nle(this.#t,e)}listPnlHistory(e){return Ule(this.#t,e)}listNotifications(e={}){return Hle(this.#t,e)}async fetchUnreadNotificationsCount(){return await $le(this.#t)}async markNotificationsRead(e){await Wle(this.#t,e)}async placeOrder(e){return await uce(this,e)}async postOrders(e){return await ice(this,e)}async placePositionTpSl(e){return await hce(this,e)}async cancelOrder(e){return await wce(this,e)}async cancelOrders(e){return await PN(this,e)}async cancelAllOrders(e){await Pce(this,e)}async armAutoCancel(e){await _ce(this.#t,(t,n)=>this.#k(t,n),e)}async disarmAutoCancel(e){await Nce(this.#t,(t,n)=>this.#k(t,n),e)}async updateLeverage(e){return await Lce(this,e)}async updateMargin(e){await Uce(this,e)}async#x(e){await this.#i.connect({onConnectionLost:()=>this.#N(),onError:()=>{},onMessage:t=>this.#S(t),onOpen:()=>{},headers:this.#s,url:this.#o}),await this.#A(),await this.#v(),this.#c.resetBackoff(),e&&(this.#p.clear(),this.#a.push({reason:"reconnect",type:"resync"}))}async#A(){await this.#w({id:this.#f++,op:{args:{proxy:this.credentials.proxy,secret:this.credentials.secret},type:"auth"},req:"post"},fN,$ce,"Perps session authentication timed out.")}async#v(){await this.#w({id:this.#f++,req:"sub",chs:jce},fN,hN,"Perps session subscription timed out."),this.#h&&this.#w({id:this.#f++,req:"sub",chs:["builderFills"]},fN,hN,"Perps builder fills subscription timed out.").catch(()=>{})}#T(){return{"POLYMARKET-PROXY":this.credentials.proxy,"POLYMARKET-SECRET":this.credentials.secret}}async executeCommand(e,t){let n=_0(e.op),r=this.#k(e.op,e.expiresAt);return await this.#w({...r,id:this.#f++,op:n,req:"post"},t,hN,"Perps command response timed out.")}async executeCommandWithEvent(e,t,n){let r=this.#L(n),o=this.executeCommand(e,t);o.then(()=>this.#D(r,Vce),()=>{});try{let[s,i]=await Promise.all([o,r.promise]);return[s,i]}finally{this.#E(r)}}async executeDeleteCommand(e){let t=this.#k(e.op,e.expiresAt);return await X(this.#t.del(e.path,{json:{...t,op:_0(e.op)}}).andThen(z(e.responseSchema)))}#k(e,t){let n=Yce(),r=Date.now(),o;try{o=Rae({chainId:this.#r,op:e,privateKey:this.credentials.privateKey,salt:n,timestamp:r})}catch(i){throw ue.fromError(i,"Could not sign the Perps session command")}let s={salt:n,sig:o,ts:r};return t!==void 0&&(s.exp=t),s}async#w(e,t,n,r){let o=Gce(t);this.#u.set(e.id,o);let s=gn(()=>{o.reject(new _(r))},n);try{if(!this.#i.send(e))throw new _("Perps session transport is not open.");return await o.promise}finally{clearTimeout(s),this.#u.delete(e.id)}}async#P(){this.#c.stop(),this.#R(new _("Perps session closed.")),this.#_(new _("Perps session closed.")),this.#a.end(),await this.#i.close(),this.#n(this)}#S(e){if(this.#C(e)||NH.safeParse(e).success)return;let t=OH.safeParse(e);if(!t.success)return;let n=t.data;this.#O(n),this.#I(n)}#C(e){let t=Wce.safeParse(e);if(!t.success||t.data.id===void 0)return!1;let n=this.#u.get(t.data.id);if(n===void 0)return!0;let r=n.schema.safeParse(t.data.data);if(!r.success){let o=IO(t.data.data??t.data);return o!==void 0?n.reject(new O(o.error,{status:200})):n.reject(new _("Perps session unexpected response.")),!0}return Kce(r.data)?n.reject(new O(r.data.error,{status:200})):n.resolve(r.data),!0}#N(){this.#R(new _("Perps session connection closed.")),this.#_(new _("Perps session connection closed.")),this.#g===void 0&&this.#c.schedule({reconnect:()=>this.#x(!0),shouldReconnect:()=>this.#g===void 0})}#R(e){for(let t of this.#u.values())t.reject(e);this.#u.clear()}#O(e){if(zce.has(e.channel))return;let t=this.#p.get(e.channel);this.#p.set(e.channel,e.sequence),!(t===void 0||e.sequence===t+1)&&this.#I({channel:e.channel,previousSequence:t,reason:"sequence_gap",sequence:e.sequence,type:"resync"})}#I(e){this.#U(e),this.#a.push(e)}#L(e){let t,n,r={promise:new Promise((o,s)=>{t=o,n=s}),predicate:e,reject:n,resolve:t};return this.#l.add(r),r}#D(e,t){this.#l.has(e)&&(e.timeout=gn(()=>{this.#E(e),e.reject(new tt("Perps event wait timed out."))},t))}#U(e){for(let t of Array.from(this.#l))t.predicate(e)&&(this.#E(t),t.resolve(e))}#E(e){this.#l.delete(e)&&e.timeout!==void 0&&clearTimeout(e.timeout)}#_(e){for(let t of Array.from(this.#l))this.#E(t),t.reject(e)}};ic=B($,O,_,C,E),ds=h.z.number().int().nonnegative(),F5=1440*60*1e3,Xce=h.z.object({instrumentId:Ae.optional(),category:Xh.optional()}).default({}),_x=ic;Jce=h.z.object({instrumentId:Ae}),Nx=ic;Zce=h.z.object({instrumentId:Ae.optional()}).default({}),Lx=ic;eue=h.z.union([h.z.literal(10),h.z.literal(100),h.z.literal(500),h.z.literal(1e3)]),tue=h.z.object({instrumentId:Ae,depth:eue.default(100)}),Dx=ic;nue=h.z.object({instrumentId:Ae,interval:Hw,start:ds.optional(),end:ds.optional(),cursor:ye.optional()}),rue=h.z.object({cursor:ye}),oue=h.z.union([nue.transform(({cursor:e,...t})=>({cursor:e,params:hue(t)})),rue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Bx=ic;q5=h.z.object({instrumentId:Ae,start:ds.optional(),end:ds.optional()}),sue=q5.extend({cursor:ye.optional()}),iue=h.z.object({cursor:ye}),aue=h.z.union([sue.transform(({cursor:e,...t})=>({cursor:e,params:H5(t)})),iue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),lue=q5.extend({cursor:ye.optional()}),cue=h.z.object({cursor:ye}),Fx=ic;uue=h.z.union([lue.transform(({cursor:e,...t})=>({cursor:e,params:H5(t)})),cue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Hx=ic;Vx=B($,O,_,C);due=h.z.object({kind:h.z.literal("perpsCandles"),instrumentId:Ae,interval:Hw,startTimestamp:ds,endTimestamp:ds}),pue=h.z.object({kind:h.z.literal("perpsFundingHistory"),instrumentId:Ae,startTimestamp:ds,endTimestamp:ds}),mue=h.z.object({kind:h.z.literal("perpsTrades"),instrumentId:Ae,startTimestamp:ds,endTimestamp:ds,seenTradeIds:h.z.array(na)});Aue=h.z.custom(e=>FI(e),"Expected a hex-encoded 32-byte private key."),Tue=h.z.object({proxy:h.z.string().transform(e=>Be(e)),privateKey:Aue,secret:h.z.string().min(1),expiresAt:h.z.number().int().positive()}),Sue=10080*60*1e3,Pue=h.z.strictObject({builderAttribution:J.optional(),includeBuilderFills:h.z.boolean().optional(),expiresIn:h.z.number().int().positive().default(Sue),label:h.z.string().min(1).optional()}),Eue=h.z.strictObject({builderAttribution:J.optional(),includeBuilderFills:h.z.boolean().optional(),credentials:Tue}),Rue=h.z.union([Pue,Eue]),Iue=h.z.object({proxy:h.z.string()}),_ue=Iue.transform(e=>({proxy:Be(e.proxy)})),$5=h.z.bigint().positive().max(lr),Cue=h.z.object({amount:$5,metadata:ur.optional()}),Nue=h.z.object({amount:$5}),Oue=Ao.refine(e=>/^\d+(?:\.\d+)?$/.test(e)&&/[1-9]/.test(e),"Expected a positive fixed-point decimal amount."),Lue=h.z.string().min(1).refine(e=>new TextEncoder().encode(e).byteLength<=64,"Expected a label no longer than 64 UTF-8 bytes."),Due=h.z.object({recipient:J,amount:Oue,label:Lue.optional()}),zx=B($,O,ue,_,C,E),Wx=B($,O,ue,_,C,E),V5=B(E),Gx=B(bt,$,O,ue,_,C,E),Kx=B($,O,ue,_,C,E),Yx=B($,O,ue,_,C,E);Gue=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J.optional(),conditionId:h.z.union([ql,ca(ql,20)]).optional(),status:_$.optional(),eventId:h.z.array(Gt).min(1).optional(),filterType:N$.optional(),filterAmount:h.z.number().min(0).optional(),includeArchived:h.z.boolean().optional(),sortBy:C$.optional(),sortDirection:m0.optional(),window:L0.optional()}).refine(e=>e.user!==void 0||e.conditionId,{message:"Provide user or conditionId",path:["user"]}).refine(e=>e.user!==void 0||!Array.isArray(e.conditionId)||e.conditionId.length===1,{message:"Without user, provide exactly one conditionId",path:["conditionId"]}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}).refine(e=>e.user!==void 0||e.eventId===void 0,{message:"eventId requires user",path:["eventId"]}).refine(e=>!(e.includeArchived&&e.status==="CLOSED"),{message:"includeArchived does not apply to CLOSED positions",path:["includeArchived"]}).refine(e=>e.status!==ai.RedeemableLost||e.user!==void 0,{message:"REDEEMABLE_LOST requires user",path:["user"]}),tA=B($,O,_,C,E);Kue=h.z.union([Nd,h.z.tuple([Nd],Nd).refine(e=>e.length===1||!e.includes(ii.Redeemable),{message:"REDEEMABLE must be the sole status value"})]),Yue=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([Zt,ca(Zt,20)]).optional(),status:Kue.optional(),sortBy:O$.optional(),sortDirection:m0.optional(),updatedAfter:gf.optional(),updatedBefore:gf.optional()}),Que=Yue.refine(e=>e.updatedBefore===void 0||e.updatedAfter===void 0||e.updatedBefore>=e.updatedAfter,{message:"updatedBefore must not precede updatedAfter",path:["updatedBefore"]}),nA=B($,O,_,C,E);Xue=h.z.object({user:J,conditionIds:ca(ql,20).optional()}),rA=B($,O,_,C,E);Jue=h.z.object({user:J}),oA=B($,O,_,C,E);Zue=h.z.object({user:J,interval:YC.optional(),fidelity:d0.optional()}),sA=B($,O,_,C,E);ede=h.z.object({user:J,window:L0.optional()}),iA=B($,O,_,C,E);tde=h.z.object({user:h.z.string()}),aA=B($,O,_,C,E);lA=B($,O,_,C,E),G5=h.z.object({amount:h.z.bigint().min(0n),conditionId:xe,metadata:ur.optional()}),K5=lA;Y5=h.z.object({amount:h.z.bigint().positive(),legs:h.z.array(Xe).min(1).max(50),metadata:ur.optional()}),Q5=lA;rde=h.z.union([G5.extend({legs:h.z.never().optional()}),Y5.extend({conditionId:h.z.never().optional()})]);Vd=B(bt,$,O,ue,tt,en,_,C,E),X5=Vd;Z5=Vd;pA=B($,O,_,C,E),tV=h.z.object({amount:h.z.union([h.z.bigint().positive(),h.z.literal("max")]),conditionId:xe,metadata:ur.optional()}),nV=pA;rV=h.z.object({amount:h.z.union([h.z.bigint().positive(),h.z.literal("max")]),legs:h.z.array(Xe).min(1).max(50),metadata:ur.optional()}),oV=pA;ode=h.z.union([tV.extend({legs:h.z.never().optional()}),rV.extend({conditionId:h.z.never().optional()})]);jd=B(bt,$,O,ue,tt,en,_,C,E),sV=jd;aV=jd;gA=B($,O,_,C,E),cV=h.z.object({conditionId:xe,marketId:h.z.never().optional(),amount:h.z.never().optional(),positionId:h.z.never().optional(),metadata:ur.optional()}),uV=h.z.object({conditionId:h.z.never().optional(),marketId:Ji,amount:h.z.never().optional(),positionId:h.z.never().optional(),metadata:ur.optional()}),sde=h.z.union([cV,uV]),dV=gA;pV=h.z.object({positionId:Xe,conditionId:h.z.never().optional(),marketId:h.z.never().optional(),metadata:ur.optional()});mV=gA;ide=h.z.union([cV,uV,pV]);bA=B(bt,$,O,ue,tt,en,_,C,E);dde=h.z.object({address:h.z.string()}),vA=B($,O,_,C,E);ac=class extends Ct{name="RfqQuoteRejectedError";code;errorId;rfqId;constructor(e,t){super(e,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId}},xA=B(Yr,ac,ue,tt,_,E),lc=class extends Ct{name="RfqCancelQuoteRejectedError";code;errorId;rfqId;quoteId;constructor(e,t){super(e,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId,this.quoteId=t.quoteId}},AA=B(Yr,lc,tt,_),cc=class extends Ct{name="RfqConfirmationRejectedError";code;errorId;rfqId;quoteId;constructor(e,t){super(e,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId,this.quoteId=t.quoteId}},TA=B(Yr,cc,tt,_),SA=B(Yr,_,E);UO="/v1/builder/rfq/requests",pde=3e4,mde=3e4,hde=3e4,fde=500,gde=3e4,yde=1e3,bde="0x0000000000000000000000000000000000000000000000000000000000000000",ms=class extends Ct{name="RfqRequestRejectedError";status;code;constructor(e,t){super(e,t),this.status=t.status,this.code=t.code}};wde=new Set(Object.values(li));y6=h.z.array(h.z.string().regex(/^\d+$/,"Leg position IDs must be numeric strings.").transform(e=>BigInt(e).toString())).min(2,"Combo requests require at least 2 legs.").max(50,"Combo requests allow at most 50 legs.").refine(e=>new Set(e).size===e.length,"Leg position IDs must not contain duplicates.").transform(e=>[...e].sort((t,n)=>{let r=BigInt(t),o=BigInt(n);return r<o?-1:r>o?1:0})),C0=h.z.union([h.z.number(),h.z.string()]).transform((e,t)=>{let n=/^(\d+)(?:\.(\d*))?$/.exec(String(e));if(n===null)return t.addIssue({code:"custom",message:"Value must be a valid decimal."}),h.z.NEVER;let[,r="",o=""]=n;if(o.length>6)return t.addIssue({code:"custom",message:"Value must have at most 6 decimal places."}),h.z.NEVER;let s=vde(r,o);return s<=0n?(t.addIssue({code:"custom",message:"Value must be greater than 0."}),h.z.NEVER):s.toString()});kde=h.z.discriminatedUnion("direction",[h.z.object({amount:C0,direction:h.z.literal(Ue.BUY),legPositionIds:y6,side:h.z.literal(Eo.Yes).optional()}),h.z.object({direction:h.z.literal(Ue.SELL),legPositionIds:y6,side:h.z.literal(Eo.Yes).optional(),size:C0})]),EA=B($,ms,_,C,E);Tde=Nt,Sde=h.z.object({blendedPrice:h.z.string(),builderCode:h.z.string().regex(/^0x[0-9a-fA-F]{64}$/,"builderCode must be a 32-byte hex string.").transform(kw),direction:Tde,expiresAt:h.z.number().int().nonnegative(),makerAmount:C0.transform(Sl),netReceive:h.z.string().optional(),positionId:h.z.string().regex(/^\d+$/,"positionId must be a numeric string.").transform(Aw),quoteId:h.z.string().min(1).transform(Tw),rfqId:h.z.string().min(1).transform(md),takerAmount:C0.transform(Sl),totalRequired:h.z.string()}),IA=B(bt,$,ms,ue,tt,_,C,E);Cde=h.z.object({pollingIntervalMs:h.z.number().int().positive().optional(),rfqId:h.z.string().min(1).transform(md),timeoutMs:h.z.number().int().positive().optional()}),CA=B($,ms,tt,_,C,E);Nde=h.z.object({rfqId:h.z.string().min(1).transform(md)}),OA=B($,ms,_,C,E);zd=(e=>(e.Volume="volume",e.Volume24Hr="volume_24hr",e.Liquidity="liquidity",e.Competitive="competitive",e.ClosedTime="closed_time",e.StartDate="start_date",e.EndDate="end_date",e))(zd||{}),b6=100,Ode=h.z.object({q:h.z.string().trim().min(1),ascending:h.z.boolean().optional(),cache:h.z.boolean().optional(),cursor:ye.optional(),eventsStatus:h.z.string().min(1).optional(),eventsTag:h.z.array(h.z.string()).optional(),excludeTagIds:h.z.array(h.z.number().int()).optional(),keepClosedMarkets:h.z.number().int().optional(),optimized:h.z.boolean().optional(),pageSize:Ot.default(10),presets:h.z.array(h.z.string()).optional(),recurrence:h.z.enum(["daily","weekly","monthly"]).optional(),searchProfiles:h.z.boolean().optional(),searchTags:h.z.boolean().optional(),sort:h.z.enum(zd).optional()}),DA=B(Ol,$,O,_,C,E);Dde=h.z.object({ascending:h.z.boolean().optional(),closed:h.z.boolean().optional(),cursor:ye.optional(),excludeEvents:h.z.boolean().optional(),locale:h.z.string().optional(),order:h.z.string().optional(),pageSize:Ot.max(50).default(20),recurrence:h.z.enum(["daily","weekly","monthly"]).optional(),slug:h.z.array(h.z.string()).optional()}),Ude=h.z.object({id:h.z.string(),locale:h.z.string().optional()}),BA=B($,O,_,C,E);FA=B($,O,_,C,E);HA=B($,O,ue,_,C,E);Bde=[yo.ALL],Mde=4315*60*60,wV=300*1e3,Fde=h.z.object({address:J,idempotencyKey:h.z.string().trim().min(1).optional(),scopes:h.z.array(Ih).min(1).default(Bde)}).superRefine((e,t)=>{Wt(e.address,ts)&&t.addIssue({code:"custom",message:"Session key address must not be the zero address.",path:["address"]}),e.scopes.includes(yo.ALL)&&e.scopes.some(n=>n!==yo.ALL)&&t.addIssue({code:"custom",message:"Session key scope ALL cannot be combined with another scope.",path:["scopes"]})}).transform(e=>({...e,address:Be(e.address.toLowerCase())})),$A=B(bt,$,O,ue,tt,en,_,C,E);qde=h.z.object({address:J,idempotencyKey:h.z.string().trim().min(1).optional()}).superRefine((e,t)=>{Wt(e.address,ts)&&t.addIssue({code:"custom",message:"Session key address must not be the zero address.",path:["address"]})}).transform(e=>({...e,address:Be(e.address.toLowerCase())})),jA=B(bt,$,O,ue,tt,en,_,C,E);WA=B($,O,_,C);KA=B($,O,_,C);jde=h.z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._:/-]+$/),w6=h.z.string().max(64).regex(/^[a-z0-9]+usd$/,{error:"Use a canonical lowercase USD pair such as btcusd. Slash-separated symbols and USDT pairs are not supported."}),vV=(e=>(e.Update="update",e.Subscribe="subscribe",e))(vV||{}),zde=h.z.discriminatedUnion("topic",[h.z.strictObject({topic:h.z.literal("prices.crypto"),symbols:h.z.array(w6).min(1)}),h.z.strictObject({topic:h.z.literal("prices.crypto.twap"),symbols:h.z.array(w6).min(1)}),h.z.strictObject({topic:h.z.literal("prices.equity"),symbol:jde,types:h.z.array(h.z.enum(vV)).optional()})]);QA=B(_,E,O,Yr),kV=(e=>(e.Market="market",e.User="user",e.Sports="sports",e.Crypto="prices.crypto",e.Twap="prices.crypto.twap",e.Equity="prices.equity",e.Comments="comments",e.LegacyBinance="prices.crypto.binance",e.LegacyChainlink="prices.crypto.chainlink",e.LegacyTwap="prices.crypto.chainlink.twap",e.LegacyEquity="prices.equity.pyth",e.PerpsTrades="perps.trades",e.PerpsBbo="perps.bbo",e.PerpsBook="perps.book",e.PerpsCandles="perps.candles",e.PerpsTickers="perps.tickers",e.PerpsStatistics="perps.statistics",e))(kV||{}),Gde=h.z.object({topic:h.z.enum(kV)}),Kde=h.z.object({topic:h.z.literal("prices.crypto.chainlink.twap"),windowSeconds:h.z.union([h.z.literal(30),h.z.literal(60)]),symbols:h.z.array(h.z.string()).optional()}),Yde=h.z.union([h.z.object({topic:h.z.literal("market"),assetIds:h.z.array(h.z.string()),tokenIds:h.z.never().optional(),customFeatureEnabled:h.z.boolean().optional()}),h.z.object({topic:h.z.literal("market"),assetIds:h.z.never().optional(),tokenIds:h.z.array(h.z.string()),customFeatureEnabled:h.z.boolean().optional()})]);Jde=h.z.object({ascending:h.z.boolean().optional(),cursor:ye.optional(),includeTemplate:h.z.boolean().optional(),isCarousel:h.z.boolean().optional(),locale:h.z.string().optional(),order:h.z.string().optional(),pageSize:Ot.max(100).default(20)}),Zde=h.z.union([h.z.object({id:h.z.string(),includeTemplate:h.z.boolean().optional(),locale:h.z.string().optional()}),h.z.object({slug:h.z.string(),locale:h.z.string().optional()})]),epe=h.z.object({id:h.z.string(),omitEmpty:h.z.boolean().optional(),status:h.z.enum(["active","closed","all"]).optional()}),tpe=h.z.object({slug:h.z.string()}),npe=h.z.object({id:h.z.string(),locale:h.z.string().optional(),omitEmpty:h.z.boolean().optional(),status:h.z.enum(["active","closed","all"]).optional()}),rpe=h.z.object({locale:h.z.string().optional(),slug:h.z.string(),omitEmpty:h.z.boolean().optional(),status:h.z.enum(["active","closed","all"]).optional()}),XA=B($,O,_,C,E);ZA=B($,O,_,C,E);tT=B($,O,_,C,E);rT=B($,O,_,C,E);ope=h.z.object({abbreviation:h.z.array(h.z.string()).optional(),ascending:h.z.boolean().optional(),cursor:ye.optional(),league:h.z.array(h.z.string()).optional(),name:h.z.array(h.z.string()).optional(),order:h.z.string().optional(),pageSize:Ot.max(100).default(20),providerId:h.z.array(h.z.number().int()).optional()}),sT=B($,O,_,C,E);spe=h.z.object({amount:h.z.bigint(),metadata:ur.optional(),recipientAddress:J,tokenAddress:J}),xV=B(E);aT=B(bt,$,O,ue,_,C,E)});var KV={};fr(KV,{AcceptComboQuoteError:()=>IA,ActivityType:()=>p0,ApproveErc1155ForAllError:()=>wv,ApproveErc20Error:()=>bv,ApprovePerpsBuilderFeeError:()=>vx,ArmPerpsAutoCancelError:()=>Px,AssetType:()=>sa,AuthorizeSessionKeyError:()=>$A,AutoCancelDailyLimitError:()=>lf,BiggestWinnerKind:()=>Ql,BuilderVolumeInterval:()=>Kl,CancelAllError:()=>zk,CancelMarketOrdersError:()=>Gk,CancelOrderError:()=>Hk,CancelOrdersError:()=>Vk,CancelledSigningError:()=>bt,CollateralReturnKnownOperationKind:()=>Dd,CombinatorialPrepareConditionCallError:()=>J6,ComboAcceptFailureReason:()=>Ro,ComboActivityType:()=>Wl,ComboKnownStatus:()=>Iw,ComboPositionSortBy:()=>Vl,ComboPositionStatus:()=>ii,ComboQuoteUnavailableReason:()=>ci,CommentParentEntityType:()=>Rh,ConnectionLostError:()=>Yr,CreateLimitOrderError:()=>fx,CreateMarketOrderError:()=>px,CreateSecureClientError:()=>Ame,CtfMergePositionsCallError:()=>G6,CtfRedeemPositionsCallError:()=>K6,CtfSplitPositionCallError:()=>W6,DepositToPerpsError:()=>Gx,DownloadAccountingSnapshotError:()=>aA,DropNotificationsError:()=>j0,Erc20ApprovalCallError:()=>V6,Erc20TransferCallError:()=>j6,EstimateMarketPriceError:()=>Qk,ExecuteCollateralReturnPlanError:()=>ek,FetchBuilderVolumeError:()=>vk,FetchClosedOnlyModeError:()=>D0,FetchCommentsByIdError:()=>ok,FetchEventError:()=>uk,FetchEventLiveVolumeError:()=>gk,FetchEventTagsError:()=>pk,FetchLastTradePriceError:()=>Vv,FetchLastTradePricesError:()=>zv,FetchMarketError:()=>Ck,FetchMarketTagsError:()=>Ok,FetchMidpointError:()=>Rv,FetchMidpointsError:()=>_v,FetchNotificationsError:()=>$0,FetchOpenInterestError:()=>Fk,FetchOrderBookError:()=>Uv,FetchOrderBooksError:()=>Bv,FetchOrderError:()=>F0,FetchOrderScoringError:()=>G0,FetchOrdersScoringError:()=>Y0,FetchPerpsBookError:()=>Dx,FetchPerpsBuilderApprovalsError:()=>Ax,FetchPerpsBuilderEarningsSummaryError:()=>Sx,FetchPerpsBuilderStatusError:()=>bx,FetchPerpsFeesError:()=>Vx,FetchPerpsInstrumentsError:()=>_x,FetchPerpsTickerError:()=>Nx,FetchPerpsTickersError:()=>Lx,FetchPortfolioValueError:()=>rA,FetchPriceError:()=>Nv,FetchPricesError:()=>Lv,FetchPublicProfileError:()=>vA,FetchRelatedTagResourcesError:()=>rT,FetchRelatedTagsError:()=>tT,FetchResolutionsError:()=>hk,FetchRewardPercentagesError:()=>rv,FetchRfqStatusError:()=>OA,FetchSeriesError:()=>FA,FetchSessionKeysError:()=>HA,FetchSportsMarketTypesError:()=>KA,FetchSpreadError:()=>Fv,FetchSpreadsError:()=>Hv,FetchTagError:()=>ZA,FetchTotalEarningsForUserForDayError:()=>Z0,FetchTraderLeaderboardStandingError:()=>Tk,FetchTradingApprovalsStateError:()=>vv,FetchUserPnlError:()=>sA,FetchUserStatsError:()=>oA,FetchUserVolumeError:()=>iA,InsufficientLiquidityError:()=>So,LeaderboardWindow:()=>Gl,ListAccountTradesError:()=>H0,ListActivityError:()=>av,ListBiggestWinnersError:()=>Sk,ListBuilderLeaderboardError:()=>bk,ListBuilderTradesError:()=>Pv,ListComboActivityError:()=>lv,ListComboMarketsError:()=>Ik,ListComboPositionsError:()=>nA,ListCommentsByUserAddressError:()=>ik,ListCommentsError:()=>nk,ListCurrentRewardsError:()=>Gv,ListEventsError:()=>lk,ListMarketHoldersError:()=>Dk,ListMarketRewardsError:()=>Yv,ListMarketsError:()=>Rk,ListOpenOrdersError:()=>B0,ListPerpsBuilderEarningsError:()=>Tx,ListPerpsCandlesError:()=>Bx,ListPerpsFundingHistoryError:()=>Fx,ListPerpsTradesError:()=>Hx,ListPositionsError:()=>tA,ListPriceHistoryError:()=>Bk,ListSeriesError:()=>BA,ListSportsError:()=>WA,ListTagsError:()=>XA,ListTeamsError:()=>sT,ListTraderLeaderboardError:()=>xk,ListTradesError:()=>sv,ListUserEarningsAndMarketsConfigError:()=>tv,ListUserEarningsForDayError:()=>X0,MAX_UINT256:()=>lr,MergePositionsError:()=>jd,NotificationType:()=>t0,OpenPerpsSessionError:()=>zx,OpenRfqSessionError:()=>SA,OperationAbortedError:()=>Xw,OrderPostStatus:()=>n0,OrderResponseErrorCode:()=>r0,OrderSide:()=>Ue,OrderType:()=>cn,PaginationLimitError:()=>Ol,PerpsCancelRetryError:()=>Jw,PerpsDepositCallError:()=>z6,PerpsDepositStatus:()=>Gh,PerpsInstrumentCategory:()=>zh,PerpsInstrumentType:()=>jh,PerpsInternalTransferDirection:()=>Kh,PerpsKlineInterval:()=>Yh,PerpsKnownCancelOrderErrorCode:()=>Sd,PerpsKnownInternalTransferType:()=>qw,PerpsKnownWithdrawalStatus:()=>Fw,PerpsLiquidityRole:()=>Zh,PerpsMarginType:()=>nf,PerpsNotificationOrderType:()=>tf,PerpsNotificationType:()=>ef,PerpsOrderStatus:()=>rf,PerpsSide:()=>Wh,PerpsSortDirection:()=>Qh,PerpsTimeInForce:()=>ti,PlaceLimitOrderError:()=>gx,PlaceMarketOrderError:()=>mx,PlanCollateralReturnError:()=>Jv,PositionFilterType:()=>$l,PositionSortBy:()=>Hl,PositionStatus:()=>ai,PostOrderError:()=>Zk,PostOrdersError:()=>ex,PriceHistoryInterval:()=>Po,ProtocolVersion:()=>ta,RateLimitError:()=>$,RealtimeKnownErrorCode:()=>Ed,RedeemPositionsError:()=>bA,RequestComboQuoteError:()=>EA,RequestRejectedError:()=>O,ResolutionMarketType:()=>Jl,ResolutionReporter:()=>ec,ResolutionSource:()=>Zl,ResolutionStatus:()=>Xl,RevokePerpsBuilderFeeError:()=>Ix,RevokePerpsCredentialsError:()=>Wx,RevokeSessionKeyError:()=>jA,RfqCancelQuoteError:()=>AA,RfqCancelQuoteRejectedError:()=>lc,RfqConfirmationDecision:()=>cs,RfqConfirmationError:()=>TA,RfqConfirmationRejectedError:()=>cc,RfqDirection:()=>Nn,RfqExecutionStatus:()=>us,RfqKnownErrorCode:()=>Cr,RfqQuoteError:()=>xA,RfqQuoteRejectedError:()=>ac,RfqRejectionCode:()=>li,RfqRequestRejectedError:()=>ms,RfqRequestedSizeUnit:()=>Qr,RfqSide:()=>Eo,RfqStatus:()=>mn,RouterMergeCallError:()=>Q6,RouterRedeemCallError:()=>X6,RouterSplitCallError:()=>Y6,SearchError:()=>DA,SearchSort:()=>zd,SessionKeyKnownScope:()=>yo,SetupGaslessWalletError:()=>Tme,SetupTradingApprovalsError:()=>kv,SignatureType:()=>Rr,SignerType:()=>CN,SigningError:()=>ue,SortDirection:()=>Ml,SplitPositionError:()=>Vd,SubscribeError:()=>QA,TeamOrdering:()=>Fh,TimeoutError:()=>tt,TipSide:()=>Bl,TradeFilterType:()=>Fl,TraderLeaderboardSort:()=>Yl,TradingRestriction:()=>PC,TransactionFailedError:()=>en,TransferErc20Error:()=>aT,TransferPerpsCollateralError:()=>Yx,TransportError:()=>_,UnexpectedResponseError:()=>C,UpdatePerpsLeverageError:()=>Ex,UpdatePerpsMarginError:()=>Rx,UserInputError:()=>E,UserPnlFidelity:()=>zl,UserPnlInterval:()=>jl,WaitForComboFillError:()=>CA,WaitForOrderFillSettlementError:()=>ux,WaitForTransactionError:()=>Z6,WalletType:()=>Se,WebSocketKnownCloseCode:()=>SC,WithdrawFromPerpsError:()=>Kx,accountActions:()=>$O,allActions:()=>UV,analyticsActions:()=>VO,authorizeSessionSignerCall:()=>HN,buildHmacSignature:()=>MV,combinatorialPrepareConditionCall:()=>dv,createPublicClient:()=>GV,createSecureClient:()=>Sme,ctfMergePositionsCall:()=>zN,ctfRedeemPositionsCall:()=>WN,ctfSplitPositionCall:()=>jN,dataActions:()=>jO,decodeErc1155BalanceOfBatchResult:()=>Rf,decodeErc1155BalanceOfResult:()=>qN,decodeErc1155IsApprovedForAllResult:()=>MN,decodeErc20AllowanceResult:()=>UN,discoveryActions:()=>zO,encodeProxyCall:()=>KN,encodeSafeMultisendCall:()=>YN,erc1155ApprovalForAllCall:()=>bf,erc1155BalanceOfBatchCall:()=>Ef,erc1155BalanceOfCall:()=>FN,erc1155IsApprovedForAllCall:()=>BN,erc20AllowanceCall:()=>DN,erc20ApprovalCall:()=>yf,erc20TransferCall:()=>S0,expectTransactionHandle:()=>bn,forkEnvironmentConfig:()=>BV,makeErrorGuard:()=>B,perpsActions:()=>WO,perpsDepositCall:()=>VN,preproduction:()=>gpe,production:()=>QO,relayerApiKey:()=>cpe,remoteBuilderSigning:()=>lpe,revokeSessionSignerCall:()=>$N,rewardsActions:()=>GO,rfqActions:()=>OV,routerMergeCall:()=>uv,routerRedeemCall:()=>wf,routerSplitCall:()=>cv,sessionKeyActions:()=>LV,subscriptionsActions:()=>KO,tradingActions:()=>DV,walletActions:()=>YO});function lpe(e){return new upe(e)}function cpe(e){return new dpe(e)}function ppe(e){let t={chainId:e.chainId,name:"ClobAuthDomain",version:"1"};return{domain:t,message:{address:e.address,message:"This message attests that I control the given wallet",nonce:e.nonce??0,timestamp:`${e.timestamp}`},primaryType:"ClobAuth",types:{EIP712Domain:fo.extractEip712DomainTypes(t),ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function mpe(e){return{listPositions:$f.bind(null,e),listComboPositions:Vf.bind(null,e),fetchPortfolioValue:jf.bind(null,e),fetchTraderLeaderboardStanding:Df.bind(null,e),fetchUserStats:zf.bind(null,e),fetchUserPnl:Wf.bind(null,e),fetchUserVolume:Gf.bind(null,e),downloadAccountingSnapshot:Kf.bind(null,e),listActivity:Sf.bind(null,e),listComboActivity:Pf.bind(null,e)}}function hs(e,t={}){return t===null||typeof t!="object"||Array.isArray(t)?t:{...t,user:t.user===void 0?e.account.wallet:t.user}}function $O(e){let t=mpe(e);return e.isPublicClient()?t:{...t,listPositions:n=>$f(e,hs(e,n)),listComboPositions:n=>Vf(e,hs(e,n)),fetchPortfolioValue:n=>jf(e,hs(e,n)),fetchTraderLeaderboardStanding:n=>Df(e,hs(e,n)),fetchUserStats:n=>zf(e,hs(e,n)),fetchUserPnl:n=>Wf(e,hs(e,n)),fetchUserVolume:n=>Gf(e,hs(e,n)),downloadAccountingSnapshot:n=>Kf(e,hs(e,n)),listActivity:n=>Sf(e,hs(e,n)),listComboActivity:n=>Pf(e,hs(e,n)),listAccountTrades:Tf.bind(null,e),fetchNotifications:V0.bind(null,e),dropNotifications:z0.bind(null,e),fetchClosedOnlyMode:U0.bind(null,e)}}function VO(e){return{listBuilderTrades:Ev.bind(null,e),listBuilderLeaderboard:wk.bind(null,e),fetchBuilderVolume:kk.bind(null,e),listTraderLeaderboard:Ak.bind(null,e),listBiggestWinners:Pk.bind(null,e)}}function jO(e){return{fetchEventLiveVolume:yk.bind(null,e),fetchResolutions:fk.bind(null,e),fetchMidpoint:Iv.bind(null,e),fetchMidpoints:Cv.bind(null,e),fetchPrice:Ov.bind(null,e),fetchPrices:Dv.bind(null,e),fetchOrderBook:Hd.bind(null,e),fetchOrderBooks:Mv.bind(null,e),fetchSpread:qv.bind(null,e),fetchSpreads:$v.bind(null,e),fetchLastTradePrice:jv.bind(null,e),fetchLastTradePrices:Wv.bind(null,e),listPriceHistory:Mk.bind(null,e),estimateMarketPrice:Xk.bind(null,e),fetchOpenInterest:qk.bind(null,e),listMarketHolders:Uk.bind(null,e),listTrades:iv.bind(null,e)}}function zO(e){return{listEvents:ck.bind(null,e),fetchEvent:dk.bind(null,e),fetchEventTags:mk.bind(null,e),listMarkets:Uf.bind(null,e),listComboMarkets:_k.bind(null,e),fetchMarket:Nk.bind(null,e),fetchMarketTags:Lk.bind(null,e),listSeries:MA.bind(null,e),fetchSeries:qA.bind(null,e),listMarketClarifications:Ek.bind(null,e),listTags:JA.bind(null,e),fetchTag:eT.bind(null,e),fetchRelatedTags:nT.bind(null,e),fetchRelatedTagResources:oT.bind(null,e),search:UA.bind(null,e),listSports:GA.bind(null,e),fetchSportsMarketTypes:YA.bind(null,e),listTeams:iT.bind(null,e),fetchPublicProfile:kA.bind(null,e),listComments:rk.bind(null,e),fetchCommentsById:sk.bind(null,e),listCommentsByUserAddress:ak.bind(null,e)}}function WO(e){let t={fetchPerpsBuilderStatus:wx.bind(null,e),fetchPerpsBook:n=>Ux(e,n),fetchPerpsFees:()=>jx(e),fetchPerpsInstruments:n=>Cx(e,n),fetchPerpsTicker:n=>Ox(e,n),fetchPerpsTickers:n=>Hf(e,n),listPerpsCandles:n=>Mx(e,n),listPerpsFundingHistory:n=>qx(e,n),listPerpsTrades:n=>$x(e,n)};return e.isSecureClient()?{...t,depositToPerps:n=>Jx(e,n),openPerpsSession:n=>Qx(e,n),revokePerpsCredentials:n=>Xx(e,n),transferPerpsCollateral:eA.bind(null,e),withdrawFromPerps:n=>Zx(e,n)}:t}function hpe(e){return{listCurrentRewards:Kv.bind(null,e),listMarketRewards:Qv.bind(null,e)}}function GO(e){let t=hpe(e);return e.isPublicClient()?t:{...t,fetchOrderScoring:K0.bind(null,e),fetchOrdersScoring:Q0.bind(null,e),listUserEarningsForDay:J0.bind(null,e),fetchTotalEarningsForUserForDay:ev.bind(null,e),listUserEarningsAndMarketsConfig:nv.bind(null,e),fetchRewardPercentages:ov.bind(null,e)}}function OV(e){return{openRfqSession(){return PA(e)},requestComboQuote(t){return RA(e,t)},acceptComboQuote(t){return _A(e,t)},waitForComboFill(t){return NA(e,t)}}}function LV(e){return{authorizeSessionKey:VA.bind(null,e),fetchSessionKeys:Wd.bind(null,e),revokeSessionKey:zA.bind(null,e)}}function KO(e){return e.isSecureClient()?{subscribe(t){return Qf(e,t)}}:{subscribe(t){return Qf(e,t)}}}function DV(e){return{createMarketOrder:Mf.bind(null,e),placeMarketOrder:hx.bind(null,e),createLimitOrder:Ff.bind(null,e),placeLimitOrder:yx.bind(null,e),postOrder:$d(e),postOrders:tx(e),waitForOrderFillSettlement:dx.bind(null,e),cancelOrder:$k.bind(null,e),cancelOrders:jk.bind(null,e),cancelAll:Wk.bind(null,e),cancelMarketOrders:Kk.bind(null,e),listOpenOrders:M0.bind(null,e),fetchOrder:q0.bind(null,e)}}function fpe(e){return{fetchTradingApprovalsState:Lf.bind(null,e)}}function YO(e){let t=fpe(e);return e.isPublicClient()?t:{...t,fetchTradingApprovalsState:()=>Lf(e,{user:e.account.wallet}),setupTradingApprovals:xv.bind(null,e),approveErc20:Nf.bind(null,e),approveErc1155ForAll:Of.bind(null,e),transferErc20:lT.bind(null,e),splitPosition:dA.bind(null,e),mergePositions:fA.bind(null,e),redeemPositions:wA.bind(null,e),planCollateralReturn:Zv.bind(null,e),executeCollateralReturnPlan:tk.bind(null,e)}}function UV(e){return e.isSecureClient()?{...$O(e),...VO(e),...jO(e),...zO(e),...WO(e),...GO(e),...OV(e),...LV(e),...KO(e),...DV(e),...YO(e)}:{...$O(e),...VO(e),...jO(e),...zO(e),...WO(e),...GO(e),...KO(e),...YO(e)}}function BV(e,t=QO){return{...t,...e,walletDerivation:{...t.walletDerivation,...e.walletDerivation},contracts:{...t.contracts,...e.contracts},clob:{...Gd(t.clob,e.clob),market:Xf(t.clob.market,e.clob?.market),user:Xf(t.clob.user,e.clob?.user)},relayer:Gd(t.relayer,e.relayer),gamma:Gd(t.gamma,e.gamma),data:Gd(t.data,e.data),combos:{...AV(t.combos,e.combos),builderGateway:Gd(t.combos.builderGateway,e.combos?.builderGateway),collateralReturn:Gd(t.combos.collateralReturn,e.combos?.collateralReturn)},perps:AV(t.perps,e.perps),realtime:Xf(t.realtime,e.realtime),rtds:Xf(t.rtds,e.rtds),sports:Xf(t.sports,e.sports)}}function Gd(e,t){return{...e,...t,headers:XO(e.headers,t?.headers)}}function Xf(e,t){return{...e,...t,headers:XO(e.headers,t?.headers)}}function AV(e,t){return{...e,...t,headers:XO(e.headers,t?.headers)}}function XO(e,t){if(!(e===void 0&&t===void 0))return{...e,...t}}async function MV(e,t,n,r,o){let s=`${t}${n}${r}`;o!==void 0&&(s+=o);let i=await globalThis.crypto.subtle.importKey("raw",ype(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(s));return wpe(bpe(a))}function ype(e){let t=e.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)r[o]=n.charCodeAt(o);return r.buffer}function bpe(e){let t=new Uint8Array(e),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function wpe(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}function Zf(e,t){let n;return{close:()=>(n===void 0&&(n=Promise.resolve(e.return()).then(()=>t())),n),[Symbol.asyncIterator](){return e[Symbol.asyncIterator]()}}}function TV(e,t,n){let r=dT(n.assetsIds,t.assetsIds),o=dT(t.assetsIds,n.assetsIds);r.length>0&&e(PV(r,n.customFeatureEnabled));let s=n.assetsIds[0];r.length===0&&t.customFeatureEnabled!==n.customFeatureEnabled&&s!==void 0&&e(PV([s],n.customFeatureEnabled)),o.length>0&&e(Ape(o))}function SV(e,t,n){if(n.includeAllMarkets){!t.includeAllMarkets&&t.markets.length>0&&e(RV(t.markets));return}if(t.includeAllMarkets){n.markets.length>0&&e(EV(n.markets));return}let r=dT(n.markets,t.markets),o=dT(t.markets,n.markets);r.length>0&&e(EV(r)),o.length>0&&e(RV(o))}function vpe(e){let t=new Set,n=!1;for(let{subscription:r}of e){for(let o of r.assetIds??r.tokenIds)t.add(o);n||=r.customFeatureEnabled===!0}return{assetsIds:Array.from(t),customFeatureEnabled:n}}function kpe(e){let t=!1,n=new Set;for(let{subscription:r}of e){if(FV(r)){t=!0;continue}for(let o of r.markets??[])n.add(o)}return{includeAllMarkets:t,markets:t?[]:Array.from(n)}}function xpe(e){return{assets_ids:e.assetsIds,custom_feature_enabled:e.customFeatureEnabled,type:"market"}}function PV(e,t){return{assets_ids:e,custom_feature_enabled:t,operation:"subscribe"}}function Ape(e){return{assets_ids:e,operation:"unsubscribe"}}function Tpe(e,t){let n={auth:{apiKey:t.key,passphrase:t.passphrase,secret:t.secret},type:"user"};return e.includeAllMarkets||(n.markets=e.markets),n}function EV(e){return{markets:e,operation:"subscribe"}}function RV(e){return{markets:e,operation:"unsubscribe"}}function Spe(e){let t=e.assetIds??e.tokenIds;return n=>{switch(n.type){case"price_change":return n.payload.priceChanges.some(r=>t.includes(r.assetId));case"new_market":return e.customFeatureEnabled===!0;case"market_resolved":return e.customFeatureEnabled===!0&&(n.payload.assetIds??[]).some(r=>t.includes(r));case"best_bid_ask":return e.customFeatureEnabled===!0&&t.includes(n.payload.assetId);default:return t.includes(n.payload.assetId)}}}function Ppe(e){if(FV(e))return()=>!0;let t=new Set((e.markets??[]).map(n=>n.toLowerCase()));return n=>t.has(n.payload.market.toLowerCase())}function FV(e){return(e.markets?.length??0)===0}function dT(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}function Ipe(e){let t=new Set,n=new Set,r=new Set,o=!1,s=!1;for(let{subscription:i}of e)switch(i.topic){case"perps.tickers":i.instrumentId===void 0?o=!0:n.add(i.instrumentId);break;case"perps.statistics":i.instrumentId===void 0?s=!0:r.add(i.instrumentId);break;default:t.add(_pe(i))}if(o)t.add("tickers::all");else for(let i of n)t.add(`tickers::${i}`);if(s)t.add("statistics::all");else for(let i of r)t.add(`statistics::${i}`);return t}function IV(e,t){return Array.from(t).filter(n=>!e.has(n))}function _V(e,t){return Array.from(e).filter(n=>!t.has(n))}function _pe(e){switch(e.topic){case"perps.trades":return`trades::${e.instrumentId}`;case"perps.bbo":return`bbo::${e.instrumentId}`;case"perps.book":return`book::${e.instrumentId}`;case"perps.candles":return`klines::${e.instrumentId}::${e.interval}`;case"perps.tickers":return e.instrumentId===void 0?"tickers::all":`tickers::${e.instrumentId}`;case"perps.statistics":return e.instrumentId===void 0?"statistics::all":`statistics::${e.instrumentId}`;default:ge(!1,`Unknown Perps topic: ${String(e)}`)}}function Cpe(e){switch(e.topic){case"perps.trades":return t=>t.topic==="perps.trades"&&t.channel===`trades::${e.instrumentId}`;case"perps.bbo":case"perps.book":return t=>t.topic===e.topic&&t.payload.instrumentId===e.instrumentId;case"perps.candles":return t=>t.topic==="perps.candles"&&t.payload.instrumentId===e.instrumentId&&t.payload.interval===e.interval;case"perps.tickers":case"perps.statistics":return t=>t.topic===e.topic&&(e.instrumentId===void 0||t.payload.instrumentId===e.instrumentId);default:ge(!1,`Unknown Perps topic: ${String(e)}`)}}function Npe(e){if(e.topic==="prices.equity"){let t=e.symbol.toLowerCase();return[{key:JSON.stringify([e.topic,t]),topic:e.topic,symbol:t}]}return e.symbols.map(t=>e.topic==="prices.crypto.twap"?{key:JSON.stringify([e.topic,t,60]),topic:e.topic,symbol:t,windowSeconds:60}:{key:JSON.stringify([e.topic,t]),topic:e.topic,symbol:t})}function Ope(e,t){return Math.random()*(e===4003?1e4:Math.min(1e3*2**t,3e4))}function Dpe(e){return new Promise((t,n)=>{let r=gn(()=>{n(new _("Realtime subscription was not accepted within 30 seconds."))},3e4);e.then(()=>{clearTimeout(r),t()},o=>{clearTimeout(r),n(o)})})}function Upe(e,t){if(t.type==="subscribe")return t;let n=e?.type==="subscribe"?e.payload.data:[],{symbol:r,timestamp:o,value:s}=t.payload;if((n.at(-1)?.timestamp??0)>o)return e;let i=[...n.filter(a=>a.timestamp>o-12e4&&a.timestamp<o),{timestamp:o,value:s}];return t.topic==="prices.crypto.twap"?{...t,type:"subscribe",payload:{symbol:r,data:i,windowSeconds:t.payload.windowSeconds}}:{...t,type:"subscribe",payload:{symbol:r,data:i}}}function Mpe(e){switch(e.topic){case"prices.crypto":return{channel:Rd.Crypto,filter:{symbol:e.symbol}};case"prices.crypto.twap":return{channel:Rd.Twap,filter:{symbol:e.symbol,window_seconds:e.windowSeconds}};case"prices.equity":return{channel:Rd.Equity,filter:{symbol:e.symbol}}}}function Hpe(e,t){return{...t,quote:n=>e.quote(t,n)}}function $pe(e,t){let n=t.rfqId,r=t.quoteId;return{...t,confirm:()=>e.respondToConfirmation(n,r,cs.Confirm),decline:()=>e.respondToConfirmation(n,r,cs.Decline)}}function Vpe(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function jpe(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function zpe(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function Wpe(e,t){let n=oc(e);return{auth:{apiKey:t.key,passphrase:t.passphrase,secret:t.secret},identity:{maker_address:n.maker,signature_type:n.signatureType,signer_address:n.signer},type:"auth"}}function Gpe(e,t){return{price_e6:t.price.toString(),rfq_id:e.rfqId,signed_order:t.signedOrder,size_e6:t.size.toString(),type:"RFQ_QUOTE"}}function Kpe(e,t,n){let r=oc(e);return{maker_address:r.maker,quote_id:n,rfq_id:t,signer_address:r.signer,type:"RFQ_QUOTE_CANCEL"}}function Ype(e,t,n){return{decision:n,quote_id:t,rfq_id:e,type:"RFQ_CONFIRMATION_RESPONSE"}}function Xpe(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}async function Jpe(e){let t=oc(e.account),n=gO({chainId:e.chainId,exchange:e.exchange}),r={builder:CV,maker:t.maker,makerAmount:c5(e.orderSide,e.orderPrice,e.size),metadata:CV,salt:Zpe().toString(),side:ix(e.orderSide),signatureType:t.signatureType,signer:t.signer,takerAmount:u5(e.orderSide,e.orderPrice,e.size),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:e.tokenId},o;try{o=await e.signer.signTypedData(ox({domain:n,order:r}))}catch(s){throw ue.fromError(s,"Could not sign the RFQ quote order.")}return{...r,signature:sx({domain:n,order:r,signature:o})}}function Zpe(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)}function tme(e){return F(e,eme)}async function nme(e){let t=e.response.price,n=e.response.size===void 0?ime(e.request.requestedSize,t):e.response.size,r=await Jpe({account:e.account,chainId:e.chainId,exchange:e.exchange,orderPrice:ome(e.request,e.response.source,t),orderSide:sme(e.response.source),signer:e.signer,size:n,tokenId:rme(e.request,e.response.source)});return{price:t,signedOrder:r,size:n}}function rme(e,t){return e.direction===Nn.Buy?t==="collateral"?e.noPositionId:e.yesPositionId:t==="collateral"?e.yesPositionId:e.noPositionId}function ome(e,t,n){return e.direction===Nn.Buy&&t==="collateral"||e.direction===Nn.Sell&&t==="inventory"?1000000n-n:n}function sme(e){return e==="collateral"?Ue.BUY:Ue.SELL}function ime(e,t){let n=$V(e.value);return e.unit===Qr.Shares?n:n*1000000n/t}function $V(e){let t=/^(\d+)(?:\.(\d*))?$/.exec(e);if(t===null)throw new E("Value must be a valid decimal.");let[,n="",r=""]=t;if(r.length>6)throw new E("Value must have at most 6 decimal places.");let o=BigInt(n)*1000000n+BigInt(r.padEnd(6,"0"));if(o<=0n)throw new E("Value must be greater than 0.");return o}function uT(e){return`ACK_RFQ_QUOTE:${e}`}function qO(e,t){return`ACK_RFQ_QUOTE_CANCEL:${e}:${t}`}function HO(e,t){return`ACK_RFQ_CONFIRMATION_RESPONSE:${e}:${t}`}function dme(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}function pme(e,t){return Array.from(t).flatMap(([n,r])=>e.has(n)?[]:[r])}function mme(e,t){return Array.from(e).flatMap(([n,r])=>t.has(n)?[]:[r])}function hme(e){let t=new Map;for(let{subscription:n}of e)for(let r of yme(n))t.has(r.key)||t.set(r.key,r);return t}function fme(e){return{action:"subscribe",subscriptions:e.map(({topic:t,type:n})=>({topic:t,type:n}))}}function gme(e){return{action:"unsubscribe",subscriptions:e.map(({topic:t,type:n})=>({topic:t,type:n}))}}function yme(e){switch(e.topic){case"comments":return(e.types??["comment_created"]).map(t=>Jf("comments",t));case"prices.crypto.binance":return[Jf("crypto_prices","update")];case"prices.crypto.chainlink":return[Jf("crypto_prices_chainlink","update")];case"prices.crypto.chainlink.twap":return[Jf(bme(e.windowSeconds),"update")];case"prices.equity.pyth":return[Jf("equity_prices","update")];default:ge(!1,`Unknown RTDS topic: ${String(e)}`)}}function bme(e){switch(e){case 30:return"crypto_prices_twap_thirty";case 60:return"crypto_prices_twap_sixty";default:ge(!1,`Unknown TWAP window: ${String(e)}`)}}function Jf(e,t){return{key:`${e}:${t}`,topic:e,type:t}}function wme(e){switch(e.topic){case"comments":return t=>!(t.topic!=="comments"||e.types!==void 0&&e.types.length>0&&!e.types.includes(t.type)||(e.parentEntityId!==void 0||e.parentEntityType!==void 0)&&(!(t.type==="comment_created"||t.type==="comment_removed")||e.parentEntityId!==void 0&&t.payload.parentEntityID!==e.parentEntityId||e.parentEntityType!==void 0&&t.payload.parentEntityType!==e.parentEntityType));case"prices.crypto.binance":return t=>t.topic==="prices.crypto.binance"&&(e.symbols===void 0||e.symbols.length===0||e.symbols.includes(t.payload.symbol));case"prices.crypto.chainlink":return t=>t.topic==="prices.crypto.chainlink"&&(e.symbols===void 0||e.symbols.length===0||e.symbols.includes(t.payload.symbol));case"prices.crypto.chainlink.twap":return t=>t.topic==="prices.crypto.chainlink.twap"&&t.payload.windowSeconds===e.windowSeconds&&(e.symbols===void 0||e.symbols.length===0||e.symbols.includes(t.payload.symbol));case"prices.equity.pyth":return t=>t.topic==="prices.equity.pyth"&&t.payload.symbol.toLowerCase()===e.symbol.toLowerCase()&&(e.types===void 0||e.types.length===0||e.types.includes(t.type));default:ge(!1,`Unknown RTDS topic: ${String(e)}`)}}function GV(e={}){return new WV({environment:e.environment??QO,apiKey:e.apiKey,onRateLimitUpdate:e.onRateLimitUpdate}).extend(UV)}async function Sme(e){let t=GV({environment:e.environment,apiKey:e.apiKey,onRateLimitUpdate:e.onRateLimitUpdate}),n=await Pme(t,e),r=await t.beginAuthentication({wallet:n,credentials:e.credentials,nonce:e.nonce},e.signer).then(e8(e.signer));if(r.account.walletType===Se.EOA||await _f(r,{wallet:r.account.wallet,type:r.account.walletType}))return r;if(r.account.walletType===Se.DEPOSIT_WALLET)return await Eme(r),r;throw new E(`Wallet ${r.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function Pme(e,t){if(t.wallet!==void 0)return t.wallet;let n=Be(await t.signer.getAddress()),r=O0(n,e.environment.walletDerivation);return await _f(e,{wallet:r,type:Se.DEPOSIT_WALLET})?r:Af(n,e.environment.walletDerivation)}async function Eme(e){let t=Af(e.account.signer,e.environment.walletDerivation);if(!Wt(e.account.wallet,t))throw new E(`Wallet ${e.account.wallet} does not match the expected Deposit Wallet ${t} for this signer, nor a deployed wallet address.`);await(await pv(e)).wait()}var Lr,ape,upe,dpe,QO,gpe,eg,qV,Epe,Rpe,HV,Lpe,Bpe,Fpe,qpe,Qpe,CV,NV,eme,ame,lme,cme,ume,VV,jV,zV,vme,kme,WV,xme,Ame,Tme,YV=L(()=>{"use strict";cT();cT();Zw();Zw();cf();cf();OC();h0();o0();o0();rN();Lr=require("zod");Tl();hw();Qw();lN();g0();ape=Lr.z.object({POLY_BUILDER_API_KEY:Lr.z.string().min(1),POLY_BUILDER_TIMESTAMP:Lr.z.string().min(1),POLY_BUILDER_PASSPHRASE:Lr.z.string().min(1),POLY_BUILDER_SIGNATURE:Lr.z.string().min(1)});upe=class{#e;constructor(e){this.#e=e}get isBuilderKey(){return!0}get supportGasless(){return!0}async authorize(e){try{return await this.#r(e)}catch(t){throw ue.fromError(t,"Could not authorize the builder-authenticated request")}}async#t(){let e=this.#e.headers,t=typeof e=="function"?await e():e,n=new Headers(t);return n.set("content-type","application/json"),n}async#r(e){let t=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#t(),method:"POST",mode:"cors"});if(!t.ok)throw new Error(`Remote signer rejected request with status ${t.status}`);return ape.parse(await t.json())}},dpe=class{#e;constructor(e){this.#e=e}get isBuilderKey(){return!1}get supportGasless(){return!0}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};QO={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:Be("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:Be("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:Be("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:Be("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:Be("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:Be("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},contracts:{collateralToken:Be("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:Be("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:Be("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:Be("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:Be("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:Be("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:Be("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:Be("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:Be("0x12121212006e4CD160D18e3f00711DA5c3372600"),binaryModule:Be("0x1000008dD9001B968442c1000017eaE6E0dA00Ba"),negRiskModule:Be("0x200000900045e3B6259600682756002200028933"),combinatorialModule:Be("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:Be("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:Be("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:Be("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:Be("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),perpsDepositContract:Be("0xDCa4af75705dbB50f62437045afF9921947917d2")},clob:{rest:"https://clob.polymarket.com",market:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/market"},user:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/user"}},relayer:{rest:"https://relayer-v2.polymarket.com"},gamma:{rest:"https://gamma-api.polymarket.com"},data:{rest:"https://data-api.polymarket.com"},combos:{rest:"https://combos-rfq-api.polymarket.com",ws:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq",builderGateway:{rest:"https://combos-rfq-gateway-builder.polymarket.com"},collateralReturn:{rest:"https://combos-rfq-collateral-return.polymarket.com"}},perps:{rest:"https://api.perpetuals.polymarket.com",ws:"wss://ws.perpetuals.polymarket.com/v1/ws"},realtime:{ws:"wss://ws-live-v2.polymarket.com/ws"},rtds:{ws:"wss://ws-live-data.polymarket.com"},sports:{ws:"wss://sports-api.polymarket.com/ws"},relayerMaxPolls:100,relayerPollFrequencyMs:2e3};gpe=BV({name:"preproduction",clob:{rest:"https://clob-preprod-int-v2.polymarket.com"},data:{rest:"https://data-api-preprod-int.polymarket.com"},gamma:{rest:"https://gamma-api-preprod-int.polymarket.com"},relayer:{rest:"https://relayer-v2-preprod-int.polymarket.com"}});eg=class{#e=new Set;#t;constructor(e){this.#t=e?.deriveServerState??(()=>{})}add(e,t={}){let n={queue:Bd({objectMode:!0})};t.matches!==void 0&&(n.matches=t.matches);let r={subscription:e,subscriber:n};return{change:this.#r(r),entry:r}}#r(e){let t=this.serverState();return this.#e.add(e),{before:t,after:this.serverState()}}remove(e){let t=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:t,after:this.serverState()}}dispatch(e){for(let{subscriber:t}of this.#e)(t.matches===void 0||t.matches(e))&&t.queue.push(e)}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:t}of this.#e)t.queue.end(e);this.#e.clear()}serverState(){return this.#t(this.#e)}};qV=class{#e;#t;#r;#s=new mi({heartbeat:new kO});#n=new ua;#o=new eg({deriveServerState:vpe});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#o.add(e,{matches:Spe(e)});return await this.#i(n,t),Zf(n.subscriber.queue,()=>this.#a(n))}async#i(e,t){let{before:n,after:r}=t;try{(await this.#l()).reusedOpenSocket&&TV(o=>this.#s.send(o),n,r)}catch(o){throw await this.#a(e),o}}async#a(e){let{before:t,after:n}=this.#o.remove(e);if(!this.#o.hasActiveSubscriptions()){await this.close();return}TV(r=>this.#s.send(r),t,n)}async close(){this.#r===void 0&&(this.#r=this.#u().finally(()=>{this.#r=void 0})),await this.#r}async#u(){this.#n.stop(),this.#o.endAll(),await this.#s.close()}#l(){return this.#s.connect({onConnectionLost:()=>this.#d(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#t})}#c(){this.#n.resetBackoff(),this.#y()}#p(e){let t=Array.isArray(e)?e:[e];for(let n of t){let r=RH.safeParse(n);r.success&&this.#o.dispatch(r.data)}}#d(){this.#o.hasActiveSubscriptions()&&this.#h()}#m(){}#y(){this.#s.send(xpe(this.#o.serverState()))}#h(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}},Epe=class{#e;#t;#r;#s;#n=new mi({heartbeat:new kO});#o=new ua;#i=new eg({deriveServerState:kpe});constructor(e){this.#e=e.credentials,this.#t=e.headers,this.#r=e.url}async subscribe(e){let{change:t,entry:n}=this.#i.add(e,{matches:Ppe(e)});return await this.#a(n,t),Zf(n.subscriber.queue,()=>this.#u(n))}async#a(e,t){let{before:n,after:r}=t;try{(await this.#c()).reusedOpenSocket&&SV(o=>this.#n.send(o),n,r)}catch(o){throw await this.#u(e),o}}async#u(e){let{before:t,after:n}=this.#i.remove(e);if(!this.#i.hasActiveSubscriptions()){await this.close();return}SV(r=>this.#n.send(r),t,n)}async close(){this.#s===void 0&&(this.#s=this.#l().finally(()=>{this.#s=void 0})),await this.#s}async#l(){this.#o.stop(),this.#i.endAll(),await this.#n.close()}#c(){return this.#n.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#d(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#t,url:this.#r})}#p(e){this.#o.resetBackoff(),this.#h(e)}#d(e){let t=Array.isArray(e)?e:[e];for(let n of t){let r=IH.safeParse(n);r.success&&this.#i.dispatch(r.data)}}#m(){this.#i.hasActiveSubscriptions()&&this.#f()}#y(){}#h(e){this.#n.send(Tpe(this.#i.serverState(),e))}#f(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()})}},Rpe=class{#e;#t;#r;#s;#n=new Set;#o=new Set;#i=new Set;#a=!1;constructor(e){this.#e=e.chainId,this.#t=e.headers,this.#r=e.restUrl,this.#s=e.wsUrl}connect(e,t,n,r){if(this.#a)return Promise.reject(new _("Perps session manager has been shut down."));let o=new M5({builderAttribution:t,approveBuilderFee:n,includeBuilderFills:r,chainId:this.#e,credentials:e,headers:this.#t,onClose:i=>this.#u(i),restUrl:this.#r,wsUrl:this.#s});this.#o.add(o);let s;return s=(async()=>{try{if(await o.connect(),this.#a)throw await o.close(),new _("Perps session manager has been shut down.");return this.#n.add(o),o}catch(i){throw await o.close(),i}finally{this.#i.delete(s),this.#o.delete(o)}})(),this.#i.add(s),s}async shutdown(){this.#a=!0;let e=Array.from(this.#n),t=Array.from(this.#o),n=Array.from(this.#i);this.#n.clear(),this.#o.clear(),this.#i.clear(),await Promise.allSettled([...e.map(r=>r.close()),...t.map(r=>r.close()),...n.map(r=>r.catch(()=>{}))]).then(()=>{})}#u(e){this.#n.delete(e),this.#o.delete(e)}},HV=class{#e;#t;#r;#s=1;#n=new mi({heartbeat:new xO});#o=new ua;#i=new eg({deriveServerState:Ipe});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#i.add(e,{matches:Cpe(e)});return await this.#a(n,t),Zf(n.subscriber.queue,()=>this.#u(n))}async#a(e,t){try{(await this.#c()).reusedOpenSocket&&(this.#h(IV(t.before,t.after)),this.#f(_V(t.before,t.after)))}catch(n){throw await this.#u(e),n}}async#u(e){let{before:t,after:n}=this.#i.remove(e);this.#h(IV(t,n)),this.#f(_V(t,n)),this.#i.hasActiveSubscriptions()||await this.close()}async close(){this.#r===void 0&&(this.#r=this.#l().finally(()=>{this.#r=void 0})),await this.#r}async#l(){this.#o.stop(),this.#i.endAll(),await this.#n.close()}#c(){return this.#n.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#d(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#t})}#p(){this.#o.resetBackoff(),this.#h(Array.from(this.#i.serverState()))}#d(e){let t=CH.safeParse(e);t.success&&this.#i.dispatch(t.data)}#m(){this.#i.hasActiveSubscriptions()&&this.#b()}#y(){}#h(e){e.length!==0&&this.#n.send(this.#g("sub",e))}#f(e){e.length!==0&&this.#n.send(this.#g("unsub",e))}#g(e,t){return{id:this.#s++,req:e,chs:t}}#b(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()})}};Lpe=class{#e;#t=new ua;#r=new Map;#s=[];#n;#o;#i=!1;#a=!1;#u=!1;#l=!1;#c;#p=0;#d=64;#m=Number.NEGATIVE_INFINITY;constructor(e){this.#e=e}get size(){return this.#r.size}has(e){return this.#r.has(e)}get closed(){return this.#a}get keyTarget(){return Date.now()-this.#m>=6e4?64:this.#d}add(e,t){clearTimeout(this.#o);let n=this.#r.get(e.key);if(n===void 0){let{promise:r,resolve:o,reject:s}=Promise.withResolvers();r.catch(()=>{}),n={subscription:e,listeners:new Set,ready:r,resolve:o,reject:s,subscribed:!1,accepted:!1},this.#r.set(e.key,n),this.#i&&this.#f("subscribe",[n])}return n.listeners.add(t),n.snapshot!==void 0&&t.event(n.snapshot),!this.#i&&!this.#l&&this.#c===void 0&&!this.#t.isScheduled&&this.#y(),Dpe(n.ready)}remove(e,t){let n=this.#r.get(e);n!==void 0&&(n.listeners.delete(t),!(n.listeners.size>0)&&(this.#r.delete(e),n.reject(new _("Realtime subscription closed.")),this.#i&&this.#f("unsubscribe",[n]),this.#r.size===0&&(this.#o=gn(()=>{this.close()},1e3))))}#y(){if(this.#a||this.#l)return Promise.resolve();if(this.#c!==void 0)return this.#c;let e=this.#h().catch(t=>{this.#S([...this.#r.values()].filter(n=>!n.accepted),_.fromError(t))}).finally(()=>{this.#c===e&&(this.#c=void 0),this.#i||this.#w(1006)});return this.#c=e,e}async#h(){let e=this.#p;if(await this.#e.open({event:t=>this.#x(t),dropped:()=>this.#A(),disconnected:t=>this.#T(t)}),!(this.#a||e!==this.#p))try{if(await this.#e.authorize(),this.#a||e!==this.#p)return;this.#i=!0,this.#f("subscribe",[...this.#r.values()])}catch(t){if(this.#a||e!==this.#p)return;t instanceof O&&t.code!==Ed.AuthUnavailable?this.#P(t):await this.#k(1006)}}#f(e,t){if(t.length===0)return;let n=this.#s.at(-1);n?.op===e?n.keys.push(...t):this.#s.push({op:e,keys:t}),this.#g()}#g(){this.#n!==void 0||this.#u||!this.#i||this.#a||(this.#n=gn(()=>{this.#n=void 0,this.#b()},10))}async#b(){if(!this.#i||this.#a)return;let e=this.#s.shift();if(e===void 0)return;let t=[...new Set(e.keys)].filter(r=>e.op==="unsubscribe"||this.#r.get(r.subscription.key)===r);if(t.length===0){this.#g();return}let n=this.#p;this.#u=!0;try{let r=await this.#e.change(e.op,t.map(({subscription:o})=>o));if(n!==this.#p||this.#a)return;if(e.op==="unsubscribe"&&r.length>0){let o=r[0];if(o!==void 0)throw o.error}if(e.op==="subscribe"){this.#t.resetBackoff();let o=new Set(r.map(s=>s.key));for(let s of t)o.has(s.subscription.key)||(s.subscribed=!0,s.accepted=!0,s.resolve());for(let{key:s,error:i}of r){let a=t.find(l=>l.subscription.key===s);a!==void 0&&this.#S([a],i,!1)}}}catch(r){if(n!==this.#p||this.#a)return;r instanceof O&&e.op==="subscribe"?this.#S(t,r):await this.#k(1006)}finally{this.#u=!1,this.#g()}}#x(e){for(let t of this.#r.values()){let n=t.subscription;if(n.topic!==e.topic)continue;let r=e.payload;if(r.symbol.toLowerCase()===n.symbol&&!(n.topic==="prices.crypto.twap"&&(!("windowSeconds"in r)||r.windowSeconds!==n.windowSeconds))){t.snapshot=Upe(t.snapshot,e);for(let o of t.listeners)o.event(e)}}}#A(){let e=Date.now();e-this.#m<5e3||(this.#d=Math.max(1,Math.floor(this.keyTarget/2)),this.#m=e)}#v(){this.#p++,this.#i=!1,this.#s=[],clearTimeout(this.#n),this.#n=void 0;for(let e of this.#r.values()){if(e.snapshot=void 0,!e.subscribed)continue;let{promise:t,resolve:n,reject:r}=Promise.withResolvers();t.catch(()=>{}),e.ready=t,e.resolve=n,e.reject=r,e.subscribed=!1}}#T(e){let t=new Yr("Realtime connection closed.",e);this.#v(),e.code===4001||e.code===4008?this.#P(t):this.#w(e.code)}async#k(e){this.#l=!0,this.#v();try{await this.#e.close()}finally{this.#l=!1,this.#w(e)}}#w(e){this.#t.schedule({delayPolicy:t=>Ope(e,t),shouldReconnect:()=>!this.#a&&this.#r.size>0,reconnect:()=>this.#y()})}#P(e){let t=[...this.#r.values()],n=new Set(t.flatMap(r=>[...r.listeners]));for(let r of t)r.reject(e);for(let r of n)r.end(e);this.close()}#S(e,t,n=!0){let r=e.filter(s=>this.#r.get(s.subscription.key)===s),o=new Set(r.flatMap(s=>[...s.listeners]));for(let s of r)this.#r.delete(s.subscription.key),s.reject(t);n&&this.#i&&this.#f("unsubscribe",r);for(let s of o)s.end(t);this.#r.size===0&&(this.#o=gn(()=>{this.close()},1e3))}async close(){if(this.#a)return;this.#a=!0,this.#t.stop(),clearTimeout(this.#o);let e=new _("Realtime connection closed.");this.#v();for(let t of this.#r.values())t.reject(e);this.#r.clear(),await this.#e.close()}};Bpe=class{#e;#t=new mi({heartbeat:new I5,connectTimeoutMs:1e4,closeTimeoutMs:1e3});#r=new Map;#s;#n=0;#o=0;#i=0;constructor(e){this.#e=e}async open(e){this.#s=e;let t=this.#i;await this.#t.connect({url:this.#e.url,headers:this.#e.headers,onOpen:()=>{},onError:()=>{},onConnectionLost:n=>{t===this.#i&&(this.#l(new Yr("Realtime connection closed.",n)),e.disconnected(n))},onMessage:n=>{t===this.#i&&this.#u(n)}})}async authorize(){let{key:e,secret:t,passphrase:n}=this.#e.credentials;await this.#a({op:"auth",auth:{apiKey:e,secret:t,passphrase:n}},Nl.Authed,[])}async change(e,t){let n=[],r=0;for(;r<t.length;){let o=[];for(;r+o.length<t.length;){let i=t[r+o.length];if(i===void 0)break;let a=Mpe(i),l={op:e,subscriptions:[...o,a],rid:String(this.#n+1)};if(o.length>0&&new TextEncoder().encode(JSON.stringify(l)).length>6e4)break;o.push(a)}let s=await this.#a({op:e,subscriptions:o},e==="subscribe"?Nl.Subscribed:Nl.Unsubscribed,o.map(({channel:i})=>i));for(let{index:i,error:a}of s){let l=t[r+i];l!==void 0&&n.push({key:l.key,error:a})}r+=o.length}return n}#a(e,t,n){let r=String(++this.#n);return new Promise((o,s)=>{let i={op:t,channels:[...n],rejections:[],resolve:o,reject:s};this.#r.set(r,i),i.sendTimer=gn(()=>{i.timer=gn(()=>{this.#r.delete(r),s(new _("Realtime acknowledgement timed out after 10 seconds."))},1e4),this.#o=Date.now();try{if(!this.#t.send({...e,rid:r}))throw new _("Realtime connection is not open.")}catch(a){clearTimeout(i.timer),this.#r.delete(r),s(_.fromError(a))}},Math.max(0,110-(Date.now()-this.#o)))})}#u(e){let t=DH.safeParse(e);if(t.success){let{op:o,rid:s,code:i,channel:a}=t.data,l=s===void 0?void 0:this.#r.get(s);if(l===void 0)return;if(o===Nl.Error&&i!==void 0){let c=new O(`Realtime subscription rejected: ${i}`,{status:200,code:i}),u=l.channels.flatMap((d,p)=>d===a?[p]:[]);if(a===void 0||u.length!==1)l.reject(c);else{let d=u[0];if(d===void 0||(l.channels[d]=void 0,l.rejections.push({index:d,error:c}),l.channels.some(p=>p!==void 0)))return;l.resolve(l.rejections)}}else if(o===l.op){if(l.channels.length>0){let c=l.channels.indexOf(a??"");if(c<0||(l.channels[c]=void 0,l.channels.some(u=>u!==void 0)))return}l.resolve(l.rejections)}else return;clearTimeout(l.timer),s!==void 0&&this.#r.delete(s);return}let n=UH.safeParse(e);if(!n.success)return;let r=FH(n.data);r!==void 0&&this.#s?.event(r),(n.data.dropped??0)>0&&this.#s?.dropped()}#l(e){for(let t of this.#r.values())clearTimeout(t.sendTimer),clearTimeout(t.timer),t.reject(e);this.#r.clear()}async close(){this.#i++,this.#s=void 0,this.#l(new _("Realtime connection closed.")),await this.#t.close()}};Fpe=class{#e;#t=new Set;#r=new Set;constructor(e){this.#e=e}async subscribe(e){let t=[...new Map(Npe(e).map(a=>[a.key,a])).values()],n=Bd({objectMode:!0}),r=[],o=!1,s,i=async()=>{if(!o){o=!0;for(let a of r)a();s===void 0?await n.return():n.end(s),this.#r.delete(i)}};this.#r.add(i);try{await Promise.all(t.map(a=>{let l=this.#s(a.key),c={event(u){if(o||"types"in e&&e.types!==void 0&&e.types.length>0&&!e.types.includes(u.type))return;let d="symbol"in u.payload?{...u.payload,symbol:"symbol"in a?a.symbol:u.payload.symbol}:u.payload;n.push({...u,payload:d})},end(u){s=u,n.end(u),i()}};return r.push(()=>l.remove(a.key,c)),l.add(a,c)}))}catch(a){throw await i(),a}return{close:i,async*[Symbol.asyncIterator](){try{yield*n}finally{await i()}}}}#s(e){for(let n of this.#t)if(n.closed)this.#t.delete(n);else if(n.has(e))return n;for(let n of this.#t)if(n.size<n.keyTarget)return n;let t=new Lpe(new Bpe(this.#e));return this.#t.add(t),t}async close(){await Promise.all([...this.#r].map(t=>t()));let e=[...this.#t];this.#t.clear(),await Promise.all(e.map(t=>t.close()))}},qpe=class{#e;constructor(e){this.#e=new Fpe(e)}async subscribe(e){return this.#e.subscribe(e)}async close(){await this.#e.close()}};Qpe=class{#e=new Map;#t;constructor(e){this.#t=e}waitFor(e,t){let n=Xpe(),r,o=gn(()=>{this.remove(e,r),n.reject(new tt(t))},this.#t);r=n.promise.finally(()=>clearTimeout(o));let s=this.#e.get(e)??[];return s.push({...n,promise:r}),this.#e.set(e,s),r}resolve(e,t){let n=this.#e.get(e),r=n?.shift();r!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),r.resolve(t))}reject(e,t){let n=this.#e.get(e),r=n?.shift();r!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),r.reject(t))}remove(e,t){let n=this.#e.get(e);if(n===void 0)return;let r=n.filter(o=>o.promise!==t);r.length===0?this.#e.delete(e):this.#e.set(e,r)}rejectAll(e){for(let t of this.#e.values())for(let n of t)n.reject(e);this.#e.clear()}};CV="0x0000000000000000000000000000000000000000000000000000000000000000";NV=H.transform(e=>$V(e)).refine(e=>e<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),eme=Lr.z.strictObject({price:NV.refine(e=>e<1000000n,{message:"Price must be less than 1."}),size:NV.optional(),source:Lr.z.enum(["collateral","inventory"]).default("collateral")});ame=3e4,lme=3e4,cme=class{#e;#t;#r;#s;#n;#o;#i;#a;#u;#l;#c=!1;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#o=e.signer,this.#i=e.url}async connect(){if(this.#c)throw new _("RFQ quoter manager has been shut down.");if(this.#a!==void 0){if(!this.#a.closed)return this.#a;this.#a=void 0}if(this.#l!==void 0)return this.#l;let e=new ume({account:this.#e,chainId:this.#t,credentials:this.#r,exchange:this.#s,headers:this.#n,onClose:()=>this.#p(e),signer:this.#o,url:this.#i});this.#u=e;let t;return t=(async()=>{try{if(await e.connect(),this.#c)throw await e.close(),new _("RFQ quoter manager has been shut down.");return this.#a=e,e}catch(n){throw await e.close(),n}finally{this.#l===t&&(this.#l=void 0),this.#u===e&&(this.#u=void 0)}})(),this.#l=t,t}async shutdown(){this.#c=!0;let e=this.#a,t=this.#u,n=this.#l;this.#a=void 0,this.#u=void 0,this.#l=void 0,await Promise.allSettled([e?.close(),t?.close(),n?.catch(()=>{})]).then(()=>{})}#p(e){this.#a===e&&(this.#a=void 0),this.#u===e&&(this.#u=void 0)}},ume=class{#e;#t;#r;#s;#n;#o;#i;#a;#u=new mi;#l=Bd({objectMode:!0});#c=new Qpe(lme);#p;#d;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#o=e.onClose,this.#i=e.signer,this.#a=e.url}get closed(){return this.#p!==void 0}async connect(){let e=dme();this.#d=e;let t=gn(()=>{e.reject(new _("RFQ quoter authentication timed out."))},ame);try{await this.#u.connect({headers:this.#n,onConnectionLost:n=>this.#v(n),onError:()=>{},onMessage:n=>this.#x(n),onOpen:()=>this.#b(),url:this.#a}),await e.promise}finally{clearTimeout(t),this.#d=void 0}}async#m(e){if(!this.#u.send(e))throw new _("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#y()),await this.#p}[Symbol.asyncIterator](){return this.#l[Symbol.asyncIterator]()}async#y(){let e=new _("RFQ quoter websocket closed.");this.#g(e),this.#l.end(),await this.#u.close(),this.#o()}async#h(e){this.#p===void 0&&(this.#p=this.#f(e)),await this.#p}async#f(e){this.#g(e),this.#l.end(e),await this.#u.close(),this.#o()}#g(e){this.#d?.reject(e),this.#c.rejectAll(e)}#b(){this.#u.send(Wpe(this.#e,this.#r))}#x(e){if(this.#p!==void 0)return;let t=h4.safeParse(e);if(!t.success)return;let n=t.data;switch(n.type){case"auth":this.#A(n);return;case"quote_request":this.#l.push(Hpe(this,n));return;case"quote_ack":this.#c.resolve(uT(n.rfqId),Vpe(n));return;case"quote_cancel_ack":this.#c.resolve(qO(n.rfqId,n.quoteId),jpe(n));return;case"confirmation_request":this.#l.push($pe(this,n));return;case"confirmation_ack":this.#c.resolve(HO(n.rfqId,n.quoteId),zpe(n));return;case"execution_update":this.#l.push(n);return;case"trade":this.#l.push(n);return;case"rfq_error":this.#T(n);return}}#A(e){if(e.success===!0){this.#d?.resolve(void 0);return}this.#d?.reject(new _(`RFQ quoter authentication failed: ${e.error}`))}#v(e){this.#h(new Yr("RFQ quoter connection lost.",e))}#T(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new _("Uncorrelated RFQ quoter error."));return}this.#c.reject(uT(e.rfqId),new ac(e.message,{code:e.code,errorId:e.errorId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_QUOTE_CANCEL"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new _("Uncorrelated RFQ quoter error."));return}this.#c.reject(qO(e.rfqId,e.quoteId),new lc(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_CONFIRMATION_RESPONSE"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new _("Uncorrelated RFQ quoter error."));return}this.#c.reject(HO(e.rfqId,e.quoteId),new cc(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}))}}async quote(e,t){let n=tme(t),r=await nme({account:this.#e,chainId:this.#t,exchange:this.#s,request:e,response:n,signer:this.#i}),o=this.#c.waitFor(uT(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#m(Gpe(e,r)),await o}catch(s){throw this.#c.remove(uT(e.rfqId),o),s}}async cancelQuote(e){let t=qO(e.rfqId,e.quoteId),n=this.#c.waitFor(t,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#m(Kpe(this.#e,e.rfqId,e.quoteId)),await n}catch(r){throw this.#c.remove(t,n),r}}async respondToConfirmation(e,t,n){let r=HO(e,t),o=this.#c.waitFor(r,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#m(Ype(e,t,n)),await o}catch(s){throw this.#c.remove(r,o),s}}};VV=class{#e;#t;#r;#s=new mi({heartbeat:new E5});#n=new ua;#o=new eg({deriveServerState:hme});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#o.add(e,{matches:wme(e)});return await this.#i(n,t),Zf(n.subscriber.queue,()=>this.#a(n))}async#i(e,t){try{if((await this.#l()).reusedOpenSocket){let{before:n,after:r}=t,o=pme(n,r);this.#h(o)}}catch(n){throw await this.#a(e),n}}async#a(e){let{before:t,after:n}=this.#o.remove(e),r=mme(t,n);this.#f(r),this.#o.hasActiveSubscriptions()||await this.close()}async close(){this.#r===void 0&&(this.#r=this.#u().finally(()=>{this.#r=void 0})),await this.#r}async#u(){this.#n.stop(),this.#o.endAll(),await this.#s.close()}#l(){return this.#s.connect({onConnectionLost:()=>this.#d(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#t})}#c(){this.#n.resetBackoff(),this.#y()}#p(e){let t=WH.safeParse(e);t.success&&this.#o.dispatch(t.data)}#d(){this.#o.hasActiveSubscriptions()&&this.#g()}#m(){}#y(){this.#h(Array.from(this.#o.serverState().values()))}#h(e){e.length!==0&&this.#s.send(fme(e))}#f(e){e.length!==0&&this.#s.send(gme(e))}#g(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}};jV=class{#e;#t;#r;#s=new mi({heartbeat:new R5});#n=new ua;#o=new eg;constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{entry:t}=this.#o.add(e);return await this.#i(t),Zf(t.subscriber.queue,()=>this.#a(t))}async#i(e){try{await this.#l()}catch(t){throw await this.#a(e),t}}async#a(e){this.#o.remove(e),this.#o.hasActiveSubscriptions()||await this.close()}async close(){this.#r===void 0&&(this.#r=this.#u().finally(()=>{this.#r=void 0})),await this.#r}async#u(){this.#n.stop(),this.#o.endAll(),await this.#s.close()}#l(){return this.#s.connect({onConnectionLost:()=>this.#d(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#t})}#c(){this.#n.resetBackoff()}#p(e){let t=GH.safeParse(e);t.success&&this.#o.dispatch(t.data)}#d(){this.#o.hasActiveSubscriptions()&&this.#y()}#m(){}#y(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}},zV=class{#e;#t;get context(){return this.#e}get decorators(){return this.#t}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get perps(){return this.context.perps}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??!1}get hasBuilderApiKey(){return this.context.apiKey?.isBuilderKey??!1}constructor(e){this.#e=e,this.#t=[]}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#t.push(e)}},vme=Lr.z.object({key:os,passphrase:Lr.z.string(),secret:Lr.z.string()}),kme=Lr.z.object({wallet:J,credentials:vme.optional(),nonce:Lr.z.number().int().nonnegative().optional()}).superRefine((e,t)=>{e.credentials!==void 0&&e.nonce!==void 0&&t.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]})}).transform(e=>e.credentials!==void 0?{wallet:e.wallet,credentials:e.credentials}:e.nonce!==void 0?{wallet:e.wallet,nonce:e.nonce}:{wallet:e.wallet}),WV=class extends zV{constructor(e){super({apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,data:new vn({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new vn({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new vn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:t=>this.resolveClobHeaders(t)}),relayer:new vn({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:t=>this.resolveRelayerHeaders(t)}),rfq:new vn({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new vn({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new _N({url:e.environment.rpc}),webSockets:{clobMarket:new qV({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new jV({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new VV({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new HV({headers:e.environment.perps.headers,url:e.environment.perps.ws})}})}isSecureClient(){return!1}isPublicClient(){return!0}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close()]).then(()=>{})}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,t){let n=F(e,kme);return Promise.resolve(async function*(){let r=Math.floor(Date.now()/1e3),o=n?.nonce??0,s=Be(yield QN()),i=Be(n.wallet),a=_6(this.environment,s,i);if(n.credentials!==void 0){let u=this.#e(n.credentials,a,t);try{if((await Tv(u)).includes(n.credentials.key))return u}catch(d){if(!(d instanceof O)||d.status!==401)throw d}}let l=yield{kind:"signAuthMessage",payload:ppe({address:s,chainId:this.environment.chainId,nonce:o,timestamp:r})},c=await Av(this,{address:s,nonce:o,signature:rs(l),timestamp:r});return this.#e(c,a,t)}.call(this))}#e(e,t,n){let r=new xme({account:t,apiKey:this.context.apiKey,credentials:e,environment:this.environment,onRateLimitUpdate:this.context.onRateLimitUpdate,signer:n});for(let o of this.decorators)r.extend(o);return r}},xme=class extends zV{#e=!1;get context(){return ge(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=!0}constructor(e){let t=new qpe({url:e.environment.realtime.ws,headers:e.environment.realtime.headers,credentials:e.credentials});super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,signer:e.signer,clob:new vn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:n=>this.resolveClobHeaders(n)}),relayer:new vn({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:n=>this.resolveRelayerHeaders(n)}),rpc:new _N({url:e.environment.rpc}),gamma:new vn({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new vn({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new vn({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new vn({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new vn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,resolveHeaders:async n=>({...await this.resolveClobHeaders(n),...await this.#r(n)}),root:e.environment.clob.rest}),combos:new vn({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:n=>this.resolveRelayerHeaders(n),root:e.environment.combos.collateralReturn.rest}),builderGateway:new vn({headers:e.environment.combos.builderGateway.headers,resolveHeaders:async n=>({...await this.#t(n),...await this.#r(n)}),root:e.environment.combos.builderGateway.rest}),webSockets:{clobMarket:new qV({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new Epe({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new cme({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.contracts.exchangeV3,headers:e.environment.combos.headers,signer:e.signer,url:e.environment.combos.ws}),sports:new jV({headers:e.environment.sports.headers,url:e.environment.sports.ws}),realtime:t,rtds:new VV({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new HV({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new Rpe({chainId:e.environment.chainId,headers:e.environment.perps.headers,restUrl:e.environment.perps.rest,wsUrl:e.environment.perps.ws})}})}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}get secureClob(){return this.context.secureClob}get combos(){return this.context.combos}get builderGateway(){return this.context.builderGateway}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.realtime.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close(),this.webSockets.clobUser.close()]).then(()=>{})}isSecureClient(){return!0}isPublicClient(){return!1}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),t=this.webSockets.perpsSession.shutdown(),n=this.webSockets.rfqQuoter.shutdown(),{apiKey:r,environment:o,onRateLimitUpdate:s}=this.context;try{await Sv(this)}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,t,n]).then(()=>{})}let i=new WV({apiKey:r,environment:o,onRateLimitUpdate:s});for(let a of this.decorators)i.extend(a);return i}async#t(e){return e.method!=="GET"&&this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):{}}async#r(e){try{let t=Math.floor(Date.now()/1e3);return{POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await MV(this.credentials.secret,t,e.method,e.path,e.body),POLY_TIMESTAMP:`${t}`}}catch(t){throw ue.fromError(t,"Could not sign the L2-authenticated request")}}};Ame=B(bt,$,O,ue,tt,en,_,C,E),Tme=B(E)});var QV={};fr(QV,{AcceptComboQuoteError:()=>IA,ApproveErc1155ForAllError:()=>wv,ApproveErc20Error:()=>bv,ApprovePerpsBuilderFeeError:()=>vx,ArmPerpsAutoCancelError:()=>Px,AuthorizeSessionKeyError:()=>$A,BiggestWinnerKind:()=>Ql,BuilderVolumeInterval:()=>Kl,CancelAllError:()=>zk,CancelMarketOrdersError:()=>Gk,CancelOrderError:()=>Hk,CancelOrdersError:()=>Vk,CollateralReturnKnownOperationKind:()=>Dd,ComboAcceptFailureReason:()=>Ro,ComboActivityType:()=>Wl,ComboPositionSortBy:()=>Vl,ComboPositionStatus:()=>ii,ComboQuoteUnavailableReason:()=>ci,CreateApiKeyError:()=>g8,CreateBuilderApiKeyError:()=>k8,CreateLimitOrderError:()=>fx,CreateMarketOrderError:()=>px,CreateOrDeriveApiKeyError:()=>b8,DeleteApiKeyError:()=>v8,DeployDepositWalletError:()=>r8,DepositToPerpsError:()=>Gx,DeriveApiKeyError:()=>y8,DownloadAccountingSnapshotError:()=>aA,DropNotificationsError:()=>j0,EstimateMarketPriceError:()=>Qk,ExecuteCollateralReturnPlanError:()=>ek,FetchApiKeysError:()=>w8,FetchBalanceAllowanceError:()=>D6,FetchBuilderApiKeysError:()=>A8,FetchBuilderFeeRatesError:()=>L8,FetchBuilderVolumeError:()=>vk,FetchClosedOnlyModeError:()=>D0,FetchCommentsByIdError:()=>ok,FetchEventError:()=>uk,FetchEventLiveVolumeError:()=>gk,FetchEventTagsError:()=>pk,FetchExecuteParamsError:()=>t8,FetchLastTradePriceError:()=>Vv,FetchLastTradePricesError:()=>zv,FetchMarketError:()=>Ck,FetchMarketInfoError:()=>O8,FetchMarketTagsError:()=>Ok,FetchMidpointError:()=>Rv,FetchMidpointsError:()=>_v,FetchNegRiskError:()=>_8,FetchNotificationsError:()=>$0,FetchOpenInterestError:()=>Fk,FetchOrderBookError:()=>Uv,FetchOrderBooksError:()=>Bv,FetchOrderError:()=>F0,FetchOrderScoringError:()=>G0,FetchOrdersScoringError:()=>Y0,FetchPerpsBookError:()=>Dx,FetchPerpsBuilderApprovalsError:()=>Ax,FetchPerpsBuilderEarningsSummaryError:()=>Sx,FetchPerpsBuilderStatusError:()=>bx,FetchPerpsFeesError:()=>Vx,FetchPerpsInstrumentsError:()=>_x,FetchPerpsTickerError:()=>Nx,FetchPerpsTickersError:()=>Lx,FetchPortfolioValueError:()=>rA,FetchPriceError:()=>Nv,FetchPricesError:()=>Lv,FetchPublicProfileError:()=>vA,FetchRelatedTagResourcesError:()=>rT,FetchRelatedTagsError:()=>tT,FetchResolutionsError:()=>hk,FetchRewardPercentagesError:()=>rv,FetchRfqStatusError:()=>OA,FetchSeriesError:()=>FA,FetchSessionKeysError:()=>HA,FetchSportsMarketTypesError:()=>KA,FetchSpreadError:()=>Fv,FetchSpreadsError:()=>Hv,FetchTagError:()=>ZA,FetchTickSizeError:()=>R8,FetchTotalEarningsForUserForDayError:()=>Z0,FetchTraderLeaderboardStandingError:()=>Tk,FetchTradingApprovalsStateError:()=>vv,FetchUserPnlError:()=>sA,FetchUserStatsError:()=>oA,FetchUserVolumeError:()=>iA,GaslessTransactionHandle:()=>Cf,GaslessTransactionMetadataSchema:()=>ur,IsWalletDeployedError:()=>n8,LeaderboardWindow:()=>Gl,ListAccountTradesError:()=>H0,ListActivityError:()=>av,ListBiggestWinnersError:()=>Sk,ListBuilderLeaderboardError:()=>bk,ListBuilderTradesError:()=>Pv,ListComboActivityError:()=>lv,ListComboMarketsError:()=>Ik,ListComboPositionsError:()=>nA,ListCommentsByUserAddressError:()=>ik,ListCommentsError:()=>nk,ListCurrentRewardsError:()=>Gv,ListEventsError:()=>lk,ListMarketClarificationsError:()=>q8,ListMarketHoldersError:()=>Dk,ListMarketRewardsError:()=>Yv,ListMarketsError:()=>Rk,ListOpenOrdersError:()=>B0,ListPerpsBuilderEarningsError:()=>Tx,ListPerpsCandlesError:()=>Bx,ListPerpsFundingHistoryError:()=>Fx,ListPerpsTradesError:()=>Hx,ListPositionsError:()=>tA,ListPriceHistoryError:()=>Bk,ListSeriesError:()=>BA,ListSportsError:()=>WA,ListTagsError:()=>XA,ListTeamsError:()=>sT,ListTraderLeaderboardError:()=>xk,ListTradesError:()=>sv,ListUserEarningsAndMarketsConfigError:()=>tv,ListUserEarningsForDayError:()=>X0,MergeComboPositionError:()=>aV,MergeMarketPositionError:()=>sV,MergePositionsError:()=>jd,OpenPerpsSessionError:()=>zx,OpenRfqSessionError:()=>SA,PlaceLimitOrderError:()=>gx,PlaceMarketOrderError:()=>mx,PlanCollateralReturnError:()=>Jv,PositionFilterType:()=>$l,PositionSortBy:()=>Hl,PositionStatus:()=>ai,PostOrderError:()=>Zk,PostOrdersError:()=>ex,PrepareCollateralReturnExecutionError:()=>U8,PrepareErc1155ApprovalForAllError:()=>d8,PrepareErc20ApprovalError:()=>u8,PrepareErc20TransferError:()=>xV,PrepareGaslessTransactionError:()=>o8,PrepareLimitOrderError:()=>bO,PrepareLimitOrderPostingError:()=>v5,PrepareMarketOrderError:()=>yO,PrepareMarketOrderPostingError:()=>b5,PrepareMergeComboPositionError:()=>oV,PrepareMergeMarketPositionError:()=>nV,PrepareMergePositionsError:()=>pA,PreparePerpsDepositError:()=>V5,PrepareRedeemComboPositionError:()=>mV,PrepareRedeemMarketPositionsError:()=>dV,PrepareRedeemPositionsError:()=>gA,PrepareSplitComboPositionError:()=>Q5,PrepareSplitMarketPositionError:()=>K5,PrepareSplitPositionError:()=>lA,PrepareTradingApprovalsError:()=>p8,PriceHistoryInterval:()=>Po,RedeemPositionsError:()=>bA,RequestComboQuoteError:()=>EA,ResolutionMarketType:()=>Jl,ResolutionReporter:()=>ec,ResolutionSource:()=>Zl,ResolutionStatus:()=>Xl,ResolveConditionByTokenError:()=>N8,RevokeBuilderApiKeyError:()=>S8,RevokePerpsBuilderFeeError:()=>Ix,RevokePerpsCredentialsError:()=>Wx,RevokeSessionKeyError:()=>jA,RfqCancelQuoteError:()=>AA,RfqCancelQuoteRejectedError:()=>lc,RfqConfirmationDecision:()=>cs,RfqConfirmationError:()=>TA,RfqConfirmationRejectedError:()=>cc,RfqDirection:()=>Nn,RfqExecutionStatus:()=>us,RfqKnownErrorCode:()=>Cr,RfqQuoteError:()=>xA,RfqQuoteRejectedError:()=>ac,RfqRejectionCode:()=>li,RfqRequestRejectedError:()=>ms,RfqRequestedSizeUnit:()=>Qr,RfqSide:()=>Eo,RfqStatus:()=>mn,SearchError:()=>DA,SearchSort:()=>zd,SessionKeyKnownScope:()=>yo,SetupTradingApprovalsError:()=>kv,SortDirection:()=>Ml,SplitComboPositionError:()=>Z5,SplitMarketPositionError:()=>X5,SplitPositionError:()=>Vd,SubscribeError:()=>QA,TipSide:()=>Bl,TradeFilterType:()=>Fl,TraderLeaderboardSort:()=>Yl,TransferErc20Error:()=>aT,TransferPerpsCollateralError:()=>Yx,UpdateBalanceAllowanceError:()=>U6,UpdatePerpsLeverageError:()=>Ex,UpdatePerpsMarginError:()=>Rx,UserPnlFidelity:()=>zl,UserPnlInterval:()=>jl,WaitForComboFillError:()=>CA,WaitForGaslessTransactionError:()=>c8,WaitForOrderFillSettlementError:()=>ux,WithdrawFromPerpsError:()=>Kx,acceptComboQuote:()=>_A,approveErc1155ForAll:()=>Of,approveErc20:()=>Nf,authorizeSessionKey:()=>VA,buildDepositWalletExecuteRequest:()=>qd,buildProxyWalletExecuteRequest:()=>mv,buildSafeWalletExecuteRequest:()=>gv,cancelAll:()=>Wk,cancelMarketOrders:()=>Kk,cancelOrder:()=>$k,cancelOrders:()=>jk,createApiKey:()=>tO,createBuilderApiKey:()=>x8,createLimitOrder:()=>Ff,createMarketOrder:()=>Mf,createOrDeriveApiKey:()=>Av,deleteApiKey:()=>Sv,deployDepositWallet:()=>pv,depositToPerps:()=>Jx,deriveApiKey:()=>nO,downloadAccountingSnapshot:()=>Kf,dropNotifications:()=>z0,estimateMarketPrice:()=>Xk,executeCollateralReturnPlan:()=>tk,extractOnChainNonceFromSubmitError:()=>hv,fetchApiKeys:()=>Tv,fetchBalanceAllowance:()=>W0,fetchBuilderApiKeys:()=>T8,fetchBuilderFeeRates:()=>sO,fetchBuilderVolume:()=>kk,fetchClosedOnlyMode:()=>U0,fetchCommentsById:()=>sk,fetchEvent:()=>dk,fetchEventLiveVolume:()=>yk,fetchEventTags:()=>mk,fetchExecuteParams:()=>If,fetchLastTradePrice:()=>jv,fetchLastTradePrices:()=>Wv,fetchMarket:()=>Nk,fetchMarketInfo:()=>oO,fetchMarketTags:()=>Lk,fetchMidpoint:()=>Iv,fetchMidpoints:()=>Cv,fetchNegRisk:()=>C8,fetchNotifications:()=>V0,fetchOpenInterest:()=>qk,fetchOrder:()=>q0,fetchOrderBook:()=>Hd,fetchOrderBooks:()=>Mv,fetchOrderScoring:()=>K0,fetchOrdersScoring:()=>Q0,fetchPerpsBook:()=>Ux,fetchPerpsBuilderStatus:()=>wx,fetchPerpsFees:()=>jx,fetchPerpsInstruments:()=>Cx,fetchPerpsTicker:()=>Ox,fetchPerpsTickers:()=>Hf,fetchPortfolioValue:()=>jf,fetchPrice:()=>Ov,fetchPrices:()=>Dv,fetchPublicProfile:()=>kA,fetchRelatedTagResources:()=>oT,fetchRelatedTags:()=>nT,fetchResolutions:()=>fk,fetchRewardPercentages:()=>ov,fetchRfqStatus:()=>LA,fetchSeries:()=>qA,fetchSessionKeys:()=>Wd,fetchSportsMarketTypes:()=>YA,fetchSpread:()=>qv,fetchSpreads:()=>$v,fetchTag:()=>eT,fetchTickSize:()=>I8,fetchTotalEarningsForUserForDay:()=>ev,fetchTraderLeaderboardStanding:()=>Df,fetchTradingApprovalsState:()=>Lf,fetchTransaction:()=>XN,fetchUserPnl:()=>Wf,fetchUserStats:()=>zf,fetchUserVolume:()=>Gf,isRetryableGaslessSubmitError:()=>yv,isWalletDeployed:()=>_f,listAccountTrades:()=>Tf,listActivity:()=>Sf,listBiggestWinners:()=>Pk,listBuilderLeaderboard:()=>wk,listBuilderTrades:()=>Ev,listComboActivity:()=>Pf,listComboMarkets:()=>_k,listComboPositions:()=>Vf,listComments:()=>rk,listCommentsByUserAddress:()=>ak,listCurrentRewards:()=>Kv,listEvents:()=>ck,listMarketClarifications:()=>Ek,listMarketHolders:()=>Uk,listMarketRewards:()=>Qv,listMarkets:()=>Uf,listOpenOrders:()=>M0,listPerpsCandles:()=>Mx,listPerpsFundingHistory:()=>qx,listPerpsTrades:()=>$x,listPositions:()=>$f,listPriceHistory:()=>Mk,listSeries:()=>MA,listSports:()=>GA,listTags:()=>JA,listTeams:()=>iT,listTraderLeaderboard:()=>Ak,listTrades:()=>iv,listUserEarningsAndMarketsConfig:()=>nv,listUserEarningsForDay:()=>J0,mergeComboPosition:()=>lV,mergeMarketPosition:()=>iV,mergePositions:()=>fA,openPerpsSession:()=>Qx,openRfqSession:()=>PA,placeLimitOrder:()=>yx,placeMarketOrder:()=>hx,planCollateralReturn:()=>Zv,postOrder:()=>$d,postOrders:()=>tx,prepareCollateralReturnExecution:()=>iO,prepareErc1155ApprovalForAll:()=>ZN,prepareErc20Approval:()=>JN,prepareErc20Transfer:()=>FO,prepareGaslessTransaction:()=>Or,prepareLimitOrder:()=>cx,prepareLimitOrderPosting:()=>k5,prepareMarketOrder:()=>lx,prepareMarketOrderPosting:()=>w5,prepareMergeComboPosition:()=>hA,prepareMergeMarketPosition:()=>mA,prepareMergePositions:()=>NO,preparePerpsDeposit:()=>_O,prepareRedeemComboPosition:()=>hV,prepareRedeemMarketPositions:()=>OO,prepareRedeemPosition:()=>yA,prepareRedeemPositions:()=>LO,prepareSplitComboPosition:()=>uA,prepareSplitMarketPosition:()=>cA,prepareSplitPosition:()=>CO,prepareTradingApprovals:()=>eO,redeemPositions:()=>wA,requestComboQuote:()=>RA,resignDepositWalletExecuteRequest:()=>fv,resolveConditionByToken:()=>rO,resolveEstimatedMarketPrice:()=>dO,resolveMarketPriceFromOrderBook:()=>Jk,revokeBuilderApiKey:()=>P8,revokePerpsCredentials:()=>Xx,revokeSessionKey:()=>zA,search:()=>UA,setupTradingApprovals:()=>xv,signOrder:()=>ax,splitComboPosition:()=>eV,splitMarketPosition:()=>J5,splitPosition:()=>dA,subscribe:()=>Qf,transferErc20:()=>lT,transferPerpsCollateral:()=>eA,updateBalanceAllowance:()=>ON,waitForComboFill:()=>NA,waitForOrderFillSettlement:()=>dx,withdrawFromPerps:()=>Zx});var XV=L(()=>{"use strict";cT()});var Hge={};fr(Hge,{AI_AGENT_TOOL_NAMES:()=>tS,AbortError:()=>Li,AgentCore:()=>cS,ApproveTokenTool:()=>Gp,BRIDGE_NON_EVM_CHAIN_FAMILY:()=>Qa,BRIDGE_STATUS_POLL_MS:()=>pY,BRIDGE_SUPPORT_URL:()=>mY,BUILDER_CODE:()=>EP,BaseNftAiTool:()=>bs,BaseSwapProvider:()=>Ta,BaseTool:()=>K,BaseWalletActionTool:()=>eo,BuyTokenTool:()=>Kp,CachedResource:()=>xs,ChatHistory:()=>Xp,CoinpoolConfigApi:()=>sg,DEFAULT_CHAIN:()=>er,DEFAULT_PROVIDER:()=>gi,DEFAULT_RPC_BY_CHAIN:()=>Mr,DEFILLAMA_EXTRA_SIGNALS:()=>Oo,DEFILLAMA_POOL_CHAIN_HEXES:()=>Bp,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION:()=>hr,DELAYED_ORDER:()=>_y,DEPOSIT_REFERENCE_USD:()=>tL,DEPOSIT_STABLE_SYMBOLS:()=>Mm,DebridgeProvider:()=>Tp,DefiLlamaEstimatePoolYieldTool:()=>Vp,DefiLlamaPoolByAddressTool:()=>$p,DefiLlamaPoolCandidateResolver:()=>jp,DefiLlamaPoolDetailTool:()=>Hp,DefiLlamaPoolSearchTool:()=>qp,DefiLlamaPoolService:()=>Jn,DefiLlamaTopPoolsTool:()=>Fp,ERC1967_INIT_CODE:()=>Ds,EstimatePoolYieldTool:()=>Ip,GAMES_TAG_ID:()=>LP,GeminiProvider:()=>jt,GeminiSearchAiTool:()=>hp,HEX_TO_PANTOGRAPH:()=>Y1,HIDE_FROM_NEW_TAG_ID:()=>DP,KeyringSettingApi:()=>lg,KnowledgeBase:()=>Zp,LendingMarketDetailTool:()=>_u,LendingMarketsTool:()=>Iu,LendingReadService:()=>Eu,LendingService:()=>io,LendingSupplyService:()=>Ru,MARKET_ORDER:()=>qm,MARKET_STREAM:()=>Hm,MULTICALL3_ADDRESS:()=>vt,ManageLiquidityRedirectTool:()=>bc,MoralisService:()=>De,NATIVE_GAS_LIMIT:()=>wz,NATIVE_TOKEN_PLACEHOLDER:()=>IP,NFC_AGENT_TOOL_NAMES:()=>eS,NFC_AMAZON_DEFAULT_DOMAIN:()=>fL,NFC_AMAZON_DOMAINS:()=>hL,NFTContractInfoTool:()=>cp,NFTMetadataTool:()=>up,NFT_AGENT_TOOL_NAMES:()=>ZT,NfcBuyTool:()=>mp,NfcInfoTool:()=>pp,NoFormTool:()=>gg,ONBOARDING_STEP:()=>on,ONBOARDING_TRACKING:()=>Iy,ORDER_INPUT_ERROR:()=>Us,OpenAddLiquidityFormTool:()=>fc,OpenSupplyFormTool:()=>Nu,PERPS_DEPOSIT_CONTRACT:()=>CP,POLYGON_CHAIN_ID:()=>Bm,POLYGON_HEX_CHAIN_ID:()=>Vi,POLYMARKET_API:()=>Hi,POLYMARKET_LIVE_DATA_WS:()=>_P,POLYMARKET_WEB_URL:()=>$i,POOL_UNISWAP_AGENT_TOOL_NAMES:()=>rS,POSITION_DUST_SHARES:()=>BP,PREDICTION_ACTIVITY_TYPES:()=>UP,PREDICTION_AGENT_TOOL_NAMES:()=>XT,PREDICTION_CATEGORIES:()=>ji,PREDICTION_SORTS:()=>Fm,PUSD_ADDRESS:()=>Os,PUSD_DECIMALS:()=>Ls,PantographService:()=>Ft,PolymarketApiError:()=>Ys,PolymarketOnboardingError:()=>hi,PolymarketRedeemError:()=>fa,PolymarketService:()=>Ye,PolymarketTradeError:()=>ha,PolymarketWithdrawError:()=>gs,PoolByAddressTool:()=>Rp,PoolDetailTool:()=>Pp,PoolFallbackAiTool:()=>fp,PoolPriceRangesTool:()=>yc,PoolSearchTool:()=>Ep,PoolService:()=>Et,PoolSwapRouter:()=>vp,PredictionActivityTool:()=>np,PredictionDepositTool:()=>op,PredictionMarketDetailTool:()=>ep,PredictionMarketsTool:()=>Jd,PredictionPortfolioTool:()=>tp,PredictionSetupTool:()=>rp,PredictionTradeTool:()=>sp,PredictionWithdrawTool:()=>ip,PreviewAddLiquidityTool:()=>gc,PublicClient:()=>Ha,REDEEM:()=>Xa,RELAYER_DEPLOY_POLL:()=>Ry,RELAYER_SUBMIT_PATH:()=>Ey,RelayProvider:()=>bp,Router:()=>em,SUPPLIABLE_TYPES:()=>wP,SUPPORTED_CHAINS:()=>eu,SUPPORTED_CHAINS_LABEL:()=>nu,SWAP_PROVIDER_CONFIG:()=>Ap,SendNativeTool:()=>zp,SendNftTool:()=>Qp,SendTokenTool:()=>Wp,Subagent:()=>ct,SubgraphAddPoolTool:()=>Up,SubgraphCoinPoolPairsTool:()=>Dp,SubgraphPoolByAddressTool:()=>Np,SubgraphPoolByPositionIdTool:()=>Op,SubgraphPoolSearchTool:()=>_p,SubgraphPositionDetailTool:()=>Lp,SubgraphTrendingPoolsTool:()=>Cp,Summarizer:()=>Jp,SwapProviderFactory:()=>ag,SwapRouter:()=>wp,SwapRouterRegistry:()=>ig,SwapTokenTool:()=>Yp,Synthesizer:()=>tm,TOKEN_AGENT_TOOL_NAMES:()=>JT,TRADE_ERROR:()=>gt,TRADING_APPROVALS_METADATA:()=>NP,TRANSFER_TOPIC:()=>oz,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Q1,TokenAnalyticsTool:()=>du,TokenHoldersTool:()=>uu,TokenInfoTool:()=>cu,TokenScoreTool:()=>pu,ToolRegistry:()=>Zc,TopGainersTool:()=>hu,TopPoolsTool:()=>Sp,TransactionByHashTool:()=>Pu,TrendingTokensTool:()=>mu,UNISWAP_CHAIN_SLUG:()=>ug,UNRESOLVED_ASSET:()=>Ka,UP_OR_DOWN_TAG_ID:()=>OP,UpstashKnowledgeBase:()=>Ia,UserSwapRouter:()=>kp,WALLET_ACTION_AGENT_TOOL_NAMES:()=>oS,WALLET_AGENT_TOOL_NAMES:()=>QT,WALLET_DERIVATION:()=>jr,WITHDRAW:()=>xn,WalletApprovalsTool:()=>Au,WalletDefiPositionsTool:()=>Tu,WalletDefiProtocolPositionsTool:()=>Su,WalletHistoryTool:()=>bu,WalletLendingPositionsTool:()=>Cu,WalletNFTsTool:()=>lp,WalletNftTransfersTool:()=>vu,WalletPnlSummaryTool:()=>ku,WalletPnlTool:()=>xu,WalletTokenBalancesTool:()=>yu,WalletTokenTransfersTool:()=>wu,WebsiteTrustKeyringAgent:()=>uS,ZERO_ADDRESS:()=>Pt,adjustBuyAmountForFees:()=>GP,allInBuyNotional:()=>XD,amazonDomainForLanguage:()=>gL,apiClient:()=>se,applyMarketEvent:()=>nL,applyYieldConversions:()=>my,bestPrice:()=>eU,buildApprovalCalls:()=>ZO,buildApprovals:()=>qT,buildBuilderSignature:()=>DI,buildChallenge:()=>JS,buildRangePresets:()=>vL,buildUniswapPoolUrl:()=>Ur,builderApiKey:()=>UI,buyNotional:()=>QD,buyNotionalAfterFee:()=>JD,call:()=>Mo,canDeriveV3PoolAddress:()=>SL,ceil2:()=>YD,chains:()=>Ua,checkNativeGasAffordable:()=>mg,checksumAddress:()=>Sc,clampTick:()=>ks,classifyTradeError:()=>oL,classifyWithdrawError:()=>iL,clearPublicClientCache:()=>Yg,coinpoolConfigApi:()=>Pa,compareDecimal:()=>Oi,completeX402:()=>ZS,configureSupportedChains:()=>ey,configureSwapProvider:()=>MT,convertSusdsShares:()=>Ga,createAiAgent:()=>Ag,createDefaultSubagents:()=>sS,createNfcAgent:()=>xg,createNftAgent:()=>kg,createPolymarketSigner:()=>ma,createPoolUniswapAgent:()=>Tg,createPredictionAgent:()=>wg,createPublicClient:()=>Ni,createTokenAgent:()=>vg,createTransport:()=>_i,createWalletActionAgent:()=>Sg,createWalletAgent:()=>bg,createX402SignatureProvider:()=>tP,decodeAbiParameters:()=>Dn,decodeErrorResult:()=>_c,decodeFunctionData:()=>ES,decodeFunctionResult:()=>Do,defiLlamaPoolInfoScope:()=>pr,defiLlamaPoolSupportsLabel:()=>mr,deployDepositWallet:()=>vw,depositPriceImpact:()=>nj,deriveBeaconDepositWallet:()=>NI,deriveDepositWallet:()=>LI,deriveSafeWallet:()=>OI,deriveUupsDepositWallet:()=>CI,deriveV3PoolAddress:()=>PL,displayFromChallenge:()=>M1,effectivePriceUSD:()=>Cm,encodeAbiParameters:()=>Ec,encodeApprove:()=>FT,encodeErrorResult:()=>xS,encodeFunctionData:()=>Le,encodeSignedHeader:()=>eP,erc1155Abi:()=>$g,erc20Abi:()=>Ve,erc20Abi_bytes32:()=>Fc,erc721Abi:()=>qc,estimateGas:()=>Bc,estimateNativeGasReserveWei:()=>dg,estimateTransactionFeeWei:()=>RL,ethCallAt:()=>cD,ethCallByChain:()=>uK,eventHeadline:()=>Uy,eventUrl:()=>jP,evmDepositAssets:()=>gT,exactAmountString:()=>$a,extractOutRaw:()=>ez,extractQuoteError:()=>tz,fallback:()=>Ci,feePerShare:()=>zi,feeWeiToNative:()=>IL,fetchOnboardingSnapshot:()=>fs,fetchTopMarketplaces:()=>yL,fetchTradingApprovalsStatus:()=>hT,fetchUnderlyingPricesUSD:()=>Lm,findWalletDepositOptions:()=>fT,floor2:()=>Za,floorToDecimals:()=>gr,formatDefiLlamaPool:()=>Ln,getAbiItem:()=>Si,getAddress:()=>yS,getBalance:()=>Oc,getBlock:()=>Mc,getBlockNumber:()=>Cc,getCashBalance:()=>cd,getCashBalanceBaseUnits:()=>Sh,getChain:()=>kn,getChainContractAddress:()=>dm,getChainId:()=>Nc,getChainMeta:()=>Co,getCode:()=>Pi,getDefaultRpcUrl:()=>$S,getGasPrice:()=>Uc,getNativeTokenInfo:()=>mc,getPolymarketBuilderCode:()=>Ou,getPublicClient:()=>Rt,getRevertReason:()=>am,getRpcOverrides:()=>fm,getStorageAt:()=>Lc,getTokenPriceUSD:()=>uy,getTransactionCount:()=>Dc,http:()=>so,humanToWei:()=>Is,ingestKnowledgeBase:()=>Mz,isAbortError:()=>ja,isAddress:()=>fe,isAddressEqual:()=>bS,isEvmAddress:()=>zr,isMarketOpen:()=>jm,isPaymentRequired:()=>eG,isShareBasedProtocol:()=>au,isShareBasedYieldToken:()=>eD,isSupplyChain:()=>by,keyringSettingApi:()=>Sa,listCandidateChains:()=>bP,listSupplyChains:()=>yy,mapEvent:()=>Dy,mapMarket:()=>VP,marketFee:()=>Vm,marketProtocol:()=>$m,moneylineMarket:()=>Ja,mulDivFloor:()=>Va,multicall:()=>Qc,multicall3Abi:()=>oo,multicallRaw:()=>Ri,nativeGasShortfall:()=>kz,nfcAmazonSearchUrl:()=>CT,normaliseCountry:()=>NT,normalizeDecimal:()=>Xc,normalizeLevels:()=>el,normalizePriceRangeToPool:()=>yp,normalizeText:()=>St,onboardingStep:()=>ZV,openSecureClient:()=>Yd,parseAbi:()=>CS,parseAbiItem:()=>qg,parseAbiParameters:()=>cm,parsePolymarketUrl:()=>zm,parsePredictionHint:()=>Wm,pickLogo:()=>yi,placePredictionOrder:()=>ij,planYieldTokenConversions:()=>fP,predictionHint:()=>By,prepareMarketOrder:()=>ZD,priceToTick:()=>pc,protocolLabelFor:()=>yr,psm3For:()=>py,pusdFromBaseUnits:()=>sL,pusdToBaseUnits:()=>vT,quoteBuyAsPolymarket:()=>WP,quoteBuyUsd:()=>Du,quoteDeposit:()=>ng,quoteMarketOrder:()=>YP,quoteSellShares:()=>KP,quoteWithdrawal:()=>lj,readContract:()=>Fo,readPaymentError:()=>U1,readPaymentRequired:()=>Xg,readProtocolFeeWei:()=>HT,readReceipt:()=>B1,readSpendableBalance:()=>fg,readTokenUsdPrice:()=>hg,redeemPredictionPositions:()=>uj,registerMaybeNoForm:()=>YT,remoteBuilderSigning:()=>FF,requestWithX402:()=>ZW,resolveAccountWallet:()=>yw,resolveCategory:()=>My,resolveGasLimit:()=>vz,resolveNfcShopLinks:()=>dp,resolveRawYieldAsset:()=>z1,resolveRawYieldIdentity:()=>za,resolveRawYieldProtocol:()=>j1,resolveRpcUrl:()=>Ho,resolveRpcUrls:()=>qa,resolveTokenPriceUSD:()=>Nm,roundTickToSpacing:()=>vs,rpcCall:()=>lD,runPolymarketOnboarding:()=>ej,setPolymarketBuilderCode:()=>RP,setRpcOverrides:()=>Fa,slippagePrice:()=>Fy,spendableNative:()=>pg,swapProviderFactory:()=>xp,swapRouterRegistry:()=>BT,tickToPrice:()=>_o,ticketFee:()=>zP,toBuilderAuthorization:()=>Zo,toEventSelector:()=>wS,toFunctionSelector:()=>Es,toPantographChain:()=>bG,toPlainDecimal:()=>ym,unitPriceUSD:()=>lu,upDownWindow:()=>Oy,valueYieldTokens:()=>hy,walletDepositAssets:()=>eL,watchCryptoPrice:()=>WD,watchOrderBooks:()=>oj,weiToHuman:()=>Jc,withdrawDestinations:()=>wT,withdrawFromPolymarket:()=>cj});module.exports=zz(Hge);var qL=ML(require("axios"));var FL="0.3.23";var Gz=`keyring-agent-core/${FL} (Keyring Chatbot Agent; +https://keyring.app)`,dS=null;function HL(e){dS=e}var Kz=["payment-signature","x-payment"];function Yz(e){return e?Object.keys(e).some(t=>Kz.includes(t.toLowerCase())):!1}var $L;function rm(e){$L=e}var Qz=3e4,Xz=typeof process<"u"&&process.versions?.node!=null,pS=class{instance;constructor(t={}){this.instance=qL.default.create({baseURL:t.baseURL,timeout:t.timeout??Qz,validateStatus:()=>!0,headers:{Accept:"application/json",...Xz?{"Accept-Encoding":"gzip, deflate, br","User-Agent":t.userAgent??Gz}:{},...t.headers}})}async request(t,n,r,o={}){let s=o.signal??$L,i=await this.instance.request({...o,signal:s,method:t,url:n,data:r}),a={};for(let[c,u]of Object.entries(i.headers??{}))u!=null&&(a[c.toLowerCase()]=String(u));let l={ok:i.status>=200&&i.status<300,status:i.status,statusText:i.statusText,data:i.data,headers:a};if(l.status===402&&dS&&!Yz(o.headers)){let c=await dS(l,{url:n,method:String(t),body:r,headers:o.headers});if(c)return this.request(t,n,r,{...o,headers:{...o.headers,...c}})}return l}get(t,n){return this.request("GET",t,void 0,n)}post(t,n,r){return this.request("POST",t,n,r)}put(t,n,r){return this.request("PUT",t,n,r)}patch(t,n,r){return this.request("PATCH",t,n,r)}delete(t,n){return this.request("DELETE",t,void 0,n)}},se=new pS;function he(e){let{data:t,status:n,statusText:r}=e,o=r?`HTTP ${n} ${r}`:`HTTP ${n}`;if(typeof t=="string")return t.trim()||o;if(t&&typeof t=="object"){let s=t,i=l=>l&&typeof l=="object"?l.message:void 0,a=[s.message,s.errorMessage,s.error,s.error_description,s.detail,i(s.error),i(s.data)];for(let l of a)if(typeof l=="string"&&l.trim())return l.trim()}return o}function Jz(e){return e instanceof $e?e.details||e.shortMessage:e instanceof Error?e.message:typeof e=="string"?e:""}var $e=class extends Error{name="BaseError";shortMessage;details;metaMessages;constructor(t,n={}){let r=n.details??Jz(n.cause),o=n.metaMessages??[],s=[t||"An error occurred.",...o.length>0?["",...o]:[],...r?["",`Details: ${r}`]:[]].join(`
|
|
8
|
+
`)}function YH(e){return QH(e).slice(0,99)}function QH(e,t=[]){let n=e.flatMap(r=>{let o=[...t,...r.path];return r.code==="invalid_union"?r.errors.flatMap(s=>QH(s,o)):[{code:r.code,message:r.message,path:o.length===0?null:xee(o)}]});return vee(n)}function vee(e){let t=new Set,n=[];for(let r of e){let o=`${r.code}:${r.path??""}:${r.message}`;t.has(o)||(t.add(o),n.push(r))}return n.sort(kee)}function kee(e,t){return e.path===null&&t.path!==null?-1:e.path!==null&&t.path===null?1:(e.path??"").localeCompare(t.path??"")}function xee(e){return e.reduce((t,n)=>typeof n=="number"?`${t}[${n.toString()}]`:typeof n!="string"?t:n.includes('"')?`${t}["${n.replaceAll('"','\\"')}"]`:yee.test(n)?t.length===0?n:`${t}.${n}`:`${t}["${n}"]`,"")}function B(...e){return{isError(t){return e.some(n=>t instanceof n)}}}var yee,E,Ol,C,_,SC,Yr,PC,O,$,tt,Xw,en,bt,So,lf,Jw,ue,Zw=L(()=>{"use strict";Qw();Tl();yee=/^[$A-Z_a-z][$\w]*$/;E=class XH extends Ct{name="UserInputError";constructor(t,n={}){super(t,n)}static fromZodError(t){return new XH(bee(t),{cause:t})}},Ol=class extends Ct{name="PaginationLimitError";constructor(e,t={}){super(e,t)}},C=class JH extends Ct{name="UnexpectedResponseError";constructor(t,n={}){super(t,n)}static fromZodError(t,n){return new JH(wee(t,n),{cause:t})}},_=class ZH extends Ct{name="TransportError";constructor(t,n={}){super(t,n)}static fromError(t){return new ZH(t instanceof Error?t.message:"Request failed",{cause:t})}},SC=(e=>(e[e.NormalClosure=1e3]="NormalClosure",e[e.GoingAway=1001]="GoingAway",e[e.ProtocolError=1002]="ProtocolError",e[e.UnsupportedData=1003]="UnsupportedData",e[e.NoStatusReceived=1005]="NoStatusReceived",e[e.AbnormalClosure=1006]="AbnormalClosure",e[e.InvalidFramePayload=1007]="InvalidFramePayload",e[e.PolicyViolation=1008]="PolicyViolation",e[e.MessageTooBig=1009]="MessageTooBig",e[e.InternalError=1011]="InternalError",e[e.ServiceRestart=1012]="ServiceRestart",e[e.TryAgainLater=1013]="TryAgainLater",e))(SC||{}),Yr=class extends Ct{name="ConnectionLostError";code;reason;constructor(e,t){super(e,t),this.code=t.code,this.reason=t.reason}},PC=(e=>(e.RESTARTING="restarting",e.POST_ONLY="post_only",e))(PC||{}),O=class extends Ct{name="RequestRejectedError";status;code;retryAfter;restriction;constructor(e,t){super(e,t),this.status=t.status,this.code=t.code,this.retryAfter=t.retryAfter,this.restriction=t.restriction}},$=class extends Ct{name="RateLimitError";retryAfter;rateLimit;constructor(e,t={}){super(e,t),this.retryAfter=t.retryAfter,this.rateLimit=t.rateLimit}},tt=class extends Ct{name="TimeoutError";constructor(e,t={}){super(e,t)}},Xw=class e3 extends Ct{name="OperationAbortedError";constructor(t,n={}){super(t,n)}static fromReason(t){return new e3("Operation was aborted.",{cause:t})}},en=class extends Ct{name="TransactionFailedError";constructor(e,t={}){super(e,t)}},bt=class t3 extends Ct{name="CancelledSigningError";constructor(t,n={}){super(t,n)}static fromError(t){return new t3(t.message,{cause:t})}},So=class extends Ct{name="InsufficientLiquidityError";constructor(e,t={}){super(e,t)}},lf=class extends Ct{name="AutoCancelDailyLimitError";constructor(e,t={}){super(e,t)}},Jw=class extends Ct{name="PerpsCancelRetryError";results;pendingIndexes;constructor(e,t){super(e,t),this.results=[...t.results],this.pendingIndexes=[...t.pendingIndexes]}},ue=class n3 extends Ct{name="SigningError";constructor(t,n={}){super(t,n)}static fromError(t,n){let r=n??(t instanceof Error?t.message:"Signing failed");return new n3(r,{cause:t})}}});var cf=L(()=>{"use strict";xo()});var o3,Rr,EC,RC=L(()=>{"use strict";o3=require("zod"),Rr=(e=>(e[e.EOA=0]="EOA",e[e.POLY_PROXY=1]="POLY_PROXY",e[e.POLY_GNOSIS_SAFE=2]="POLY_GNOSIS_SAFE",e[e.POLY_1271=3]="POLY_1271",e))(Rr||{}),EC=o3.z.enum(Rr)});function e0(e){return A.z.object({count:A.z.number(),data:A.z.array(e),limit:A.z.number(),next_cursor:A.z.string()}).transform(({next_cursor:t,...n})=>({...n,nextCursor:t}))}function is(e,t){return A.z.object({id:a_,owner:os,payload:t,timestamp:Yee,type:A.z.literal(e)})}function fte(e){return e.success&&e.errorMsg===""&&e.orderID!==""&&wte(e.status)}function gte(e){switch(e){case"live":return"live";case"matched":return"matched";case"delayed":return"delayed";default:YF(`Unexpected order post status: ${e}`)}}function yte(e){return fte(e)?mte.parse({makingAmount:e.makingAmount,ok:!0,orderId:e.orderID,status:gte(e.status),takingAmount:e.takingAmount,tradeIds:e.tradeIDs,transactionsHashes:e.transactionsHashes}):hte.parse({code:bte(e),message:e.errorMsg||"Unknown order failure",ok:!1})}function bte(e){if(e.status==="unmatched")return"unmatched";switch(e.errorMsg){case"the market is not yet ready to process new orders":return"market_not_ready";case"invalid nonce":return"invalid_nonce";case"invalid expiration":return"invalid_expiration";case"invalid post-only order: order crosses book":return"post_only_would_cross";case"post-only mode: only post-only orders and cancels are allowed":return"post_only_mode";case"order couldn't be fully filled. FOK orders are fully filled or killed.":return"fok_not_filled";case"no orders found to match with FAK order. FAK orders are partially filled or killed if no match is found.":return"fak_not_filled"}return e.errorMsg.includes("not enough balance / allowance")?"insufficient_balance_or_allowance":"unknown"}function wte(e){return e==="live"||e==="matched"||e==="delayed"}var A,c3,IC,u3,Aee,Tee,d3,sa,p3,m3,h3,f3,See,g3,Pee,y3,b3,Eee,Ree,Iee,_ee,w3,_C,v3,k3,s3,x3,Cee,A3,i3,Nee,T3,S3,P3,E3,R3,Oee,I3,_3,C3,Lee,N3,Dee,O3,Uee,L3,Bee,Mee,Fee,D3,qee,U3,t0,Hee,CC,$ee,Vee,B3,jee,zee,Wee,Gee,Kee,Yee,Qee,Xee,Jee,Zee,ete,tte,nte,rte,ote,ste,ite,ate,M3,a3,lte,cte,F3,q3,H3,l3,ute,n0,dte,r0,pte,mte,hte,NC,$3,Yn,vte,kte,V3,xte,Ate,Tte,j3,Ste,z3,Pte,W3,OC=L(()=>{"use strict";RC();$h();xo();A=require("zod");Tl();c3=A.z.object({closed_only:A.z.boolean()}).transform(({closed_only:e})=>({closedOnly:e})),IC=A.z.object({asset_id:Me,associate_trades:A.z.array(A.z.string()),created_at:Xi,expiration:r_,id:A.z.string(),maker_address:A.z.string(),market:xe,order_type:A.z.string(),original_size:R,outcome:A.z.string(),owner:A.z.string(),price:R,side:A.z.string(),size_matched:R,status:A.z.string()}).transform(({asset_id:e,associate_trades:t,created_at:n,expiration:r,maker_address:o,market:s,order_type:i,original_size:a,size_matched:l,...c})=>{let u={...c,conditionId:s,assetId:e,tokenId:e,associateTrades:t,createdAt:n,makerAddress:o,orderType:i,originalSize:a,sizeMatched:l};return r===void 0?u:{...u,expiresAt:r}}),u3=e0(IC),Aee=A.z.object({asset_id:Me,fee_rate_bps:A.z.preprocess(Gn,R.nullable()),maker_address:A.z.string(),matched_amount:R,order_id:A.z.string(),outcome:A.z.string(),owner:A.z.string(),price:R,side:A.z.string()}).transform(({asset_id:e,fee_rate_bps:t,maker_address:n,matched_amount:r,order_id:o,...s})=>({...s,assetId:e,tokenId:e,feeRateBps:t,makerAddress:n,matchedAmount:r,orderId:o})),Tee=A.z.object({asset_id:Me,bucket_index:A.z.number(),fee_rate_bps:R,id:A.z.string(),last_update:Xi,maker_address:A.z.string(),maker_orders:A.z.array(Aee),market:xe,match_time:Xi,outcome:A.z.string(),owner:A.z.string(),price:R,side:A.z.string(),size:R,status:Lh,taker_order_id:A.z.string(),trader_side:A.z.enum(["TAKER","MAKER"]),transaction_hash:A.z.preprocess(gd,A.z.string().optional())}).transform(({asset_id:e,bucket_index:t,fee_rate_bps:n,last_update:r,maker_address:o,maker_orders:s,market:i,match_time:a,taker_order_id:l,trader_side:c,transaction_hash:u,...d})=>({...d,conditionId:i,assetId:e,tokenId:e,bucketIndex:t,feeRateBps:n,updatedAt:r,makerAddress:o,makerOrders:s,matchedAt:a,takerOrderId:l,traderSide:c,transactionHash:u})),d3=e0(Tee),sa=(e=>(e.COLLATERAL="COLLATERAL",e.CONDITIONAL="CONDITIONAL",e.CONDITIONAL_V2="CONDITIONAL-V2",e))(sa||{}),p3=A.z.enum(sa),m3=A.z.object({allowances:A.z.record(J,A.z.string().transform(BigInt)),balance:ss}),h3=A.z.object({scoring:A.z.boolean()}),f3=A.z.record(A.z.string(),A.z.boolean()),See=A.z.object({asset_address:A.z.string(),asset_rate:H,condition_id:xe,date:un,earnings:H,maker_address:A.z.string()}).transform(({asset_address:e,asset_rate:t,condition_id:n,maker_address:r,...o})=>({...o,assetAddress:e,assetRate:t,conditionId:n,makerAddress:r})),g3=e0(See),Pee=A.z.object({asset_address:A.z.string(),asset_rate:H,date:un,earnings:H,maker_address:A.z.string()}).transform(({asset_address:e,asset_rate:t,maker_address:n,...r})=>({...r,assetAddress:e,assetRate:t,makerAddress:n})),y3=A.z.array(Pee),b3=A.z.record(xe,A.z.number()),Eee=A.z.object({outcome:A.z.string(),price:H,token_id:Me}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Ree=A.z.object({asset_address:A.z.string(),end_date:un,rate_per_day:H,start_date:un,total_rewards:H}).transform(({asset_address:e,end_date:t,rate_per_day:n,start_date:r,total_rewards:o})=>({assetAddress:e,endDate:t,ratePerDay:n,startDate:r,totalRewards:o})),Iee=A.z.object({asset_address:A.z.string(),asset_rate:H,earnings:H}).transform(({asset_address:e,asset_rate:t,...n})=>({...n,assetAddress:e,assetRate:t})),_ee=A.z.object({condition_id:xe,earning_percentage:A.z.number(),earnings:A.z.array(Iee),event_slug:A.z.string(),image:A.z.string(),maker_address:A.z.string(),market_competitiveness:A.z.number(),market_slug:A.z.string(),question:A.z.string(),rewards_config:A.z.array(Ree),rewards_max_spread:A.z.number(),rewards_min_size:H,tokens:A.z.array(Eee)}).transform(({condition_id:e,earning_percentage:t,event_slug:n,maker_address:r,market_competitiveness:o,market_slug:s,rewards_config:i,rewards_max_spread:a,rewards_min_size:l,...c})=>({...c,conditionId:e,earningPercentage:t,eventSlug:n,makerAddress:r,marketCompetitiveness:o,marketSlug:s,rewardsConfig:i,rewardsMaxSpread:a,rewardsMinSize:l})),w3=e0(_ee),_C=A.z.object({apiKey:os,secret:A.z.string(),passphrase:A.z.string()}).transform(e=>({key:e.apiKey,passphrase:e.passphrase,secret:e.secret})),v3=A.z.object({apiKeys:A.z.array(os)}),k3=A.z.object({key:os,secret:A.z.string(),passphrase:A.z.string()}),s3=A.z.object({key:os,createdAt:un.optional(),revokedAt:un.nullable().optional()}),x3=A.z.array(A.z.union([os.transform(e=>({key:e})),s3])).transform(e=>e.map(t=>s3.parse(t))),Cee=A.z.object({id:A.z.string(),tradeType:A.z.string(),takerOrderHash:A.z.string(),builder:A.z.string(),market:xe,assetId:Me,side:Nt,size:R,sizeUsdc:R,price:R,status:A.z.string(),outcome:A.z.string(),outcomeIndex:A.z.number().int(),owner:A.z.string(),maker:A.z.string(),transactionHash:A.z.string(),matchTime:Xi,bucketIndex:A.z.number().int(),fee:R,feeUsdc:R,err_msg:A.z.string().nullable().optional(),createdAt:un.optional(),updatedAt:un.optional()}).transform(({err_msg:e,assetId:t,market:n,matchTime:r,...o})=>({...o,conditionId:n,assetId:t,tokenId:t,errMsg:e,matchedAt:r})),A3=A.z.object({limit:A.z.number().int(),count:A.z.number().int(),next_cursor:A.z.string(),data:A.z.array(Cee)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),i3=1e4,Nee=A.z.object({builder_maker_fee_rate_bps:A.z.number(),builder_taker_fee_rate_bps:A.z.number()}).transform(({builder_maker_fee_rate_bps:e,builder_taker_fee_rate_bps:t})=>({maker:e/i3,taker:t/i3})),T3=Nee,S3=A.z.object({canceled:A.z.array(fd),not_canceled:A.z.record(fd,A.z.string())}).transform(({canceled:e,not_canceled:t})=>({canceled:e,notCanceled:t})),P3=A.z.object({mid:R}),E3=A.z.record(Me,R),R3=A.z.object({price:R}),Oee=A.z.partialRecord(Nt,R),I3=A.z.record(Me,Oee),_3=A.z.object({spread:R}),C3=A.z.record(Me,R),Lee=A.z.object({price:R,side:Nt}),N3=Lee.extend({side:A.z.union([Nt,A.z.literal("")])}).transform(e=>e.side===""?null:{price:e.price,side:e.side}),Dee=A.z.object({price:R,side:Nt,token_id:Me}).transform(({token_id:e,price:t,side:n})=>({assetId:e,tokenId:e,price:t,side:n})),O3=A.z.array(Dee),Uee=A.z.object({condition_id:xe}).transform(({condition_id:e})=>e),L3=Uee,Bee=A.z.object({r:A.z.number().default(0),e:A.z.number().default(0)}).transform(({r:e,e:t})=>({rate:e,exponent:t})),Mee=A.z.object({t:Me,o:A.z.string()}).transform(({t:e,o:t})=>({assetId:e,tokenId:e,outcome:t})),Fee=A.z.object({fd:Bee.nullish(),mts:Pl,nr:A.z.boolean().optional(),t:A.z.array(Mee)}).transform(({fd:e,mts:t,nr:n,t:r})=>({feeInfo:e??{rate:0,exponent:0},negRisk:n??!1,tickSize:t,tokens:r})),D3=Fee,qee=A.z.object({neg_risk:A.z.boolean()}).transform(({neg_risk:e,...t})=>({...t,negRisk:e})),U3=qee,t0=(e=>(e[e.ORDER_CANCELLATION=1]="ORDER_CANCELLATION",e[e.ORDER_FILL=2]="ORDER_FILL",e[e.MARKET_REGISTERED=3]="MARKET_REGISTERED",e[e.MARKET_RESOLVED=4]="MARKET_RESOLVED",e[e.REWARD_PAYOUT=5]="REWARD_PAYOUT",e[e.CHILD_COMMENT_CREATED=6]="CHILD_COMMENT_CREATED",e[e.YIELD_PAYOUT=7]="YIELD_PAYOUT",e[e.ORDER_FILL_FAILED=8]="ORDER_FILL_FAILED",e[e.AUTO_REDEEMED=9]="AUTO_REDEEMED",e[e.COMBO_AUTO_REDEEMED=10]="COMBO_AUTO_REDEEMED",e))(t0||{}),Hee=A.z.enum(t0),CC=A.z.object({asset_id:Me,eventSlug:A.z.string().optional(),icon:A.z.string().optional(),image:A.z.string().optional(),market:xe,market_slug:A.z.string().optional(),matched_size:R,order_id:fd,original_size:R,outcome:A.z.string(),outcome_index:A.z.number().int(),price:R,question:A.z.string().optional(),remaining_size:R,seriesSlug:A.z.string().optional(),side:Nt,trade_id:A.z.preprocess(gd,A.z.string().optional()),transaction_hash:A.z.preprocess(gd,et.optional()),type:A.z.preprocess(gd,Oh.optional())}).transform(({asset_id:e,market:t,market_slug:n,matched_size:r,order_id:o,original_size:s,outcome_index:i,remaining_size:a,trade_id:l,transaction_hash:c,type:u,...d})=>({...d,conditionId:t,assetId:e,tokenId:e,marketSlug:n,matchedSize:r,orderId:o,orderType:u,originalSize:s,outcomeIndex:i,remainingSize:a,tradeId:l,transactionHash:c})),$ee=A.z.object({outcome:A.z.string(),price:H.optional(),token_id:Me,winner:A.z.boolean()}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Vee=A.z.object({max_spread:A.z.number(),min_size:H,rates:A.z.array(A.z.object({asset_address:A.z.string(),rewards_daily_rate:H}).transform(({asset_address:e,rewards_daily_rate:t})=>({assetAddress:e,dailyRate:t}))).nullish()}).transform(({max_spread:e,min_size:t,...n})=>({...n,maxSpread:e,minSize:t})),B3=A.z.object({accepting_order_timestamp:hd.nullish(),accepting_orders:A.z.boolean(),active:A.z.boolean(),archived:A.z.boolean().optional(),closed:A.z.boolean(),condition_id:xe,description:A.z.string(),enable_order_book:A.z.boolean().optional(),end_date_iso:hd.nullish(),eventSlug:A.z.string().optional(),fpmm:A.z.string(),game_start_time:hd.nullish(),icon:A.z.string(),image:A.z.string(),is_50_50_outcome:A.z.boolean().optional(),maker_base_fee:A.z.number().nullable(),market_slug:A.z.string(),minimum_order_size:H,minimum_tick_size:H,neg_risk:A.z.boolean().optional(),neg_risk_market_id:A.z.string().optional(),neg_risk_request_id:A.z.string().optional(),notifications_enabled:A.z.boolean().optional(),question:A.z.string(),question_id:vo,rewards:Vee.optional(),seconds_delay:A.z.number().int(),tags:A.z.array(A.z.string()).nullish(),taker_base_fee:A.z.number().nullable(),tokens:A.z.array($ee)}).transform(({accepting_order_timestamp:e,accepting_orders:t,condition_id:n,enable_order_book:r,end_date_iso:o,game_start_time:s,is_50_50_outcome:i,maker_base_fee:a,market_slug:l,minimum_order_size:c,minimum_tick_size:u,neg_risk:d,neg_risk_market_id:p,neg_risk_request_id:m,notifications_enabled:g,question_id:f,seconds_delay:y,taker_base_fee:w,...v})=>({...v,acceptingOrders:t,acceptingOrdersTimestamp:e,conditionId:n,enableOrderBook:r,endDate:o,gameStartTime:s,is5050Outcome:i,makerBaseFee:a,marketSlug:l,minimumOrderSize:c,minimumTickSize:u,negRisk:d,negRiskMarketId:p,negRiskRequestId:m,notificationsEnabled:g,questionId:f,secondsDelay:y,takerBaseFee:w})),jee=A.z.object({proxyWallet:J,reward:H,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),zee=A.z.object({amount:H,proxyWallet:J,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),Wee=A.z.object({body:A.z.string().nullish(),createdAt:oe.nullish(),eventSlug:A.z.string().nullish(),eventTitle:A.z.string().nullish(),id:Xs,image:A.z.string().nullish(),parentCommentID:Xs.nullish(),parentEntityID:A.z.number().int().nullish(),parentEntityType:Js.nullish(),profile:Rl.nullish(),seriesSlug:A.z.string().nullish(),seriesTitle:A.z.string().nullish(),userAddress:A.z.string().nullish()}),Gee=A.z.object({amount:H,conditionId:xe,image:A.z.string(),marketUrl:A.z.string().optional(),negRisk:A.z.boolean(),portfolioUrl:A.z.string().optional(),position:A.z.string().optional(),proxyWallet:J,question:A.z.string(),slug:A.z.string(),txnHash:et}).transform(({slug:e,txnHash:t,...n})=>({...n,marketSlug:e,transactionHash:t})),Kee=A.z.object({amount:H,conditionId:Zt,legs:A.z.number().int(),outcomeIndex:A.z.number().int(),portfolioUrl:A.z.string().optional(),positionId:Xe,proxyWallet:J,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),Yee=A.z.preprocess(e=>typeof e!="string"?e:/^\d+$/.test(e)?Number(e):Date.parse(e),pe);Qee=is(1,CC),Xee=is(2,CC),Jee=is(3,B3),Zee=is(4,B3),ete=is(5,jee),tte=is(6,Wee),nte=is(7,zee),rte=is(8,CC),ote=is(9,Gee),ste=is(10,Kee),ite=A.z.discriminatedUnion("type",[Qee,Xee,Jee,Zee,ete,tte,nte,rte,ote,ste]),ate=A.z.object({type:A.z.number().int()}),M3=A.z.array(A.z.unknown()).transform((e,t)=>{let n=[];return e.forEach((r,o)=>{let s=ate.safeParse(r);if(!s.success){for(let a of s.error.issues)t.addIssue({...a,path:[o,...a.path]});return}if(!Hee.safeParse(s.data.type).success)return;let i=ite.safeParse(r);if(i.success){n.push(i.data);return}for(let a of i.error.issues)t.addIssue({...a,path:[o,...a.path]})}),n}),a3=A.z.object({price:R,size:R}),lte=A.z.string().regex(/^[a-f0-9]{40}$/).transform(e=>e),cte=R.transform(Number).pipe(Pl),F3=A.z.object({market:xe,asset_id:Me,timestamp:Pr.nullish(),bids:A.z.array(a3),asks:A.z.array(a3),min_order_size:R,tick_size:cte,neg_risk:A.z.boolean(),last_trade_price:R.nullish(),hash:lte}).transform(({market:e,asset_id:t,min_order_size:n,tick_size:r,neg_risk:o,last_trade_price:s,...i})=>({...i,conditionId:e,assetId:t,tokenId:t,minOrderSize:n,tickSize:r,negRisk:o,lastTradePrice:s})),q3=F3,H3=A.z.array(F3),l3=A.z.preprocess(e=>e===""?"0":e,R),ute=A.z.object({errorMsg:A.z.string(),makingAmount:l3,orderID:A.z.string(),status:A.z.string(),success:A.z.boolean(),takingAmount:l3,tradeIDs:A.z.array(A.z.string()).default([]),transactionsHashes:A.z.array(A.z.string()).default([])}),n0=(e=>(e.LIVE="live",e.MATCHED="matched",e.DELAYED="delayed",e))(n0||{}),dte=A.z.nativeEnum(n0),r0=(e=>(e.UNMATCHED="unmatched",e.MARKET_NOT_READY="market_not_ready",e.INSUFFICIENT_BALANCE_OR_ALLOWANCE="insufficient_balance_or_allowance",e.INVALID_NONCE="invalid_nonce",e.INVALID_EXPIRATION="invalid_expiration",e.POST_ONLY_WOULD_CROSS="post_only_would_cross",e.POST_ONLY_MODE="post_only_mode",e.FOK_NOT_FILLED="fok_not_filled",e.FAK_NOT_FILLED="fak_not_filled",e.UNKNOWN="unknown",e))(r0||{}),pte=A.z.nativeEnum(r0),mte=A.z.object({ok:A.z.literal(!0),orderId:fd.refine(e=>e.length>0),status:dte,makingAmount:R,takingAmount:R,tradeIds:A.z.array(A.z.string()),transactionsHashes:A.z.array(et)}),hte=A.z.object({ok:A.z.literal(!1),code:pte,message:A.z.string().min(1)}),NC=ute.transform(yte),$3=A.z.array(NC);Yn="LTE=",vte=A.z.object({id:A.z.number().int().optional(),asset_address:A.z.string(),start_date:un,end_date:un.optional(),rate_per_day:H,total_rewards:H.optional()}).transform(({asset_address:e,start_date:t,end_date:n,rate_per_day:r,total_rewards:o,...s})=>({...s,assetAddress:e,startDate:t,endDate:n,ratePerDay:r,totalRewards:o})),kte=A.z.object({condition_id:xe,rewards_max_spread:A.z.number().optional(),rewards_min_size:H.optional(),rewards_config:A.z.array(vte).optional(),sponsored_daily_rate:H.optional(),sponsors_count:A.z.number().int().optional(),native_daily_rate:H.optional(),total_daily_rate:H.optional()}).transform(({condition_id:e,rewards_max_spread:t,rewards_min_size:n,rewards_config:r,sponsored_daily_rate:o,sponsors_count:s,native_daily_rate:i,total_daily_rate:a,...l})=>({...l,conditionId:e,rewardsMaxSpread:t,rewardsMinSize:n,rewardsConfig:r,sponsoredDailyRate:o,sponsorsCount:s,nativeDailyRate:i,totalDailyRate:a})),V3=A.z.object({limit:A.z.number().int(),count:A.z.number().int(),next_cursor:A.z.string(),data:A.z.array(kte)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),xte=A.z.object({token_id:Me,outcome:A.z.string(),price:H}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Ate=A.z.object({asset_address:A.z.string(),start_date:un,end_date:un.optional(),rate_per_day:H,total_rewards:H.optional()}).transform(({asset_address:e,start_date:t,end_date:n,rate_per_day:r,total_rewards:o,...s})=>({...s,assetAddress:e,startDate:t,endDate:n,ratePerDay:r,totalRewards:o})),Tte=A.z.object({condition_id:xe,question:A.z.string(),market_slug:A.z.string().optional(),event_slug:A.z.string().optional(),image:A.z.string().optional(),rewards_max_spread:A.z.number().optional(),rewards_min_size:H.optional(),market_competitiveness:A.z.number().optional(),tokens:A.z.array(xte),rewards_config:A.z.array(Ate).optional()}).transform(({condition_id:e,market_slug:t,event_slug:n,rewards_max_spread:r,rewards_min_size:o,market_competitiveness:s,rewards_config:i,...a})=>({...a,conditionId:e,marketSlug:t,eventSlug:n,rewardsMaxSpread:r,rewardsMinSize:o,marketCompetitiveness:s,rewardsConfig:i})),j3=A.z.object({limit:A.z.number().int(),count:A.z.number().int(),next_cursor:A.z.string(),data:A.z.array(Tte)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),Ste=A.z.object({address:J,scopes:A.z.array(Ih).min(1),valid_until:A.z.number().int().nonnegative()}).transform(({valid_until:e,...t})=>({...t,validUntil:e})),z3=A.z.object({signers:A.z.array(Ste),wallet:J}),Pte=A.z.object({minimum_tick_size:Pl}).transform(({minimum_tick_size:e,...t})=>({...t,minimumTickSize:e})),W3=Pte});var ae,uf,Ete,Rte,G3,iCe,Ite,_te,K3,Cte,Nte,Y3,Id,Ote,Q3,LC,DC,UC,X3,Se,aCe,o0=L(()=>{"use strict";$h();$h();xo();ae=require("zod"),uf=(e=>(e.Pending="pending",e.Queued="queued",e.Success="success",e.Failed="failed",e.Cancelled="cancelled",e))(uf||{}),Ete=ae.z.union([ae.z.string(),ae.z.number().int().transform(String)]).transform(xw),Rte=ae.z.object({id:ae.z.number().int(),marketId:Ete.nullish(),eventId:Gt.nullish(),questionId:vo.nullish(),content:ae.z.string().nullish(),state:ae.z.enum(uf).nullish(),clearBook:ae.z.boolean().nullish(),notifyDiscord:ae.z.boolean().nullish(),showInFrontend:ae.z.boolean().nullish(),adapterAddress:J.nullish(),negRiskRequestId:ae.z.string().nullish(),txHash:et.nullish(),createdAt:oe.nullish(),queuedAt:oe.nullish(),scheduledFor:oe.nullish(),txTimestamp:oe.nullish()}),G3=ae.z.array(Rte),iCe=ae.z.object({hasMore:ae.z.boolean().nullish(),totalResults:ae.z.number().int().nullish()}),Ite=ae.z.object({id:ae.z.string(),communityMod:ae.z.boolean().nullish(),creator:ae.z.boolean().nullish(),mod:ae.z.boolean().nullish()}),_te=ae.z.object({id:ae.z.string().nullish(),name:ae.z.string().nullish(),user:ae.z.number().int().nullish(),referral:ae.z.string().nullish(),createdBy:ae.z.number().int().nullish(),updatedBy:ae.z.number().int().nullish(),createdAt:oe.nullish(),updatedAt:oe.nullish(),utmSource:ae.z.string().nullish(),utmMedium:ae.z.string().nullish(),utmCampaign:ae.z.string().nullish(),utmContent:ae.z.string().nullish(),utmTerm:ae.z.string().nullish(),walletActivated:ae.z.boolean().nullish(),pseudonym:ae.z.string().nullish(),displayUsernamePublic:ae.z.boolean().nullish(),profileImage:ae.z.string().nullish(),bio:ae.z.string().nullish(),proxyWallet:ae.z.string().nullish(),profileImageOptimized:Zs.nullish(),isCloseOnly:ae.z.boolean().nullish(),isCertReq:ae.z.boolean().nullish(),certReqDate:oe.nullish(),discordUsername:ae.z.string().nullish(),xUsername:ae.z.string().nullish(),verifiedBadge:ae.z.boolean().nullish(),dubPartnerId:ae.z.string().nullish(),termsAcceptedAt:oe.nullish(),viewOnlyAcknowledgedAt:oe.nullish(),isReferralRestricted:ae.z.boolean().nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),K3=ae.z.object({createdAt:oe.nullish(),proxyWallet:J.nullish(),profileImage:ae.z.string().nullish(),displayUsernamePublic:ae.z.boolean().nullish(),bio:ae.z.string().nullish(),pseudonym:ae.z.string().nullish(),name:ae.z.string().nullish(),users:ae.z.array(Ite).nullish(),xUsername:ae.z.string().nullish(),verifiedBadge:ae.z.boolean().nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),Cte=ae.z.object({id:Dh,event_count:ae.z.number().int().nullish(),label:ae.z.string().nullish(),slug:ae.z.string().nullish()}).transform(({event_count:e,...t})=>({...t,eventCount:e})),Nte=ae.z.object({hasMore:ae.z.boolean().nullish(),totalResults:ae.z.number().int().nullish()}),Y3=ae.z.object({events:ae.z.array(ei).nullish(),tags:ae.z.array(Cte).nullish(),profiles:ae.z.array(_te).nullish(),pagination:Nte.nullish()}),Id=El.extend({templates:ae.z.array(Uw).nullish()}),Ote=ae.z.object({id:ae.z.string(),tagID:ae.z.number().int().nullish(),relatedTagID:ae.z.number().int().nullish(),rank:ae.z.number().int().nullish()}).transform(({tagID:e,relatedTagID:t,...n})=>({...n,tagId:e,relatedTagId:t})),Q3=ae.z.array(Id),LC=ae.z.array(Ote),DC=ae.z.array(Id),UC=Dw.extend({events:ae.z.array(ei).nullish(),collections:ae.z.array(Lw).nullish(),tags:ae.z.array(Id).nullish()}),X3=ae.z.array(UC),Se=(e=>(e[e.EOA=0]="EOA",e[e.POLY_PROXY=1]="POLY_PROXY",e[e.GNOSIS_SAFE=2]="GNOSIS_SAFE",e[e.DEPOSIT_WALLET=3]="DEPOSIT_WALLET",e))(Se||{}),aCe=ae.z.object({type:ae.z.enum(Se),typeName:ae.z.enum(["EOA","POLY_PROXY","GNOSIS_SAFE","DEPOSIT_WALLET"])})});var Ll,BC=L(()=>{"use strict";Ll=class extends Error{response;request;options;constructor(t,n,r){let o=t.status||t.status===0?t.status:"",s=t.statusText??"",i=`${o} ${s}`.trim(),a=i?`status code ${i}`:"an unknown error";super(`Request failed with ${a}: ${n.method} ${n.url}`),this.name="HTTPError",this.response=t,this.request=n,this.options=r}}});var _d,MC=L(()=>{"use strict";_d=class extends Error{name="NonError";value;constructor(t){let n="Non-error value was thrown";try{typeof t=="string"?n=t:t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"&&(n=t.message)}catch{}super(n),this.value=t}}});var Cd,J3=L(()=>{"use strict";MC();Cd=class extends Error{name="ForceRetryError";customDelay;code;customRequest;constructor(t){let n=t?.cause?t.cause instanceof Error?t.cause:new _d(t.cause):void 0;super(t?.code?`Forced retry: ${t.code}`:"Forced retry",n?{cause:n}:void 0),this.customDelay=t?.delay,this.code=t?.code,this.customRequest=t?.request}}});var FC,Z3,s0,e$,t$,i0,Lte,n$,a0,r$,l0,df,o$,s$,i$,a$,Dl=L(()=>{"use strict";FC=(()=>{let e=!1,t=!1,n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(n&&r)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(o){if(o instanceof Error&&o.message==="unsupported BodyInit type")return!1;throw o}return e&&!t})(),Z3=typeof globalThis.AbortController=="function",s0=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",e$=typeof globalThis.ReadableStream=="function",t$=typeof globalThis.FormData=="function",i0=["get","post","put","patch","head","delete"],Lte=()=>{};Lte();n$={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},a0=2147483647,r$=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,l0=Symbol("stop"),df=class{options;constructor(t){this.options=t}},o$=e=>new df(e),s$={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},i$={next:!0},a$={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0}});var Dte,l$,c$,u$,d$=L(()=>{"use strict";Dl();Dte=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=r$,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r=="string"?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},l$=(e,t,n)=>{let r,o=0;return e.pipeThrough(new TransformStream({transform(s,i){if(i.enqueue(s),r){o+=r.byteLength;let a=t===0?0:o/t;a>=1&&(a=1-Number.EPSILON),n?.({percent:a,totalBytes:Math.max(t,o),transferredBytes:o},r)}r=s},flush(){r&&(o+=r.byteLength,n?.({percent:1,totalBytes:Math.max(t,o),transferredBytes:o},r))}}))},c$=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let n=Math.max(0,Number(e.headers.get("content-length"))||0);return new Response(l$(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},u$=(e,t,n)=>{if(!e.body)return e;let r=Dte(n??e.body);return new Request(e,{duplex:"half",body:l$(e.body,r,t)})}});var ia,p$=L(()=>{"use strict";ia=e=>e!==null&&typeof e=="object"});function c0(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:$C(e[n]??[],t[n]??[])}var pf,qC,HC,Ute,$C,VC=L(()=>{"use strict";Dl();p$();pf=(...e)=>{for(let t of e)if((!ia(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return $C({},...e)},qC=(e={},t={})=>{let n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(let[s,i]of o.entries())r&&i==="undefined"||i===void 0?n.delete(s):n.set(s,i);return n};HC=(e={},t={})=>({beforeRequest:c0(e,t,"beforeRequest"),beforeRetry:c0(e,t,"beforeRetry"),afterResponse:c0(e,t,"afterResponse"),beforeError:c0(e,t,"beforeError")}),Ute=(e,t)=>{let n=new URLSearchParams;for(let r of[e,t])if(r!==void 0)if(r instanceof URLSearchParams)for(let[o,s]of r.entries())n.append(o,s);else if(Array.isArray(r))for(let o of r){if(!Array.isArray(o)||o.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");n.append(String(o[0]),String(o[1]))}else if(ia(r))for(let[o,s]of Object.entries(r))s!==void 0&&n.append(o,String(s));else{let o=new URLSearchParams(r);for(let[s,i]of o.entries())n.append(s,i)}return n},$C=(...e)=>{let t={},n={},r={},o,s=[];for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(ia(i)){for(let[a,l]of Object.entries(i)){if(a==="signal"&&l instanceof globalThis.AbortSignal){s.push(l);continue}if(a==="context"){if(l!=null&&(!ia(l)||Array.isArray(l)))throw new TypeError("The `context` option must be an object");t={...t,context:l==null?{}:{...t.context,...l}};continue}if(a==="searchParams"){l==null?o=void 0:o=o===void 0?l:Ute(o,l);continue}ia(l)&&a in t&&(l=$C(t[a],l)),t={...t,[a]:l}}ia(i.hooks)&&(r=HC(r,i.hooks),t.hooks=r),ia(i.headers)&&(n=qC(n,i.headers),t.headers=n)}return o!==void 0&&(t.searchParams=o),s.length>0&&(s.length===1?t.signal=s[0]:s0?t.signal=AbortSignal.any(s):t.signal=s.at(-1)),t}});var h$,Bte,Mte,Fte,m$,f$,g$=L(()=>{"use strict";Dl();h$=e=>i0.includes(e)?e.toUpperCase():e,Bte=["get","put","head","delete","options","trace"],Mte=[408,413,429,500,502,503,504],Fte=[413,429,503],m$={limit:2,methods:Bte,statusCodes:Mte,afterStatusCodes:Fte,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},f$=(e={})=>{if(typeof e=="number")return{...m$,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.methods&&=e.methods.map(n=>n.toLowerCase()),e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");let t=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));return{...m$,...t}}});var Ul,jC=L(()=>{"use strict";Ul=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}}});async function zC(e,t,n,r){return new Promise((o,s)=>{let i=setTimeout(()=>{n&&n.abort(),s(new Ul(e))},r.timeout);r.fetch(e,t).then(o).catch(s).then(()=>{clearTimeout(i)})})}var y$=L(()=>{"use strict";jC()});async function WC(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));function o(){clearTimeout(s),r(t.reason)}let s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e)})}var b$=L(()=>{"use strict"});var w$,v$,k$=L(()=>{"use strict";Dl();w$=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in a$)&&!(r in s$)&&(!(r in e)||r in i$)&&(n[r]=t[r]);return n},v$=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e});function x$(e){return e instanceof Ll||e?.name===Ll.name}function A$(e){return e instanceof Ul||e?.name===Ul.name}var T$=L(()=>{"use strict";BC();jC()});var mf,S$=L(()=>{"use strict";BC();MC();J3();d$();VC();g$();y$();b$();k$();T$();Dl();mf=class e{static create(t,n){let r=new e(t,n),o=async()=>{if(typeof r.#n.timeout=="number"&&r.#n.timeout>a0)throw new RangeError(`The \`timeout\` option cannot be greater than ${a0}`);await Promise.resolve();let i=await r.#y();for(let a of r.#n.hooks.afterResponse){let l=r.#c(i.clone()),c;try{c=await a(r.request,r.#h(),l,{retryCount:r.#r})}catch(d){throw r.#d(l),r.#d(i),d}if(c instanceof df)throw r.#d(l),r.#d(i),new Cd(c.options);let u=c instanceof globalThis.Response?c:i;l!==u&&r.#d(l),i!==u&&r.#d(i),i=u}if(r.#c(i),!i.ok&&(typeof r.#n.throwHttpErrors=="function"?r.#n.throwHttpErrors(i.status):r.#n.throwHttpErrors)){let a=new Ll(i,r.request,r.#h());for(let l of r.#n.hooks.beforeError)a=await l(a,{retryCount:r.#r});throw a}if(r.#n.onDownloadProgress){if(typeof r.#n.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!e$)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");let a=i.clone();return r.#d(i),c$(a,r.#n.onDownloadProgress)}return i},s=r.#m(o).finally(()=>{let i=r.#o;r.#p(i?.body??void 0),r.#p(r.request.body??void 0)});for(let[i,a]of Object.entries(n$))i==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(s[i]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||a);let l=await s;if(i==="json"){if(l.status===204)return"";let c=await l.text();return c===""?"":n.parseJson?n.parseJson(c):JSON.parse(c)}return l[i]()});return s}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t}request;#t;#r=0;#s;#n;#o;#i;#a;constructor(t,n={}){if(this.#s=t,this.#n={...n,headers:qC(this.#s.headers,n.headers),hooks:HC({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:h$(n.method??this.#s.method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:f$(n.retry),throwHttpErrors:n.throwHttpErrors??!0,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis),context:n.context??{}},typeof this.#s!="string"&&!(this.#s instanceof URL||this.#s instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this.#n.prefixUrl&&typeof this.#s=="string"){if(this.#s.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this.#n.prefixUrl.endsWith("/")||(this.#n.prefixUrl+="/"),this.#s=this.#n.prefixUrl+this.#s}Z3&&s0&&(this.#i=this.#n.signal??this.#s.signal,this.#t=new globalThis.AbortController,this.#n.signal=this.#i?AbortSignal.any([this.#i,this.#t.signal]):this.#t.signal),FC&&(this.#n.duplex="half"),this.#n.json!==void 0&&(this.#n.body=this.#n.stringifyJson?.(this.#n.json)??JSON.stringify(this.#n.json),this.#n.headers.set("content-type",this.#n.headers.get("content-type")??"application/json"));let r=n.headers&&new globalThis.Headers(n.headers).has("content-type");if(this.#s instanceof globalThis.Request&&(t$&&this.#n.body instanceof globalThis.FormData||this.#n.body instanceof URLSearchParams)&&!r&&this.#n.headers.delete("content-type"),this.request=new globalThis.Request(this.#s,this.#n),v$(this.#n.searchParams)){let s="?"+(typeof this.#n.searchParams=="string"?this.#n.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this.#n.searchParams)).toString()),i=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,s);this.request=new globalThis.Request(i,this.#n)}if(this.#n.onUploadProgress){if(typeof this.#n.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!FC)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#g(this.request,this.#n.body??void 0)}}#u(){let t=this.#n.retry.delay(this.#r),n=t;this.#n.retry.jitter===!0?n=Math.random()*t:typeof this.#n.retry.jitter=="function"&&(n=this.#n.retry.jitter(t),(!Number.isFinite(n)||n<0)&&(n=t));let r=this.#n.retry.backoffLimit??Number.POSITIVE_INFINITY;return Math.min(r,n)}async#l(t){if(this.#r++,this.#r>this.#n.retry.limit)throw t;let n=t instanceof Error?t:new _d(t);if(n instanceof Cd)return n.customDelay??this.#u();if(!this.#n.retry.methods.includes(this.request.method.toLowerCase()))throw t;if(this.#n.retry.shouldRetry!==void 0){let r=await this.#n.retry.shouldRetry({error:n,retryCount:this.#r});if(r===!1)throw t;if(r===!0)return this.#u()}if(A$(t)&&!this.#n.retry.retryOnTimeout)throw t;if(x$(t)){if(!this.#n.retry.statusCodes.includes(t.response.status))throw t;let r=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Retry-After")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(r&&this.#n.retry.afterStatusCodes.includes(t.response.status)){let o=Number(r)*1e3;Number.isNaN(o)?o=Date.parse(r)-Date.now():o>=Date.parse("2024-01-01")&&(o-=Date.now());let s=this.#n.retry.maxRetryAfter??o;return o<s?o:s}if(t.response.status===413)throw t}return this.#u()}#c(t){return this.#n.parseJson&&(t.json=async()=>this.#n.parseJson(await t.text())),t}#p(t){t&&t.cancel().catch(()=>{})}#d(t){this.#p(t.body??void 0)}async#m(t){try{return await t()}catch(n){let r=Math.min(await this.#l(n),a0);if(this.#r<1)throw n;if(await WC(r,this.#i?{signal:this.#i}:{}),n instanceof Cd&&n.customRequest){let o=this.#n.signal?new globalThis.Request(n.customRequest,{signal:this.#n.signal}):new globalThis.Request(n.customRequest);this.#f(o)}for(let o of this.#n.hooks.beforeRetry){let s=await o({request:this.request,options:this.#h(),error:n,retryCount:this.#r});if(s instanceof globalThis.Request){this.#f(s);break}if(s instanceof globalThis.Response)return s;if(s===l0)return}return this.#m(t)}}async#y(){this.#t?.signal.aborted&&(this.#t=new globalThis.AbortController,this.#n.signal=this.#i?AbortSignal.any([this.#i,this.#t.signal]):this.#t.signal,this.request=new globalThis.Request(this.request,{signal:this.#n.signal}));for(let n of this.#n.hooks.beforeRequest){let r=await n(this.request,this.#h(),{retryCount:this.#r});if(r instanceof Response)return r;if(r instanceof globalThis.Request){this.#f(r);break}}let t=w$(this.request,this.#n);return this.#o=this.request,this.request=this.#o.clone(),this.#n.timeout===!1?this.#n.fetch(this.#o,t):zC(this.#o,t,this.#t,this.#n)}#h(){if(!this.#a){let{hooks:t,...n}=this.#n;this.#a=Object.freeze(n)}return this.#a}#f(t){this.#a=void 0,this.request=this.#g(t)}#g(t,n){return!this.#n.onUploadProgress||!t.body?t:u$(t,this.#n.onUploadProgress,n??this.#n.body??void 0)}}});var GC,qte,u0,P$=L(()=>{"use strict";S$();Dl();VC();GC=e=>{let t=(n,r)=>mf.create(n,pf(e,r));for(let n of i0)t[n]=(r,o)=>mf.create(r,pf(e,o,{method:n}));return t.create=n=>GC(pf(n)),t.extend=n=>(typeof n=="function"&&(n=n(e??{})),GC(pf(e,n))),t.stop=l0,t.retry=o$,t},qte=GC(),u0=qte});function Hte(e){let t=e.length===64?`${e}00`:e;return _h(t.toLowerCase())}function $te(e){if(e.length===66)return!0;let t=e.toLowerCase();return t.startsWith("0x01")||t.startsWith("0x02")}function ls(e){return U.z.object({data:U.z.array(e),pagination:U.z.object({limit:U.z.number().int(),offset:U.z.number().int(),has_more:U.z.boolean(),next_cursor:U.z.string().min(1).nullable()})}).refine(t=>t.pagination.has_more===(t.pagination.next_cursor!==null),{message:"has_more and next_cursor must agree",path:["pagination","next_cursor"]}).transform(({data:t,pagination:n})=>({items:t,hasMore:n.has_more,nextCursor:n.next_cursor===null?void 0:n.next_cursor}))}function si(e){return U.z.object({data:e}).transform(t=>t.data)}function sne(e){let t=ine(e);switch(e.type){case"SPLIT":return{...t,type:"SPLIT"};case"MERGE":return{...t,type:"MERGE"};case"CONVERT":return{...t,type:"CONVERT"};case"COMPRESS":return{...t,type:"COMPRESS"};case"WRAP":return{...t,type:"WRAP"};case"UNWRAP":return{...t,type:"UNWRAP"};case"REDEEM":return{...t,type:"REDEEM",payout:e.payout_usdc??null}}}function ine(e){return{id:e.id,type:e.type,wallet:e.proxy_wallet,conditionId:e.combo_condition_id,positionId:e.combo_position_id,amount:e.amount_usdc??null,timestamp:e.timestamp,transactionHash:e.transaction_hash,blockNumber:e.block_number,legs:e.legs}}function ane(e){let t=cne(e);switch(e.type){case"TRADE":return lne(e,t);case"SPLIT":case"MERGE":case"REDEEM":case"CONVERSION":return{...t,type:e.type,conditionId:Ir(e.condition_id,"condition_id"),amount:e.usdc_size,title:Ir(e.title,"title"),slug:Ir(e.slug,"slug"),icon:e.icon??null,eventSlug:Ir(e.event_slug,"event_slug")};case"MIGRATION":case"REWARD":case"MAKER_REBATE":case"REFERRAL_REWARD":case"YIELD":case"DEPOSIT":case"WITHDRAWAL":case"TAKER_REBATE":return{...t,type:e.type,amount:e.usdc_size};case"TIP":return{...t,type:e.type,amount:e.usdc_size,side:e.side===void 0?null:R$.parse(e.side)}}}function lne(e,t){let n={...t,type:"TRADE",side:Nt.parse(Ir(e.side,"side")),shares:e.size,amount:e.usdc_size,price:e.price,title:Ir(e.title,"title"),icon:e.icon??null};if(e.is_combo===!0)return{...n,isCombo:!0,conditionId:Zt.parse(Ir(e.condition_id,"condition_id")),positionId:Xe.parse(Ir(e.token_id,"token_id"))};let r=Ir(e.token_id,"token_id");return{...n,isCombo:!1,conditionId:Ir(e.condition_id,"condition_id"),assetId:r,tokenId:r,outcome:Ir(e.outcome,"outcome"),outcomeIndex:e.outcome_index,slug:Ir(e.slug,"slug"),eventSlug:Ir(e.event_slug,"event_slug")}}function cne(e){return{wallet:e.proxy_wallet,timestamp:e.timestamp,transactionHash:e.transaction_hash,name:e.name??null,pseudonym:e.pseudonym??null,bio:e.bio??null,profileImage:e.profile_image??null,profileImageOptimized:e.profile_image_optimized??null}}function Ir(e,t){if(e==null)throw new TypeError(`Expected activity.${t} to be present`);return e}var U,p0,KC,Bl,R$,Ml,m0,Fl,I$,ql,ii,Nd,ai,_$,Vte,Hl,C$,$l,N$,Vl,O$,oi,jte,zte,Wte,jl,YC,zl,d0,pn,L$,Gte,Kte,Yte,Qte,Xte,D$,Jte,U$,B$,M$,F$,q$,H$,Wl,Zte,ene,tne,Kt,$$,nne,rne,one,V$,j$,z$,Po,W$,une,G$,hf,dne,pne,mne,hne,fne,K$,Y$,Q$,Gl,ff,Kl,X$,Yl,J$,Ql,YCe,gne,yne,as,bne,wne,vne,kne,xne,Z$,e4,t4,n4,r4,Xl,Ane,Jl,Tne,Zl,Sne,ec,Pne,E$,Ene,o4,h0=L(()=>{"use strict";xo();U=require("zod"),p0=(e=>(e.TRADE="TRADE",e.SPLIT="SPLIT",e.MERGE="MERGE",e.REDEEM="REDEEM",e.REWARD="REWARD",e.CONVERSION="CONVERSION",e.MIGRATION="MIGRATION",e.MAKER_REBATE="MAKER_REBATE",e.REFERRAL_REWARD="REFERRAL_REWARD",e.YIELD="YIELD",e.DEPOSIT="DEPOSIT",e.WITHDRAWAL="WITHDRAWAL",e.TAKER_REBATE="TAKER_REBATE",e.TIP="TIP",e))(p0||{}),KC=U.z.enum(p0),Bl=(e=>(e.In="IN",e.Out="OUT",e))(Bl||{}),R$=U.z.enum(Bl),Ml=(e=>(e.Asc="ASC",e.Desc="DESC",e))(Ml||{}),m0=U.z.enum(Ml),Fl=(e=>(e.Cash="CASH",e.Tokens="TOKENS",e))(Fl||{}),I$=U.z.enum(Fl);ql=xe.refine($te,"Expected a 32-byte condition ID or a 31-byte protocol v2 market condition ID").transform(Hte);ii=(e=>(e.Open="OPEN",e.Redeemable="REDEEMABLE",e.Partial="PARTIAL",e.ResolvedPartial="RESOLVED_PARTIAL",e.ResolvedWin="RESOLVED_WIN",e.ResolvedLoss="RESOLVED_LOSS",e))(ii||{}),Nd=U.z.enum(ii),ai=(e=>(e.Open="OPEN",e.Redeemable="REDEEMABLE",e.RedeemableLost="REDEEMABLE_LOST",e.Mergeable="MERGEABLE",e.Closed="CLOSED",e))(ai||{}),_$=U.z.enum(ai),Vte=U.z.enum(["OPEN","REDEEMABLE","CLOSED"]),Hl=(e=>(e.CurrentValue="CURRENT_VALUE",e.Tokens="TOKENS",e.UnrealizedPnl="UNREALIZED_PNL",e.RealizedPnl="REALIZED_PNL",e.TotalPnl="TOTAL_PNL",e.Timestamp="TIMESTAMP",e))(Hl||{}),C$=U.z.enum(Hl),$l=(e=>(e.Cash="CASH",e.Tokens="TOKENS",e))($l||{}),N$=U.z.enum($l),Vl=(e=>(e.FirstEntry="FIRST_ENTRY",e.EntryCost="ENTRY_COST",e.CurrentValue="CURRENT_VALUE",e.Updated="UPDATED",e))(Vl||{}),O$=U.z.enum(Vl),oi=U.z.preprocess(e=>e===""?void 0:e,U.z.string().optional()),jte=U.z.preprocess(e=>e===999?void 0:e,U.z.number().int().optional()),zte=U.z.object({proxy_wallet:J,token_id:Me,condition_id:xe,current_size:H,avg_price:H,entry_cost_usdc:H,entry_fees_usdc:H,total_cost_usdc:H,current_price:H,current_value:H,total_size:H,realized_pnl:H,unrealized_pnl:H,total_pnl:H,percent_pnl:H,percent_realized_pnl:H,status:Vte,redeemable:U.z.boolean(),mergeable:U.z.boolean(),negative_risk:U.z.boolean(),archived:U.z.boolean(),title:oi,slug:oi,icon:oi,event_id:oi,event_slug:oi,outcome:oi,outcome_index:jte,opposite_outcome:oi,opposite_token_id:U.z.preprocess(e=>e===""?void 0:e,Me.optional()),end_date:U.z.preprocess(e=>e===""?void 0:e,Wn.optional()),last_event_at:U.z.preprocess(e=>e===0?void 0:e,wo.optional()),name:oi,profile_image:oi,verified:U.z.boolean()}).transform(e=>({wallet:e.proxy_wallet,assetId:e.token_id,tokenId:e.token_id,conditionId:e.condition_id,currentSize:e.current_size,avgPrice:e.avg_price,entryCostUsdc:e.entry_cost_usdc,entryFeesUsdc:e.entry_fees_usdc,totalCostUsdc:e.total_cost_usdc,currentPrice:e.current_price,currentValue:e.current_value,totalSize:e.total_size,realizedPnl:e.realized_pnl,unrealizedPnl:e.unrealized_pnl,totalPnl:e.total_pnl,percentPnl:e.percent_pnl,percentRealizedPnl:e.percent_realized_pnl,status:e.status,redeemable:e.redeemable,mergeable:e.mergeable,negativeRisk:e.negative_risk,archived:e.archived,title:e.title,slug:e.slug,icon:e.icon,eventId:e.event_id,eventSlug:e.event_slug,outcome:e.outcome,outcomeIndex:e.outcome_index,oppositeOutcome:e.opposite_outcome,oppositeAssetId:e.opposite_token_id,oppositeTokenId:e.opposite_token_id,endDate:e.end_date,lastEventAt:e.last_event_at,name:e.name,profileImage:e.profile_image,verified:e.verified})),Wte=U.z.object({proxy_wallet:J,value:H}).transform(({proxy_wallet:e,value:t})=>({wallet:e,value:t})),jl=(e=>(e.Max="max",e.OneMonth="1m",e.OneWeek="1w",e.OneDay="1d",e.TwelveHours="12h",e.SixHours="6h",e))(jl||{}),YC=U.z.enum(jl),zl=(e=>(e.OneDay="1d",e.EighteenHours="18h",e.TwelveHours="12h",e.ThreeHours="3h",e.OneHour="1h",e))(zl||{}),d0=U.z.enum(zl),pn=H.nullish().transform(e=>e??null),L$=U.z.object({timestamp:wo,source_block:U.z.number().int().nonnegative(),realized_market_pnl:H,realized_lp_pnl:H,realized_combo_pnl:H,unrealized_pnl:pn,fees_refunded:pn,maker_rebate:pn,taker_rebate:pn,reward_income:pn,yield_income:pn,referral_income:pn,deposits:pn,withdrawals:pn,realized_pnl:H,wallet_income:pn,position_pnl:pn,settled_pnl:pn,economic_pnl:pn,trade_pnl:pn,sponsored_income:pn,fees:pn,fees_paid:pn,cashflow_net:pn,volume:H,volume_usdc:H,trade_count:U.z.number().int().nonnegative()}).transform(({source_block:e,realized_market_pnl:t,realized_lp_pnl:n,realized_combo_pnl:r,unrealized_pnl:o,fees_refunded:s,maker_rebate:i,taker_rebate:a,reward_income:l,yield_income:c,referral_income:u,realized_pnl:d,wallet_income:p,position_pnl:m,settled_pnl:g,economic_pnl:f,trade_pnl:y,sponsored_income:w,fees_paid:v,cashflow_net:x,volume_usdc:k,trade_count:S,...D})=>({...D,sourceBlock:e,realizedMarketPnl:t,realizedLpPnl:n,realizedComboPnl:r,unrealizedPnl:o,feesRefunded:s,makerRebate:i,takerRebate:a,rewardIncome:l,yieldIncome:c,referralIncome:u,realizedPnl:d,walletIncome:p,positionPnl:m,settledPnl:g,economicPnl:f,tradePnl:y,sponsoredIncome:w,feesPaid:v,cashflowNet:x,volumeUsdc:k,tradeCount:S})),Gte=U.z.object({proxy_wallet:J,interval:YC,fidelity:d0,source_fidelity:d0,points:U.z.array(L$)}).transform(({proxy_wallet:e,source_fidelity:t,...n})=>({...n,wallet:e,sourceFidelity:t})),Kte=U.z.object({volume:H,volume_usdc:H,trade_count:U.z.number().int().nonnegative()}).transform(({volume_usdc:e,trade_count:t,...n})=>({...n,volumeUsdc:e,tradeCount:t})),Yte=U.z.object({proxy_wallet:J,trades:U.z.number().int().nonnegative(),biggest_win:H,views:U.z.number().int().nonnegative(),join_date:wo.nullish(),all_time_pnl:L$.nullish()}).transform(({proxy_wallet:e,trades:t,biggest_win:n,join_date:r,all_time_pnl:o,...s})=>({...s,wallet:e,tradedMarketCount:t,biggestWin:n,joinDate:r??null,allTimePnl:o??null})),Qte=U.z.object({event_id:U.z.string().nullish(),event_slug:U.z.string().nullish(),event_title:U.z.string().nullish(),event_image:U.z.string().nullish()}).transform(({event_id:e,event_slug:t,event_title:n,event_image:r})=>({eventId:e,eventSlug:t,eventTitle:n,eventImage:r})),Xte=U.z.object({market_id:U.z.string().nullish(),slug:U.z.string().nullish(),title:U.z.string().nullish(),question:U.z.string().nullish(),group_item_title:U.z.string().nullish(),sports_market_type:U.z.string().nullish(),line:U.z.number().nullish(),outcomes:U.z.array(U.z.string()).nullish(),outcome:U.z.string().nullish(),image_url:U.z.string().nullish(),icon_url:U.z.string().nullish(),category:U.z.string().nullish(),subcategory:U.z.string().nullish(),tags:U.z.array(U.z.string()).nullish(),end_date:oe.nullish(),event:Qte.nullish()}).transform(({market_id:e,image_url:t,icon_url:n,end_date:r,group_item_title:o,sports_market_type:s,...i})=>({...i,marketId:e,groupItemTitle:o,sportsMarketType:s,imageUrl:t,iconUrl:n,endDate:r})),D$=U.z.object({leg_index:U.z.number().int(),leg_position_id:Xe,leg_condition_id:xe,leg_outcome_index:U.z.number().int(),leg_outcome_label:U.z.string().nullish(),leg_status:Nd,leg_resolved_at:oe.nullish(),leg_current_price:H.nullish(),market:Xte.nullish()}).transform(({leg_index:e,leg_position_id:t,leg_condition_id:n,leg_outcome_index:r,leg_outcome_label:o,leg_status:s,leg_resolved_at:i,leg_current_price:a,...l})=>({...l,legIndex:e,legPositionId:t,legConditionId:n,legOutcomeIndex:r,legOutcomeLabel:o,legStatus:s,legResolvedAt:i,legCurrentPrice:a})),Jte=U.z.object({combo_condition_id:Zt,outcome_index:U.z.number().int(),outcome_label:U.z.string(),combo_position_id:Xe,proxy_wallet:J,current_size:H,entry_avg_price_usdc:H,entry_cost_usdc:H,gross_entry_cost_usdc:H,entry_fees_usdc:H,realized_payout_usdc:H,status:Nd,redeemable:U.z.boolean(),first_entry_at:oe,resolved_at:oe.nullish(),legs_total:U.z.number().int(),legs_resolved:U.z.number().int(),legs_pending:U.z.number().int(),legs:U.z.array(D$),updated_at:oe}).transform(({combo_condition_id:e,outcome_index:t,outcome_label:n,combo_position_id:r,proxy_wallet:o,current_size:s,entry_avg_price_usdc:i,entry_cost_usdc:a,gross_entry_cost_usdc:l,entry_fees_usdc:c,realized_payout_usdc:u,first_entry_at:d,resolved_at:p,legs_total:m,legs_resolved:g,legs_pending:f,updated_at:y,...w})=>({...w,conditionId:e,outcomeIndex:t,outcomeLabel:n,positionId:r,wallet:o,currentSize:s,entryAvgPriceUsdc:i,entryCostUsdc:a,grossEntryCostUsdc:l,entryFeesUsdc:c,realizedPayoutUsdc:u,firstEntryAt:d,resolvedAt:p,legsTotal:m,legsResolved:g,legsPending:f,updatedAt:y})),U$=ls(zte),B$=si(Wte),M$=si(Yte.nullable()),F$=si(Gte),q$=si(Kte),H$=ls(Jte),Wl=(e=>(e.Split="SPLIT",e.Merge="MERGE",e.Convert="CONVERT",e.Compress="COMPRESS",e.Wrap="WRAP",e.Unwrap="UNWRAP",e.Redeem="REDEEM",e))(Wl||{}),Zte=U.z.enum(Wl),ene=U.z.object({id:n_,type:Zte,proxy_wallet:J,combo_condition_id:Zt,combo_position_id:Xe,amount_usdc:H.nullish(),payout_usdc:H.nullish(),timestamp:wo,transaction_hash:et,block_number:U.z.number().int(),legs:U.z.array(D$)}),tne=ene.transform(sne),Kt=U.z.preprocess(e=>e===""?void 0:e,U.z.string().optional()),$$=U.z.preprocess(e=>e===999?void 0:e,U.z.number().int().optional()),nne=U.z.object({proxy_wallet:J,side:Nt,token_id:Me,condition_id:xe,size:H,price:H,timestamp:wo,title:Kt,slug:Kt,icon:Kt,event_slug:Kt,outcome:Kt,outcome_index:$$,name:Kt,pseudonym:Kt,bio:Kt,profile_image:Kt,profile_image_optimized:Kt,transaction_hash:et}).transform(e=>({wallet:e.proxy_wallet,side:e.side,assetId:e.token_id,tokenId:e.token_id,conditionId:e.condition_id,size:e.size,price:e.price,timestamp:e.timestamp,title:e.title,slug:e.slug,icon:e.icon,eventSlug:e.event_slug,outcome:e.outcome,outcomeIndex:e.outcome_index,name:e.name,pseudonym:e.pseudonym,bio:e.bio,profileImage:e.profile_image,profileImageOptimized:e.profile_image_optimized,transactionHash:e.transaction_hash})),rne=U.z.object({proxy_wallet:J,timestamp:wo,condition_id:U.z.preprocess(e=>e===""?void 0:e,xe.optional()),type:KC,size:H,usdc_size:H,transaction_hash:et,price:H,token_id:U.z.preprocess(e=>e===""?void 0:e,Me.optional()),side:U.z.preprocess(e=>e===""?void 0:e,U.z.union([Nt,R$]).optional()),is_combo:U.z.boolean().optional(),outcome_index:$$,title:Kt,slug:Kt,icon:Kt,event_slug:Kt,outcome:Kt,name:Kt,pseudonym:Kt,bio:Kt,profile_image:Kt,profile_image_optimized:Kt}),one=rne.transform(ane),V$=ls(nne),j$=ls(one),z$=ls(tne);Po=(e=>(e.Max="max",e.OneMonth="1m",e.OneWeek="1w",e.OneDay="1d",e.SixHours="6h",e.OneHour="1h",e))(Po||{}),W$=U.z.enum(Po),une=U.z.object({timestamp:wo,price:H,resolution_seconds:U.z.number().int().nonnegative()}).transform(({price:e,resolution_seconds:t,timestamp:n})=>({timestamp:n,price:e,resolutionSeconds:t})),G$=ls(une),hf=U.z.preprocess(e=>e===""?null:e,U.z.string().nullable()),dne=U.z.object({proxy_wallet:J,bio:hf,token_id:Me,pseudonym:hf,amount:H,display_username_public:U.z.boolean(),outcome_index:U.z.preprocess(e=>e===999?null:e,U.z.number().int().nullable()),name:hf,profile_image:hf,profile_image_optimized:hf,verified:U.z.boolean(),avg_price:H.nullish(),entry_cost_usdc:H.nullish(),current_price:H.nullish(),current_value:H.nullish(),realized_pnl:H.nullish(),unrealized_pnl:H.nullish(),total_pnl:H.nullish()}).transform(e=>({wallet:e.proxy_wallet,assetId:e.token_id,tokenId:e.token_id,amount:e.amount,displayUsernamePublic:e.display_username_public,outcomeIndex:e.outcome_index,verified:e.verified,bio:e.bio,pseudonym:e.pseudonym,name:e.name,profileImage:e.profile_image,profileImageOptimized:e.profile_image_optimized,avgPrice:e.avg_price,entryCostUsdc:e.entry_cost_usdc,currentPrice:e.current_price,currentValue:e.current_value,realizedPnl:e.realized_pnl,unrealizedPnl:e.unrealized_pnl,totalPnl:e.total_pnl})),pne=U.z.object({token_id:Me,holders:U.z.array(dne)}).transform(({holders:e,token_id:t})=>({assetId:t,token:t,holders:e})),mne=U.z.object({condition_id:U.z.union([xe,U.z.literal("GLOBAL")]),value:H}).transform(({condition_id:e,value:t})=>({conditionId:e==="GLOBAL"?null:e,value:t})),hne=U.z.object({condition_id:U.z.preprocess(Gn,xe.nullable()),taker_volume:H}).transform(({condition_id:e,taker_volume:t})=>({conditionId:e,takerVolume:t})),fne=U.z.object({taker_volume_total:H,conditions:U.z.array(hne)}).transform(({conditions:e,taker_volume_total:t})=>({markets:e,takerVolumeTotal:t})),K$=ls(pne),Y$=si(U.z.array(mne)),Q$=si(fne),Gl=(e=>(e.Day="day",e.Week="week",e.Month="month",e.All="all",e))(Gl||{}),ff=U.z.enum(Gl),Kl=(e=>(e.Day="day",e.Week="week",e.Month="month",e.Year="all",e))(Kl||{}),X$=U.z.enum(Kl),Yl=(e=>(e.Pnl="PNL",e.Volume="VOLUME",e))(Yl||{}),J$=U.z.enum(Yl),Ql=(e=>(e.Market="market",e.Combo="combo",e))(Ql||{}),YCe=U.z.enum(Ql),gne=U.z.object({rank:U.z.number().int().positive(),builder_name:U.z.string(),builder_code:bo,profile_image:U.z.string(),verified:U.z.boolean(),volume:H,active_users:U.z.number().int().min(0)}).transform(({active_users:e,builder_code:t,builder_name:n,profile_image:r,...o})=>({...o,activeUsers:e,builderCode:t,builderName:n,...r===""?{}:{profileImage:r}})),yne=U.z.object({date:Wn,rank:U.z.number().int().min(0),builder_name:U.z.string(),builder_code:bo,profile_image:U.z.string(),verified:U.z.boolean(),volume:H,active_users:U.z.number().int().min(0)}).transform(({active_users:e,builder_code:t,builder_name:n,date:r,profile_image:o,...s})=>({...s,activeUsers:e,bucketDate:r,builderCode:t,builderName:n,...o===""?{}:{profileImage:o}})),as=U.z.preprocess(Gn,U.z.string().nullable()),bne=U.z.object({rank:U.z.number().int().min(0),user_id:J,pnl:H,volume:H,user_name:as,profile_image:as,x_username:as,verified:U.z.boolean()}).transform(({profile_image:e,user_id:t,user_name:n,x_username:r,...o})=>({...o,wallet:t,userName:n,profileImage:e,xUsername:r})),wne=U.z.object({user_id:J,pnl:H,volume:H,rank_pnl:U.z.number().int().positive().nullable(),rank_volume:U.z.number().int().positive().nullable(),user_name:as,profile_image:as,x_username:as,verified:U.z.boolean()}).transform(({profile_image:e,rank_pnl:t,rank_volume:n,user_id:r,user_name:o,x_username:s,...i})=>({...i,wallet:r,pnlRank:t,volumeRank:n,userName:o,profileImage:e,xUsername:s})),vne=U.z.object({win_rank:U.z.number().int().positive(),kind:U.z.literal("market"),user_id:J,pnl:H,initial_value:H,final_value:H,resolved_at:wo,condition_id:xe,position_id:Me,event_id:Gt,event_slug:U.z.string(),event_title:U.z.string(),user_name:as,profile_image:as}),kne=U.z.object({win_rank:U.z.number().int().positive(),kind:U.z.literal("combo"),user_id:J,pnl:H,initial_value:H,final_value:H,resolved_at:wo,condition_id:Zt,position_id:Xe,event_id:U.z.literal(0),event_slug:U.z.literal(""),event_title:U.z.string(),user_name:as,profile_image:as}),xne=U.z.discriminatedUnion("kind",[vne,kne]).transform(e=>e.kind==="combo"?{rank:e.win_rank,kind:e.kind,wallet:e.user_id,pnl:e.pnl,initialValue:e.initial_value,finalValue:e.final_value,resolvedAt:e.resolved_at,conditionId:e.condition_id,positionId:e.position_id,eventId:null,eventSlug:null,eventTitle:e.event_title,userName:e.user_name,profileImage:e.profile_image}:{rank:e.win_rank,kind:e.kind,wallet:e.user_id,pnl:e.pnl,initialValue:e.initial_value,finalValue:e.final_value,resolvedAt:e.resolved_at,conditionId:e.condition_id,assetId:e.position_id,eventId:e.event_id,eventSlug:e.event_slug,eventTitle:e.event_title,userName:e.user_name,profileImage:e.profile_image}),Z$=ls(gne),e4=si(U.z.array(yne)),t4=ls(bne),n4=si(wne.nullable()),r4=ls(xne),Xl=(e=>(e.Initialized="initialized",e.Posed="posed",e.Proposed="proposed",e.Challenged="challenged",e.Reproposed="reproposed",e.Disputed="disputed",e.Active="active",e.Arbitration="arbitration",e.Resolved="resolved",e))(Xl||{}),Ane=U.z.enum(Xl),Jl=(e=>(e.Binary="BINARY",e.IncrementalNegRisk="INCREMENTAL_NEGRISK",e.AtomicNegRisk="ATOMIC_NEGRISK",e))(Jl||{}),Tne=U.z.enum(Jl),Zl=(e=>(e.Reported="reported",e.Derived="derived",e))(Zl||{}),Sne=U.z.enum(Zl),ec=(e=>(e.UmaOptimisticOracle="UMA_OO",e.Chainlink="CHAINLINK",e.Eoa="EOA",e))(ec||{}),Pne=U.z.enum(ec),E$=U.z.number().int().min(0).transform(String).pipe(yn),Ene=U.z.object({question_id:vo.optional(),condition_id:xe.optional(),status:Ane,extended_review:U.z.boolean(),was_disputed:U.z.boolean(),new_version_q:U.z.boolean(),proposed_price:R.optional(),reproposed_price:R.optional(),price:R.optional(),transaction_hash:U.z.preprocess(Gn,et.nullable()),log_index:U.z.preprocess(Gn,U.z.string().regex(/^\d+$/).transform(Number).nullable()),last_update_timestamp:Xi,market_type:Tne.optional(),payouts:U.z.tuple([E$,E$]).optional(),resolution_source:Sne.optional(),reporter:Pne.optional(),was_arbitrated:U.z.boolean().optional(),resolved_block:U.z.number().int().min(0).optional(),resolved_at:oe.optional()}).transform(e=>{let t={status:e.status,extendedReview:e.extended_review,wasDisputed:e.was_disputed,questionRulesUpdated:e.new_version_q,transactionHash:e.transaction_hash,logIndex:e.log_index,lastUpdatedAt:e.last_update_timestamp};return e.question_id!==void 0&&(t.questionId=e.question_id),e.condition_id!==void 0&&(t.conditionId=e.condition_id),e.proposed_price!==void 0&&e.proposed_price!=="69"&&(t.proposedPrice=e.proposed_price),e.reproposed_price!==void 0&&e.reproposed_price!=="69"&&(t.reproposedPrice=e.reproposed_price),e.price!==void 0&&e.price!=="69"&&(t.price=e.price),e.market_type!==void 0&&(t.marketType=e.market_type),e.payouts!==void 0&&(t.payouts=e.payouts),e.resolution_source!==void 0&&(t.resolutionSource=e.resolution_source),e.reporter!==void 0&&(t.reporter=e.reporter),e.was_arbitrated!==void 0&&(t.wasArbitrated=e.was_arbitrated),e.resolved_block!==void 0&&(t.resolvedBlock=e.resolved_block),e.resolved_at!==void 0&&(t.resolvedAt=e.resolved_at),t}),o4=si(U.z.array(Ene))});var Pe,Od,s4,f0,i4,_r,JCe,Rne,Ld,a4,Ine,l4,_ne,Cne,Nne,One,Lne,c4,QC,u4,d4,p4=L(()=>{"use strict";xo();Pe=require("zod"),Od=(e=>(e.SUBMITTED="SUBMITTED",e.REGISTRY_PENDING="REGISTRY_PENDING",e.REGISTERED="REGISTERED",e.FAILED="FAILED",e.SUPERSEDED="SUPERSEDED",e.REPAIR_REQUIRED="REPAIR_REQUIRED",e))(Od||{}),s4=Pe.z.object({status:Pe.z.enum(Od),transactionHash:et.nullish().transform(e=>e??null),transactionId:ea}),f0=(e=>(e.PENDING="PENDING",e.FENCED="FENCED",e.SWEPT="SWEPT",e.CHAIN_SUBMITTED="CHAIN_SUBMITTED",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED",e))(f0||{}),i4=Pe.z.object({status:Pe.z.enum(f0),transactionId:ea}),_r=(e=>(e.SAFE="SAFE",e.PROXY="PROXY",e.SAFE_CREATE="SAFE-CREATE",e.WALLET="WALLET",e.WALLET_CREATE="WALLET-CREATE",e))(_r||{}),JCe=Pe.z.enum(_r),Rne=Pe.z.enum(["PROXY","SAFE","SAFE-CREATE"]),Ld=(e=>(e.STATE_NEW="STATE_NEW",e.STATE_EXECUTED="STATE_EXECUTED",e.STATE_MINED="STATE_MINED",e.STATE_CONFIRMED="STATE_CONFIRMED",e.STATE_INVALID="STATE_INVALID",e.STATE_FAILED="STATE_FAILED",e))(Ld||{}),a4=Pe.z.enum(Ld),Ine=Pe.z.object({baseGas:Pe.z.string().optional(),gasLimit:Pe.z.string().optional(),gasPrice:Pe.z.string().optional(),gasToken:J.optional(),operation:Pe.z.string().optional(),payment:Pe.z.string().optional(),paymentReceiver:J.optional(),paymentToken:J.optional(),refundReceiver:J.optional(),relay:J.optional(),relayHub:J.optional(),relayerFee:Pe.z.string().optional(),safeTxnGas:Pe.z.string().optional()}),l4=Pe.z.object({address:J,nonce:Pe.z.string().min(1)}),_ne=Pe.z.object({data:Pe.z.string().min(1),from:J,metadata:Pe.z.string().optional(),nonce:Pe.z.string().min(1).optional(),proxyWallet:J,signature:Pe.z.string().min(1),signatureParams:Ine,to:J,type:Rne,value:Pe.z.string().optional()}),Cne=Pe.z.object({data:Pe.z.string().min(1),target:J,value:Pe.z.string().min(1)}),Nne=Pe.z.object({calls:Pe.z.array(Cne).min(1),deadline:Pe.z.string().min(1),depositWallet:J}),One=Pe.z.object({depositWalletParams:Nne,from:J,metadata:Pe.z.string().optional(),nonce:Pe.z.string().min(1),signature:Pe.z.string().min(1),to:J,type:Pe.z.literal("WALLET")}),Lne=Pe.z.object({from:J,metadata:Pe.z.string().optional(),to:J,type:Pe.z.literal("WALLET-CREATE")}),c4=Pe.z.union([_ne,One,Lne]),QC=Pe.z.object({state:a4,transactionHash:et.nullish().transform(e=>e??null),transactionID:ea}).transform(({transactionHash:e,transactionID:t,...n})=>({...n,transactionHash:e??null,transactionId:t})),u4=Pe.z.object({deployed:Pe.z.boolean()}),d4=Pe.z.object({error_msg:Pe.z.string().nullish(),state:a4,transaction_hash:Pe.z.union([Pe.z.literal(""),et]).transform(e=>e===""?null:e),transaction_id:ea}).transform(({error_msg:e,transaction_hash:t,transaction_id:n,...r})=>({...r,errorMsg:e??null,transactionHash:t??null,transactionId:n}))});var te,Nn,Eo,cs,us,Qr,Cr,JC,ZC,Dne,Une,Bne,Mne,m4,Fne,qne,Hne,$ne,Vne,jne,zne,Wne,Gne,Kne,Yne,h4,mn,li,ci,Ro,f4,Qne,Xne,Jne,Zne,ere,g4,eN,tN,Dd,tre,nre,XC,rre,y4,b4,w4,g0=L(()=>{"use strict";RC();xo();te=require("zod");Tl();Nn=(e=>(e.Buy="BUY",e.Sell="SELL",e))(Nn||{}),Eo=(e=>(e.Yes="YES",e.No="NO",e))(Eo||{}),cs=(e=>(e.Confirm="CONFIRM",e.Decline="DECLINE",e))(cs||{}),us=(e=>(e.Matched="MATCHED",e.Mined="MINED",e.Confirmed="CONFIRMED",e.Retrying="RETRYING",e.Failed="FAILED",e))(us||{}),Qr=(e=>(e.Notional="notional",e.Shares="shares",e))(Qr||{}),Cr=(e=>(e.AddressMismatch="ADDRESS_MISMATCH",e.AllowanceValidationFailed="ALLOWANCE_VALIDATION_FAILED",e.BalanceValidationFailed="BALANCE_VALIDATION_FAILED",e.ContradictoryLegs="CONTRADICTORY_LEGS",e.ExpiredRfq="EXPIRED_RFQ",e.InvalidAcceptance="INVALID_ACCEPTANCE",e.InvalidConfirmation="INVALID_CONFIRMATION",e.InvalidExecutionResult="INVALID_EXECUTION_RESULT",e.InvalidIdentity="INVALID_IDENTITY",e.InvalidMessage="INVALID_MESSAGE",e.InvalidOrderSide="INVALID_ORDER_SIDE",e.InvalidQuote="INVALID_QUOTE",e.InvalidRfq="INVALID_RFQ",e.InvalidRfqState="INVALID_RFQ_STATE",e.InvalidRole="INVALID_ROLE",e.InvalidSignature="INVALID_SIGNATURE",e.InvalidSignatureType="INVALID_SIGNATURE_TYPE",e.InternalError="INTERNAL_ERROR",e.LegMetadataUnavailable="LEG_METADATA_UNAVAILABLE",e.MakerAlreadyResponded="MAKER_ALREADY_RESPONDED",e.MakerDeclined="MAKER_DECLINED",e.MakerNotRequired="MAKER_NOT_REQUIRED",e.MakerQuoteLimited="MAKER_QUOTE_LIMITED",e.MissingMakerAddressInQuote="MISSING_MAKER_ADDRESS_IN_QUOTE",e.MissingMakerAmountInSignedOrder="MISSING_MAKER_AMOUNT_IN_SIGNED_ORDER",e.MissingMakerInSignedOrder="MISSING_MAKER_IN_SIGNED_ORDER",e.MissingQuoteId="MISSING_QUOTE_ID",e.MissingRfqId="MISSING_RFQ_ID",e.MissingSaltInSignedOrder="MISSING_SALT_IN_SIGNED_ORDER",e.MissingSignatureInSignedOrder="MISSING_SIGNATURE_IN_SIGNED_ORDER",e.MissingSignerAddressInQuote="MISSING_SIGNER_ADDRESS_IN_QUOTE",e.MissingSignerInSignedOrder="MISSING_SIGNER_IN_SIGNED_ORDER",e.MissingTakerAmountInSignedOrder="MISSING_TAKER_AMOUNT_IN_SIGNED_ORDER",e.MissingTimestampInSignedOrder="MISSING_TIMESTAMP_IN_SIGNED_ORDER",e.MissingTokenIdInSignedOrder="MISSING_TOKEN_ID_IN_SIGNED_ORDER",e.NoQuotes="NO_QUOTES",e.OrderSideOrTokenDoesNotMatchRequest="ORDER_SIDE_OR_TOKEN_DOES_NOT_MATCH_REQUEST",e.PreExecutionBalanceReservationFailed="PRE_EXECUTION_BALANCE_RESERVATION_FAILED",e.PriceE6NotPositive="PRICE_E6_NOT_POSITIVE",e.QuoteMismatch="QUOTE_MISMATCH",e.QuoteUnavailable="QUOTE_UNAVAILABLE",e.QuotedPriceAboveSafetyThreshold="QUOTED_PRICE_ABOVE_SAFETY_THRESHOLD",e.QuotedPriceOutOfRange="QUOTED_PRICE_OUT_OF_RANGE",e.RateLimited="RATE_LIMITED",e.RequestFailed="REQUEST_FAILED",e.ServiceUnavailable="SERVICE_UNAVAILABLE",e.SignedOrderMakerAmountNotPositive="SIGNED_ORDER_MAKER_AMOUNT_NOT_POSITIVE",e.SignedOrderMakerDoesNotMatchAuth="SIGNED_ORDER_MAKER_DOES_NOT_MATCH_AUTH",e.SignedOrderPriceWorseThanQuote="SIGNED_ORDER_PRICE_WORSE_THAN_QUOTE",e.SignedOrderSignatureTypeDoesNotMatchAuth="SIGNED_ORDER_SIGNATURE_TYPE_DOES_NOT_MATCH_AUTH",e.SignedOrderSignerDoesNotMatchAuth="SIGNED_ORDER_SIGNER_DOES_NOT_MATCH_AUTH",e.SignedOrderSizeDoesNotCoverQuote="SIGNED_ORDER_SIZE_DOES_NOT_COVER_QUOTE",e.SignedOrderTakerAmountNotPositive="SIGNED_ORDER_TAKER_AMOUNT_NOT_POSITIVE",e.SizeE6NotPositive="SIZE_E6_NOT_POSITIVE",e.SizeTooLarge="SIZE_TOO_LARGE",e.SubmissionWindowClosed="SUBMISSION_WINDOW_CLOSED",e.TradeSubmissionFailed="TRADE_SUBMISSION_FAILED",e.Unauthenticated="UNAUTHENTICATED",e.UnauthorizedRole="UNAUTHORIZED_ROLE",e.UnknownRfq="UNKNOWN_RFQ",e))(Cr||{}),JC=te.z.enum(Nn),ZC=te.z.literal("YES"),Dne=te.z.enum(cs),Une=te.z.enum(us),Bne=te.z.string().transform(e=>e),Mne=te.z.object({id:Ji,condition_id:xe,position_ids:te.z.array(Xe),pending:te.z.boolean(),slug:te.z.string(),title:te.z.string(),outcomes:te.z.array(te.z.string()),outcome_prices:te.z.array(R),image:te.z.string(),volume:te.z.number(),tags:te.z.array(te.z.string())}).superRefine((e,t)=>{e.outcomes.length!==2&&t.addIssue({code:"custom",message:`Expected binary combo market outcomes, received ${e.outcomes.length}.`,path:["outcomes"]}),e.position_ids.length!==e.outcomes.length&&t.addIssue({code:"custom",message:"Expected position_ids and outcomes to have matching lengths.",path:["position_ids"]}),e.outcome_prices.length!==e.outcomes.length&&t.addIssue({code:"custom",message:"Expected outcome_prices and outcomes to have matching lengths.",path:["outcome_prices"]})}).transform(e=>({conditionId:e.condition_id,id:e.id,image:e.image,pending:e.pending,outcomes:{yes:{label:e.outcomes[0],positionId:e.position_ids[0],price:e.outcome_prices[0]},no:{label:e.outcomes[1],positionId:e.position_ids[1],price:e.outcome_prices[1]}},slug:e.slug,tags:e.tags,title:e.title,volume:e.volume})),m4=te.z.object({markets:te.z.array(Mne),next_cursor:ye.nullish()}).transform(e=>({markets:e.markets,nextCursor:e.next_cursor??void 0})),Fne=te.z.discriminatedUnion("unit",[te.z.object({unit:te.z.literal("notional"),value_e6:yn}),te.z.object({unit:te.z.literal("shares"),value_e6:yn})]).transform(e=>({unit:e.unit,value:e.value_e6})),qne=(e=>(e.Auth="auth",e.QuoteRequest="RFQ_REQUEST",e.QuoteAck="ACK_RFQ_QUOTE",e.QuoteCancelAck="ACK_RFQ_QUOTE_CANCEL",e.ConfirmationRequest="RFQ_CONFIRMATION_REQUEST",e.ConfirmationAck="ACK_RFQ_CONFIRMATION_RESPONSE",e.ExecutionUpdate="RFQ_EXECUTION_UPDATE",e.Trade="RFQ_TRADE",e.Error="RFQ_ERROR",e))(qne||{}),Hne=te.z.object({type:te.z.literal("auth"),success:te.z.boolean(),address:J.optional(),role:te.z.string().optional(),error:te.z.string().optional()}),$ne=te.z.object({type:te.z.literal("RFQ_REQUEST"),rfq_id:ar,requestor_public_id:Ew,leg_position_ids:te.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:JC,side:ZC,requested_size:Fne,submission_deadline:pe}).transform(e=>({conditionId:e.condition_id,direction:e.direction,legPositionIds:e.leg_position_ids,noPositionId:e.no_position_id,requestorPublicId:e.requestor_public_id,requestedSize:e.requested_size,rfqId:e.rfq_id,side:e.side,submissionDeadline:e.submission_deadline,type:"quote_request",yesPositionId:e.yes_position_id})),Vne=te.z.object({type:te.z.literal("ACK_RFQ_QUOTE"),rfq_id:ar,quote_id:Zi}).transform(e=>({quoteId:e.quote_id,rfqId:e.rfq_id,type:"quote_ack"})),jne=te.z.object({type:te.z.literal("ACK_RFQ_QUOTE_CANCEL"),rfq_id:ar,quote_id:Zi}).transform(e=>({quoteId:e.quote_id,rfqId:e.rfq_id,type:"quote_cancel_ack"})),zne=te.z.object({type:te.z.literal("RFQ_CONFIRMATION_REQUEST"),rfq_id:ar,quote_id:Zi,signer_address:J,maker_address:J,signature_type:EC,leg_position_ids:te.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:JC,side:ZC,fill_size_e6:yn,price_e6:yn,confirm_by:pe}).transform(e=>({conditionId:e.condition_id,confirmBy:e.confirm_by,direction:e.direction,fillSize:e.fill_size_e6,legPositionIds:e.leg_position_ids,makerAddress:e.maker_address,noPositionId:e.no_position_id,price:e.price_e6,quoteId:e.quote_id,rfqId:e.rfq_id,side:e.side,signatureType:e.signature_type,signerAddress:e.signer_address,type:"confirmation_request",yesPositionId:e.yes_position_id})),Wne=te.z.object({type:te.z.literal("ACK_RFQ_CONFIRMATION_RESPONSE"),rfq_id:ar,quote_id:Zi,decision:Dne}).transform(e=>({decision:e.decision,quoteId:e.quote_id,rfqId:e.rfq_id,type:"confirmation_ack"})),Gne=te.z.object({type:te.z.literal("RFQ_EXECUTION_UPDATE"),rfq_id:ar,status:Une,tx_hash:et.optional()}).transform(e=>({rfqId:e.rfq_id,status:e.status,...e.tx_hash===void 0?{}:{txHash:e.tx_hash},type:"execution_update"})),Kne=te.z.object({type:te.z.literal("RFQ_TRADE"),rfq_id:ar,requester_id:Ew,condition_id:Zt,leg_position_ids:te.z.array(Xe),direction:JC,side:ZC,price_e6:yn,size_e6:yn,executed_at:pe}).transform(e=>({conditionId:e.condition_id,direction:e.direction,executedAt:e.executed_at,legPositionIds:e.leg_position_ids,price:e.price_e6,requesterId:e.requester_id,rfqId:e.rfq_id,side:e.side,size:e.size_e6,type:"trade"})),Yne=te.z.object({type:te.z.literal("RFQ_ERROR"),error_id:te.z.string().optional(),request_type:te.z.string().optional(),rfq_id:ar.optional(),quote_id:Zi.optional(),code:Bne,error:te.z.string(),request:te.z.unknown().optional()}).transform(e=>({code:e.code,errorId:e.error_id,message:e.error,quoteId:e.quote_id,requestType:e.request_type,rfqId:e.rfq_id,type:"rfq_error"})),h4=te.z.discriminatedUnion("type",[Hne,$ne,Vne,jne,zne,Wne,Gne,Kne,Yne]),mn=(e=>(e.AwaitingRequesterAcceptance="AWAITING_REQUESTER_ACCEPTANCE",e.AwaitingMakerConfirmation="AWAITING_MAKER_CONFIRMATION",e.Executing="EXECUTING",e.Filled="FILLED",e.Failed="FAILED",e.Expired="EXPIRED",e.Canceled="CANCELED",e))(mn||{}),li=(e=>(e.InvalidJson="INVALID_JSON",e.InvalidMessage="INVALID_MESSAGE",e.InvalidRole="INVALID_ROLE",e.UnauthorizedRole="UNAUTHORIZED_ROLE",e.Unauthenticated="UNAUTHENTICATED",e.AddressMismatch="ADDRESS_MISMATCH",e.InvalidRfq="INVALID_RFQ",e.ContradictoryLegs="CONTRADICTORY_LEGS",e.LegMetadataUnavailable="LEG_METADATA_UNAVAILABLE",e.InvalidAcceptance="INVALID_ACCEPTANCE",e.InvalidQuote="INVALID_QUOTE",e.InvalidSignature="INVALID_SIGNATURE",e.InvalidIdentity="INVALID_IDENTITY",e.UnknownRfq="UNKNOWN_RFQ",e.ExpiredRfq="EXPIRED_RFQ",e.InvalidRfqState="INVALID_RFQ_STATE",e.QuoteMismatch="QUOTE_MISMATCH",e.SubmissionWindowClosed="SUBMISSION_WINDOW_CLOSED",e.ServiceUnavailable="SERVICE_UNAVAILABLE",e.PreExecutionBalanceReservationFailed="PRE_EXECUTION_BALANCE_RESERVATION_FAILED",e.BalanceValidationFailed="BALANCE_VALIDATION_FAILED",e.AllowanceValidationFailed="ALLOWANCE_VALIDATION_FAILED",e.TradeSubmissionFailed="TRADE_SUBMISSION_FAILED",e.RequestFailed="REQUEST_FAILED",e))(li||{}),ci=(e=>(e.NoQuotes="NO_QUOTES",e.SizeTooLarge="SIZE_TOO_LARGE",e))(ci||{}),Ro=(e=>(e.MakerDeclined="MAKER_DECLINED",e.AcceptanceWindowExpired="ACCEPTANCE_WINDOW_EXPIRED",e.ExecutionFailed="EXECUTION_FAILED",e))(Ro||{}),f4=te.z.object({code:te.z.string().transform(e=>e),message:te.z.string()}).transform(e=>({code:e.code,message:e.message})),Qne=te.z.object({quote_id:Zi,blended_price_e6:yn,maker_amount_e6:yn,taker_amount_e6:yn,total_required_e6:yn,net_receive_e6:yn.optional()}).transform(e=>({blendedPrice:e.blended_price_e6,makerAmount:e.maker_amount_e6,quoteId:e.quote_id,takerAmount:e.taker_amount_e6,totalRequired:e.total_required_e6,...e.net_receive_e6===void 0?{}:{netReceive:e.net_receive_e6}})),Xne=te.z.object({unit:te.z.enum(Qr),value_e6:te.z.string().regex(/^\d+$/).transform(e=>BigInt(e).toString())}).transform(e=>({unit:e.unit,valueE6:e.value_e6})),Jne=te.z.object({rfq_id:ar,leg_position_ids:te.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:te.z.enum(Nn),side:te.z.enum(Eo),requested_size:Xne}).transform(e=>({conditionId:e.condition_id,direction:e.direction,legPositionIds:e.leg_position_ids,noPositionId:e.no_position_id,requestedSize:e.requested_size,rfqId:e.rfq_id,side:e.side,yesPositionId:e.yes_position_id})),Zne=te.z.object({rfq_id:ar,status:te.z.literal("AWAITING_REQUESTER_ACCEPTANCE"),expires_at:pe,builder_code:bo,request:Jne,quote:Qne}).transform(e=>({builderCode:e.builder_code,expiresAt:e.expires_at,quote:e.quote,request:e.request,rfqId:e.rfq_id,status:e.status})),ere=te.z.object({rfq_id:ar,status:te.z.enum(["FAILED","EXPIRED","CANCELED"]),error:f4.optional()}).transform(e=>({rfqId:e.rfq_id,status:e.status,...e.error===void 0?{}:{error:e.error}})),g4=te.z.union([Zne,ere]),eN=te.z.object({rfq_id:ar,status:te.z.union([te.z.enum(mn),te.z.enum(us)]),taker_order_hash:te.z.string().optional(),tx_hash:et.optional(),error:f4.optional()}).transform(e=>({rfqId:e.rfq_id,status:e.status,...e.taker_order_hash===void 0?{}:{takerOrderHash:e.taker_order_hash},...e.tx_hash===void 0?{}:{txHash:e.tx_hash},...e.error===void 0?{}:{error:e.error}})),tN=te.z.string().transform(e=>zn(e)),Dd=(e=>(e.Split="split",e.Merge="merge",e.Redeem="redeem",e.SplitOnCondition="split_on_condition",e.MergeOnCondition="merge_on_condition",e.SplitOnEvent="split_on_event",e.MergeOnEvent="merge_on_event",e.ConvertOnEvent="convert_on_event",e.Extract="extract",e.Inject="inject",e.ConvertToYesBasket="convert_to_yes_basket",e.MergeFromYesBasket="merge_from_yes_basket",e.Compress="compress",e))(Dd||{}),tre=te.z.string().transform(e=>e),nre=te.z.object({kind:tre,condition_id:Zt.optional(),event_id:Gt.optional(),position_id:Xe.optional(),condition_index:te.z.number().int().nonnegative().optional().default(0),amount:yn}).transform(e=>({amount:e.amount,conditionId:e.condition_id,conditionIndex:e.condition_index,eventId:e.event_id,kind:e.kind,positionId:e.position_id})),XC=te.z.object({position_id:Xe,amount:yn}).transform(e=>({amount:e.amount,positionId:e.position_id})),rre=te.z.object({consumed:te.z.array(XC),created:te.z.array(XC)}).transform(e=>({consumed:e.consumed,created:e.created})),y4=te.z.object({to:J,data:tN}).transform(e=>({data:e.data,to:e.to})),b4=te.z.looseObject({planHash:tN,chainId:te.z.number().int(),wallet:J,routerCall:y4}),w4=te.z.object({plan_hash:tN,chain_id:te.z.number().int(),wallet:J,block_number:te.z.string().regex(/^\d+$/).transform(BigInt),starting_pusd:R,net_pusd_out:R,final_pusd:R,operations:te.z.array(nre),operation_count:te.z.number().int(),truncated:te.z.boolean(),estimated_cost:te.z.number(),required_pusd_input:R,required_positions:te.z.array(XC),position_summary:rre.optional(),candidate_position_ids:te.z.array(Xe),router_call:y4}).transform(e=>({blockNumber:e.block_number,candidatePositionIds:e.candidate_position_ids,chainId:e.chain_id,estimatedCost:e.estimated_cost,finalPusd:e.final_pusd,netPusdOut:e.net_pusd_out,operationCount:e.operation_count,operations:e.operations,planHash:e.plan_hash,positionSummary:e.position_summary??{consumed:[],created:[]},requiredPositions:e.required_positions,requiredPusdInput:e.required_pusd_input,routerCall:e.router_call,startingPusd:e.starting_pusd,truncated:e.truncated,wallet:e.wallet}))});var tc,v4,nN,ore,k4,rN=L(()=>{"use strict";AC();xo();tc=require("zod"),v4=tc.z.number().int().transform(e=>e===0?null:pd(e)),nN=tc.z.object({status:tc.z.literal("ok"),deadline:v4}),ore=tc.z.object({deadline:v4,triggered:tc.z.number().int().nonnegative(),daily_limit:tc.z.number().int().nonnegative(),next_reset:pe}).transform(e=>({deadline:e.deadline,triggered:e.triggered,dailyLimit:e.daily_limit,nextReset:e.next_reset})),k4=ore});function x4(e){let t=e.length,n=0,r=0;for(;r<t;){let o=e.charCodeAt(r++);if((o&4294967168)===0){n++;continue}else if((o&4294965248)===0)n+=2;else{if(o>=55296&&o<=56319&&r<t){let s=e.charCodeAt(r);(s&64512)===56320&&(++r,o=((o&1023)<<10)+(s&1023)+65536)}(o&4294901760)===0?n+=3:n+=4}}return n}function sre(e,t,n){let r=e.length,o=n,s=0;for(;s<r;){let i=e.charCodeAt(s++);if((i&4294967168)===0){t[o++]=i;continue}else if((i&4294965248)===0)t[o++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&s<r){let a=e.charCodeAt(s);(a&64512)===56320&&(++s,i=((i&1023)<<10)+(a&1023)+65536)}(i&4294901760)===0?(t[o++]=i>>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=i&63|128}}function lre(e,t,n){ire.encodeInto(e,t.subarray(n))}function A4(e,t,n){e.length>are?lre(e,t,n):sre(e,t,n)}var ire,are,uNe,T4=L(()=>{"use strict";ire=new TextEncoder,are=50;uNe=new TextDecoder});var nc,S4=L(()=>{"use strict";nc=class{type;data;constructor(t,n){this.type=t,this.data=n}}});var y0,P4=L(()=>{"use strict";y0=class e extends Error{constructor(t){super(t);let n=Object.create(e.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}});function E4(e,t,n){let r=n/4294967296,o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function b0(e,t,n){let r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function R4(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}var oN=L(()=>{"use strict"});function pre({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=dre)if(t===0&&e<=ure){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e),n}else{let n=e/4294967296,r=e&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,t<<2|n&3),s.setUint32(4,r),o}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),b0(r,4,e),n}}function mre(e){let t=e.getTime(),n=Math.floor(t/1e3),r=(t-n*1e3)*1e6,o=Math.floor(r/1e9);return{sec:n+o,nsec:r-o*1e9}}function hre(e){if(e instanceof Date){let t=mre(e);return pre(t)}else return null}function fre(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let n=t.getUint32(0),r=t.getUint32(4),o=(n&3)*4294967296+r,s=n>>>2;return{sec:o,nsec:s}}case 12:{let n=R4(t,4),r=t.getUint32(0);return{sec:n,nsec:r}}default:throw new y0(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function gre(e){let t=fre(e);return new Date(t.sec*1e3+t.nsec/1e6)}var cre,ure,dre,I4,_4=L(()=>{"use strict";P4();oN();cre=-1,ure=4294967296-1,dre=17179869184-1;I4={type:cre,encode:hre,decode:gre}});var w0,C4=L(()=>{"use strict";S4();_4();w0=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(I4)}register({type:t,encode:n,decode:r}){if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{let o=-1-t;this.builtInEncoders[o]=n,this.builtInDecoders[o]=r}}tryToEncode(t,n){for(let r=0;r<this.builtInEncoders.length;r++){let o=this.builtInEncoders[r];if(o!=null){let s=o(t,n);if(s!=null){let i=-1-r;return new nc(i,s)}}}for(let r=0;r<this.encoders.length;r++){let o=this.encoders[r];if(o!=null){let s=o(t,n);if(s!=null){let i=r;return new nc(i,s)}}}return t instanceof nc?t:null}decode(t,n,r){let o=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return o?o(t,n,r):new nc(n,t)}}});function yre(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function N4(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):yre(e)?new Uint8Array(e):Uint8Array.from(e)}var O4=L(()=>{"use strict"});var bre,wre,v0,L4=L(()=>{"use strict";T4();C4();oN();O4();bre=100,wre=2048,v0=class e{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??w0.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??bre,this.initialBufferSize=t?.initialBufferSize??wre,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,n)}ensureBufferSizeToWrite(t){let n=this.pos+t;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(t){let n=new ArrayBuffer(t),r=new Uint8Array(n),o=new DataView(n);r.set(this.bytes),this.view=o,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(t){t===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let r=x4(t);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),A4(t,this.bytes,this.pos),this.pos+=r}encodeObject(t,n){let r=this.extensionCodec.tryToEncode(t,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(t))this.encodeArray(t,n);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let n=t.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let r=N4(t);this.writeU8a(r)}encodeArray(t,n){let r=t.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let o of t)this.doEncode(o,n+1)}countWithoutUndefined(t,n){let r=0;for(let o of n)t[o]!==void 0&&r++;return r}encodeMap(t,n){let r=Object.keys(t);this.sortKeys&&r.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(t,r):r.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let s of r){let i=t[s];this.ignoreUndefined&&i===void 0||(this.encodeString(s),this.doEncode(i,n+1))}}encodeExtension(t){if(typeof t.data=="function"){let r=t.data(this.pos+6),o=r.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(t.type),this.writeU8a(r);return}let n=t.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let n=t.length;this.ensureBufferSizeToWrite(n),this.bytes.set(t,this.pos),this.pos+=n}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),E4(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),b0(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}});function sN(e,t){return new v0(t).encodeSharedRef(e)}var D4=L(()=>{"use strict";L4()});var U4=L(()=>{"use strict";D4()});function ui(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}var iN=L(()=>{"use strict"});var k0,Ud,B4=L(()=>{"use strict";k0=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Ud=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new k0(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let n=this.head;this.head=n.next=new k0(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let n=this.tail.next;this.tail.next=null,this.tail=n,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}});function Bd(e={}){return vre(n=>{let r=n.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},e)}function vre(e,t){t=t??{};let n=t.onEnd,r=new Ud,o,s,i,a=ui(),l=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((y,w)=>{s=v=>{s=null,r.push(v);try{y(e(r))}catch(x){w(x)}return o}}):e(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ui()})}},c=y=>s!=null?s(y):(r.push(y),o),u=y=>(r=new Ud,s!=null?s({error:y}):(r.push({error:y}),o)),d=y=>{if(i)return o;if(t?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:y})},p=y=>i?o:(i=!0,y!=null?u(y):c({done:!0})),m=()=>(r=new Ud,p(),{done:!0}),g=y=>(p(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:l,return:m,throw:g,push:d,end:p,get readableLength(){return r.size},onEmpty:async y=>{let w=y?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let v,x;w!=null&&(v=new Promise((k,S)=>{x=()=>{S(new aN)},w.addEventListener("abort",x)}));try{await Promise.race([a.promise,v])}finally{x!=null&&w!=null&&w?.removeEventListener("abort",x)}}},n==null)return o;let f=o;return o={[Symbol.asyncIterator](){return this},next(){return f.next()},throw(y){return f.throw(y),n!=null&&(n(y),n=void 0),{done:!0}},return(){return f.return(),n!=null&&(n(),n=void 0),{done:!0}},push:d,end(y){return f.end(y),n!=null&&(n(y),n=void 0),o},get readableLength(){return f.readableLength},onEmpty:y=>f.onEmpty(y)},o}var aN,lN=L(()=>{"use strict";iN();B4();aN=class extends Error{type;code;constructor(t,n){super(t??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}});function kre(e){return e.reason}function M4(e,t,n){if(t==null||e==null)return e;let r=n?.translateError??kre;if(t.aborted)return e.catch(()=>{}),Promise.reject(r(t));let o;return Promise.race([e,new Promise((s,i)=>{o=()=>{i(r(t))},t.addEventListener("abort",o)})]).finally(()=>{o!=null&&t.removeEventListener("abort",o)})}var F4=L(()=>{"use strict"});function q4(){return new cN}var cN,H4=L(()=>{"use strict";iN();F4();cN=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ui(),this.haveNext=ui()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ui(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,n){await this._push(t,n)}async end(t,n){t!=null?await this.throw(t):await this._push(void 0,n)}async _push(t,n){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ui(),await M4(this.readNext.promise,n?.signal,n)}}});function $4(e){return e[Symbol.asyncIterator]!=null}async function xre(e,t,n){try{await Promise.all(e.map(async r=>{for(;;){let{value:o,done:s}=await r.next();if(s===!0)break;await t.push(o,{signal:n}),n.throwIfAborted()}})),await t.end(void 0,{signal:n})}catch(r){await t.end(r,{signal:n}).catch(()=>{})}}async function*Are(e){let t=new AbortController,n=q4(),r=e.map(o=>$4(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());xre(r,n,t.signal).catch(()=>{});try{yield*n}finally{t.abort();for(let o of r)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*Tre(e){for(let t of e)yield*t}function Sre(...e){let t=[];for(let n of e)$4(n)||t.push(n);return t.length===e.length?Tre(t):Are(e)}var V4,j4=L(()=>{"use strict";H4();V4=Sre});function F(e,t){let n=t.safeParse(e);if(n.success)return n.data;throw E.fromZodError(n.error)}function Fe(e,t,n=[]){function r(){return{async firstPage(){return{items:n,hasMore:!1}},from(){return r()},async*[Symbol.asyncIterator](){}}}function o(s=t){return{async firstPage(){return X(e(s))},from(i){return i===void 0?r():o(i)},async*[Symbol.asyncIterator](){let i=s;for(;;){let a=await X(e(i));if(yield a,!a.hasMore||a.limitReached)return;i=a.nextCursor}}}}return o()}function di(e){return Pre(JSON.stringify(e))}function Io(e,t,n="Invalid pagination cursor"){try{return t.parse(JSON.parse(k6(e)))}catch(r){throw new E(n,{cause:r})}}function v6(e){try{return JSON.parse(k6(e))}catch{return}}function Pre(e){return btoa(String.fromCharCode(...new TextEncoder().encode(e)))}function k6(e){return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}function aa(e){return di(x6.parse(e))}function Md(e,t,n={}){return e===void 0?{offset:0,pageSize:t}:A6(Io(e,h.z.unknown()),n)}function A6(e,t={}){let n=x6.safeParse(e);if(!n.success)throw new E("Invalid pagination cursor",{cause:n.error});let r=n.data;if(t.maxPageSize!==void 0&&r.pageSize>t.maxPageSize)throw new E(`Pagination cursor page size must be at most ${t.maxPageSize}`);if(t.maxOffset!==void 0&&r.offset>t.maxOffset)throw new Ol(`Pagination reached this listing's supported depth limit (${t.maxOffset}); whether more items exist cannot be established.`);return r}function T6(e,t){return di({kind:"keyset",fingerprint:P6(t),cursor:e})}function S6(e,t){if(!Rre(e))return;let n=Ere.safeParse(e);if(!n.success)throw new E("Invalid pagination cursor",{cause:n.error});if(t===void 0||n.data.fingerprint!==P6(t))throw new E("Pagination cursor was created for a different query");return n.data.cursor}function Rre(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="keyset"}function P6(e){return JSON.stringify(gN(e))}function gN(e){return Array.isArray(e)?e.map(gN):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>[t,gN(n)])):e}function z(e){return function(t){return _n.fromPromise(t.json(),()=>new C(`Received non-JSON response from ${t.url}`)).andThen(n=>_re(t.url,e,n))}}function Ire(e){return _n.fromPromise(e.blob(),()=>new C(`Received unreadable binary response from ${e.url}`))}function _re(e,t,n){let r=t.safeParse(n);return r.success?go(r.data):Sr(C.fromZodError(r.error,{endpoint:e}))}function Cre(e){if(!(e instanceof O)||!E6(e.cause))return!1;let t=[e.cause.message,Nre(e.cause.data)].join(" ").toLowerCase();return(e.cause.code===3||e.cause.code===-32e3||e.cause.code===-32003||e.cause.code===-32015||e.cause.code===-32603)&&(t.includes("execution reverted")||t.includes("revert")||t.includes("invalid opcode"))}function z4(e){return!R6(e)||e.jsonrpc!=="2.0"?!1:"error"in e?E6(e.error):"result"in e}function E6(e){return R6(e)&&typeof e.code=="number"&&typeof e.message=="string"}function R6(e){return typeof e=="object"&&e!==null}function I6(e){return/^0x[a-fA-F0-9]*$/.test(e)}function W4(e,t="eth_call"){if(typeof e!="string"||!I6(e))throw new C(`Expected JSON-RPC ${t} result to be a hex string`);return e}function G4(e){return`0x${e.toString(16)}`}function Nre(e){if(e===void 0)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function _6(e,t,n){let r=eoe(e,t,n);return{signer:t,wallet:n,...r}}function pi(e){switch(e){case Se.EOA:return Rr.EOA;case Se.POLY_PROXY:return Rr.POLY_PROXY;case Se.GNOSIS_SAFE:return Rr.POLY_GNOSIS_SAFE;case Se.DEPOSIT_WALLET:return Rr.POLY_1271}}function oc(e){let t=pi(e.walletType);return{maker:e.wallet,signatureType:t,signer:t===Rr.POLY_1271?e.wallet:e.signer}}function N0(e,t){return e.signerType==="OWNER"?t:Dre(e.signer,t)}function Dre(e,t){let n=zn(`0x${e.slice(2).padStart(64,"0")}`),r=zt.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes"}],[n,Ore,t]);return eq(`${r}${Lre.slice(2)}`)}function Bre(e){let t=Ure.replace("%s",e.proxyFactory.slice(2).toLowerCase()).replace("%s",e.proxyImplementation.slice(2).toLowerCase());return zn(Je.keccak256(`0x${t}`))}function Mre(e,t){return Be(ho.fromCreate2({bytecodeHash:Bre(t),from:t.proxyFactory,salt:Je.keccak256(zt.encodePacked(["address"],[e]))}))}function Fre(e,t){return Be(ho.fromCreate2({bytecodeHash:t.safeInitCodeHash,from:t.safeFactory,salt:Je.keccak256(zt.encode([{name:"address",type:"address"}],[e]))}))}function O0(e,t){let n=zn(`0x${e.slice(2).padStart(64,"0")}`),r=zt.encode([{type:"address"},{type:"bytes32"}],[t.depositWalletFactory,n]);return Be(ho.fromCreate2({bytecodeHash:Kre(t.depositWalletImplementation,r),from:t.depositWalletFactory,salt:Je.keccak256(r)}))}function Af(e,t){let n=zn(`0x${e.slice(2).padStart(64,"0")}`),r=zt.encode([{type:"address"},{type:"bytes32"}],[t.depositWalletFactory,n]);return Be(ho.fromCreate2({bytecodeHash:Yre(t.depositWalletBeacon,r),from:t.depositWalletFactory,salt:Je.keccak256(r)}))}function Kre(e,t){let n=BigInt((t.length-2)/2),r=$re+(n<<56n);return zn(Je.keccak256(we.concat(we.fromNumber(r,{size:10}),we.fromHex(e),we.fromHex("0x6009"),we.fromHex(Hre),we.fromHex(qre),we.fromHex(t)),{as:"Hex"}))}function Yre(e,t){let n=BigInt((t.length-2)/2),r=Wre+(n<<56n);return zn(Je.keccak256(we.concat(we.fromNumber(r,{size:10}),we.fromHex(e),we.fromHex(zre),we.fromHex(jre),we.fromHex(Vre),we.fromHex(t)),{as:"Hex"}))}async function Qre(e,t){try{let n=await e.ethCall({to:t,data:Gre});return Zre(n)}catch(n){if(Cre(n))return ts;throw n}}async function Xre(e,t){let n=await Qre(e,t);return!Wt(n,ts)}async function Jre(e,t,n){return await Xre(e,n.depositWalletFactory)?Af(t,n):O0(t,n)}function Zre(e){return e.length<66?ts:Be(`0x${e.slice(-40)}`)}function eoe(e,t,n){if(Wt(n,t))return{signerType:"OWNER",walletType:Se.EOA};let r=e.walletDerivation;return Wt(n,Af(t,r))?{signerType:"OWNER",walletType:Se.DEPOSIT_WALLET}:Wt(n,O0(t,r))?{signerType:"OWNER",walletType:Se.DEPOSIT_WALLET}:Wt(n,Fre(t,r))?{signerType:"OWNER",walletType:Se.GNOSIS_SAFE}:Wt(n,Mre(t,r))?{signerType:"OWNER",walletType:Se.POLY_PROXY}:{signerType:"SESSION_KEY",walletType:Se.DEPOSIT_WALLET}}function Nr(e){return h.z.union([h.z.object({...e,assetId:C6,tokenId:h.z.never().optional()}),h.z.object({...e,assetId:h.z.never().optional(),tokenId:h.z.string()})])}function Fd(e){return h.z.union([h.z.object({...e,assetId:C6.optional(),tokenId:h.z.never().optional()}),h.z.object({...e,assetId:h.z.never().optional(),tokenId:h.z.string().optional()})])}function ve(e,t){if(noe(t))return roe(e,t.exceptions);let n=new URLSearchParams;for(let[r,o]of Object.entries(t)){let s=e[r];if(s!==void 0){if(NN(s)){for(let i of s)n.append(o,la(i));continue}n.append(o,la(s))}}return n}function Ee(e={}){return{format:"snake_case",exceptions:e}}function toe(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0){if(Array.isArray(r)){t.append(n,r.map(la).join(","));continue}t.append(n,la(r))}return t}function ca(e,t){return h.z.array(e).min(1).transform(n=>[...new Map(n.map(r=>[r.toLowerCase(),r])).values()]).refine(n=>n.length<=t,`At most ${t} distinct ids`)}function tn(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let o=O6(n);if(NN(r)){t.append(o,r.map(la).join(","));continue}t.append(o,la(r))}return t}function noe(e){return"format"in e}function roe(e,t){let n=new URLSearchParams;for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=t[r]??O6(r);if(NN(o)){for(let i of o)n.append(s,la(i));continue}n.append(s,la(o))}return n}function NN(e){return Array.isArray(e)}function O6(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function la(e){return String(e)}async function U0(e){return(await X(e.secureClob.get("/auth/ban-status/closed-only").andThen(z(c3)))).closedOnly}function M0(e,t){let n=F(t,soe),{cursor:r}=n;return Fe(o=>e.secureClob.get("/data/orders",{params:ve({assetId:n.assetId??n.tokenId,id:n.id,market:n.market,nextCursor:o},Ee({assetId:"asset_id"}))}).andThen(z(u3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function q0(e,t){let n=F(t,ioe);return X(e.secureClob.get(`/data/order/${n.orderId}`).andThen(z(IC)))}function Tf(e,t){let n=F(t,loe),{cursor:r}=n;return Fe(o=>e.secureClob.get("/data/trades",{params:ve({after:n.after,assetId:n.assetId??n.tokenId,before:n.before,id:n.id,makerAddress:n.makerAddress,market:n.market,nextCursor:o},Ee({assetId:"asset_id"}))}).andThen(z(d3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function V0(e){let t=pi(e.account.walletType);return X(e.secureClob.get("/notifications",{params:ve({signatureType:t},Ee())}).andThen(z(M3)))}async function z0(e,t){let n=F(t,coe),r=pi(e.account.walletType),o=ve({ids:n.ids.join(","),signatureType:r},Ee());await X(e.secureClob.del("/notifications",{params:o}))}async function W0(e,t){let n=F(t,uoe),r=pi(e.account.walletType);return X(e.secureClob.get("/balance-allowance",{params:ve({assetType:n.assetType,tokenId:n.assetId??n.tokenId,signatureType:r},Ee())}).andThen(z(m3)))}async function ON(e,t){let n=F(t,doe),r=pi(e.account.walletType),o=ve({assetType:n.assetType,tokenId:n.assetId??n.tokenId,signatureType:r},Ee());return await X(e.secureClob.get("/balance-allowance/update",{params:o})),W0(e,n)}async function K0(e,t){let n=F(t,poe);return(await X(e.secureClob.get("/order-scoring",{params:ve(n,Ee())}).andThen(z(h3)))).scoring}async function Q0(e,t){let n=F(t,moe).orderIds;return X(e.secureClob.post("/orders-scoring",{json:n}).andThen(z(f3)))}function J0(e,t){let{cursor:n,...r}=F(t,B6),o=pi(e.account.walletType);return Fe(s=>e.secureClob.get("/rewards/user",{params:ve({...r,nextCursor:s,signatureType:o},Ee())}).andThen(z(g3)).map(i=>({items:i.data,hasMore:i.nextCursor!==Yn,nextCursor:i.nextCursor===Yn?void 0:i.nextCursor})),n)}async function ev(e,t){let n=F(t,B6),r=pi(e.account.walletType);return X(e.secureClob.get("/rewards/user/total",{params:ve({...n,signatureType:r},Ee())}).andThen(z(y3)))}function nv(e,t){let{cursor:n,...r}=F(t,hoe),o=pi(e.account.walletType);return Fe(s=>e.secureClob.get("/rewards/user/markets",{params:ve({...r,nextCursor:s,signatureType:o},Ee())}).andThen(z(w3)).map(i=>({items:i.data,hasMore:i.nextCursor!==Yn,nextCursor:i.nextCursor===Yn?void 0:i.nextCursor})),n)}async function ov(e){let t=pi(e.account.walletType);return X(e.secureClob.get("/rewards/user/percentages",{params:ve({signatureType:t},Ee())}).andThen(z(b3)))}function nn(e,t={}){let{retries:n=2,maxDelaySeconds:r=5,sleep:o=ns}=t;function s(i){return e().orElse(a=>{if(!(a instanceof $)||i<=0)return Al(a);let l=a.retryAfter??1;return l>r?Al(a):_n.fromSafePromise(o(l*1e3).catch(()=>{})).andThen(()=>s(i-1))})}return s(n)}function iv(e,t={}){let{cursor:n,pageSize:r,window:o,...s}=F(t,foe);return Fe(i=>nn(()=>e.data.get("/v2/trades",{params:tn({...s,...o,limit:r,cursor:i})})).andThen(z(V$)),n)}function Sf(e,t){let{cursor:n,pageSize:r,window:o,...s}=F(t,goe);return Fe(i=>nn(()=>e.data.get("/v2/activity",{params:tn({...s,...o,excludeDepositsWithdrawals:!1,limit:r,cursor:i})})).andThen(z(j$)),n)}function Pf(e,t){let{cursor:n,pageSize:r,...o}=F(t,yoe);return Fe(s=>nn(()=>e.data.get("/v2/activity/combos",{params:tn({...o,limit:r,cursor:s})})).andThen(z(z$)),n)}function yf(e,t,n){if(n<0n)throw new E("Approval amount must be non-negative");if(n>lr)throw new E("Approval amount exceeds uint256 range");return{data:Boe(t,n),to:e}}function DN(e,t,n){return{data:_e.encodeData(M6,[t,n]),to:e}}function UN(e){return _e.decodeResult(M6,e)}function bf(e,t,n){return{data:Moe(t,n),to:e}}function BN(e,t,n){return{data:_e.encodeData(F6,[t,n]),to:e}}function MN(e){return _e.decodeResult(F6,e)}function FN(e,t,n){return{data:_e.encodeData(q6,[t,ps(BigInt(n),"Position ID")]),to:e}}function qN(e){return _e.decodeResult(q6,e)}function Ef(e,t,n){return{data:_e.encodeData(H6,[n.map(()=>t),n.map(r=>ps(BigInt(r),"id"))]),to:e}}function Rf(e){return _e.decodeResult(H6,e)}function S0(e,t,n){if(n<0n)throw new E("Transfer amount must be non-negative");if(n>lr)throw new E("Transfer amount exceeds uint256 range");return{data:Foe(t,n),to:e}}function HN(e,t,n){return{data:_e.encodeData(Aoe,[t,ps(n,"Session key expiry")]),to:e}}function $N(e,t){return{data:_e.encodeData(Toe,[t]),to:e}}function VN(e,t,n,r){if(n<=0n)throw new E("Perps deposit amount must be positive");return{data:_e.encodeData(Soe,[t,ps(n,"Perps deposit amount"),r]),to:e}}function jN(e,t,n,r){return{data:qoe(t,n,r),to:e}}function zN(e,t,n,r){return{data:Hoe(t,n,r),to:e}}function WN(e,t,n){return{data:$oe(t,n),to:e}}function cv(e,t,n){return{data:_e.encodeData(_oe,[GN(t),ps(n,"Split amount")]),to:e}}function uv(e,t,n){return{data:_e.encodeData(Coe,[GN(t),ps(n,"Merge amount")]),to:e}}function wf(e,t,n,r){return{data:_e.encodeData(Noe,[GN(t),BigInt(Voe(n)),ps(r,"Redeem amount")]),to:e}}function dv(e,t){return{data:_e.encodeData(Ooe,[t.map(n=>ps(n,"Leg position ID"))]),to:e}}function Boe(e,t){return ge(t>=0n,"Approval amount must be non-negative"),_e.encodeData(koe,[e,t])}function Moe(e,t){return _e.encodeData(Poe,[e,t])}function Foe(e,t){return _e.encodeData(xoe,[e,t])}function qoe(e,t,n){return _e.encodeData(Eoe,[e,LN,t,$6,ps(n,"Split amount")])}function Hoe(e,t,n){return _e.encodeData(Roe,[e,LN,t,$6,ps(n,"Merge amount")])}function $oe(e,t){return _e.encodeData(Ioe,[e,LN,t,Uoe])}function ps(e,t){if(e<0n)throw new E(`${t} must be non-negative`);if(e>lr)throw new E(`${t} exceeds uint256 range`);return e}function GN(e){if(woe.test(e))return e.toLowerCase();if(voe.test(e)){let t=e.toLowerCase();if(t.endsWith("00")||t.endsWith("01"))return t.slice(0,boe)}throw new E("Protocol v2 condition ID must be bytes31, or bytes32 with a binary outcome byte")}function Voe(e){if(e!==0&&e!==1)throw new E("Protocol v2 outcome index must be 0 or 1");return e}function KN(e){return _e.encodeData(Doe,[e.map(t=>({typeCode:1,to:t.to,value:t.value??0n,data:t.data}))])}function YN(e){let t=e.map(n=>joe(n));return _e.encodeData(Loe,[t.length===0?"0x":zt.encodePacked(Array.from({length:t.length},()=>"bytes"),t)])}function joe(e){let t=e.value??0n;return zt.encodePacked(["uint8","address","uint256","uint256","bytes"],[0,e.to,t,BigInt((e.data.length-2)/2),e.data])}function bn(e,t="Expected a TransactionHandle"){return ge(typeof e=="object"&&e!==null&&"transactionHash"in e&&"transactionId"in e&&"wait"in e&&typeof e.wait=="function",t),e}function e8(e){return async function(t){let n=await t.next();for(;!n.done;)try{switch(n.value.kind){case"requestAddress":n=await t.next(await e.getAddress());break;case"signAuthMessage":n=await t.next(await e.signTypedData(n.value.payload));break}}catch(r){n=await t.throw(r)}return n.value}}function wn(e){return async function(t){let n=await t.next();for(;!n.done;)try{switch(n.value.kind){case"requestAddress":n=await t.next(await e.getAddress());break;case"signGaslessTypedData":case"signOrder":n=await t.next(await e.signTypedData(n.value.payload));break;case"signGaslessMessage":n=await t.next(await e.signMessage(n.value.payload));break;case"sendErc20ApprovalTransaction":case"sendErc1155ApprovalForAllTransaction":case"sendErc20TransferTransaction":case"sendPerpsDepositTransaction":case"sendMergePositionsTransaction":case"sendRedeemPositionsTransaction":case"sendSplitPositionTransaction":n=await t.next(await e.sendTransaction(n.value.request));break}}catch(r){n=await t.throw(r)}return n.value}}function QN(){return{kind:"requestAddress"}}function Qn(e,t){return{chainId:e,...t}}async function If(e,t){let n=F(t,Joe);return X(e.relayer.get("/v1/account/transactions/params",{params:ve(n,{address:"address",type:"type"})}).andThen(z(l4)))}async function _f(e,t){let n=await tse(e,t);return n.type===Se.EOA?!1:X(e.relayer.get("/deployed",{params:ve({address:n.wallet,type:n.type===Se.DEPOSIT_WALLET?_r.WALLET:void 0},{address:"address",type:"type"})}).andThen(z(u4)).map(({deployed:r})=>r))}async function tse(e,t){if(t!==void 0)return F(t,ese);if(!e.isSecureClient())throw new E("Gasless readiness inference requires a secure client. Pass a wallet and type when using a public client.");return e.account.walletType!==Se.EOA?{wallet:e.account.wallet,type:e.account.walletType}:{wallet:await Jre(e.rpc,e.account.signer,e.environment.walletDerivation),type:Se.DEPOSIT_WALLET}}async function pv(e){return ge(e.supportsGasless,"Deposit Wallet deployment requires a Relayer API Key or Builder API Key in the client configuration."),vf(e,{from:e.account.signer,metadata:"Deploy Deposit Wallet",to:e.environment.walletDerivation.depositWalletFactory,type:_r.WALLET_CREATE})}async function XN(e,t){let n=F(t,Zoe);return X(e.relayer.get(`/v1/account/transactions/${n.transactionId}`).andThen(z(d4)))}async function Or(e,t){let n=F(t,rse);return ge(e.supportsGasless,"Gasless transactions require a Relayer API Key or Builder API Key in the client configuration."),ge(e.account.walletType===Se.GNOSIS_SAFE||e.account.walletType===Se.POLY_PROXY||e.account.walletType===Se.DEPOSIT_WALLET,"Gasless transaction preparation supports Deposit Wallet, Safe-backed, and proxy-backed accounts"),async function*(){let r=Be(yield QN());ge(r===e.account.signer,"Wallet client address does not match the authenticated signer");for(let o=0;o<=K4;o+=1)try{switch(e.account.walletType){case Se.POLY_PROXY:return yield*ose(e,n);case Se.DEPOSIT_WALLET:return yield*sse(e,n);case Se.GNOSIS_SAFE:return yield*ise(e,n)}ge(!1,"Unsupported wallet type for gasless transaction")}catch(s){if(!yv(s)||o===K4)throw s;await ns(e.environment.relayerPollFrequencyMs)}ge(!1,"Expected gasless transaction retry loop to return")}.call(null)}async function*ose(e,t){let n=yield*mv(e,t.calls,t.metadata);return vf(e,n)}async function*mv(e,t,n){let r=await If(e,{address:e.account.signer,type:_r.PROXY}),o=e.environment.walletDerivation.proxyFactory,s=KN(t),i="0",a="0",l=(await e.rpc.ethEstimateGas({data:s,from:e.account.signer,to:o})).toString(),c=e.environment.contracts.relayHub,u=r.address,d=use(e.account.signer,o,s,i,a,l,r.nonce,c,u),p=rs(yield a8(d));return{data:s,from:e.account.signer,...n!==void 0&&{metadata:n},nonce:r.nonce,proxyWallet:e.account.wallet,signature:p,signatureParams:{gasLimit:l,gasPrice:a,relay:u,relayHub:c,relayerFee:i},to:o,type:_r.PROXY}}function hv(e){return!(e instanceof O)||e.status!==400?void 0:/batch nonce\s+\d+\s+does not match on-chain nonce\s+(\d+)/i.exec(e.message)?.[1]}async function*sse(e,t){let n=yield*qd(e,t.calls,t.metadata);try{return await vf(e,n)}catch(r){let o=hv(r);if(o===void 0)throw r;let s=yield*fv(e,n,t.calls,o);return vf(e,s)}}async function*qd(e,t,n){let r=await If(e,{address:e.account.signer,type:_r.WALLET}),o=t.map(s8),s=`${Math.floor(Date.now()/1e3)+Yoe}`,i=N0(e.account,rs(yield l8(i8({calls:o,chainId:e.environment.chainId,deadline:s,nonce:r.nonce,wallet:e.account.wallet}))));return{depositWalletParams:{calls:o,deadline:s,depositWallet:e.account.wallet},from:e.account.signer,...n!==void 0&&{metadata:n},nonce:r.nonce,signature:i,to:e.environment.walletDerivation.depositWalletFactory,type:_r.WALLET}}async function*fv(e,t,n,r){let o=N0(e.account,rs(yield l8(i8({calls:n.map(s8),chainId:e.environment.chainId,deadline:t.depositWalletParams.deadline,nonce:r,wallet:e.account.wallet}))));return{...t,nonce:r,signature:o}}async function*ise(e,t){let n=yield*gv(e,t.calls,t.metadata);return vf(e,n)}async function*gv(e,t,n){let r=await If(e,{address:e.account.signer,type:_r.SAFE}),o=ase(t,e.environment.contracts.safeMultisend),s=cse({chainId:e.environment.chainId,data:o.data,nonce:r.nonce,operation:o.operation,safeAddress:e.account.wallet,to:o.to,value:o.value}),i=rs(yield a8(zn(fo.getSignPayload(s))));return{data:o.data,from:e.account.signer,...n!==void 0&&{metadata:n},nonce:r.nonce,proxyWallet:e.account.wallet,signature:dse(i),signatureParams:lse(o.operation),to:o.to,type:_r.SAFE,value:o.value>0n?`${o.value}`:void 0}}async function vf(e,t){let n=F(t,c4),r=await X(e.relayer.post("/submit",{json:n}).andThen(z(QC)));return new Cf(e,r)}function yv(e){if(e instanceof $)return!0;if(!(e instanceof O)||e.status!==400)return!1;if(/wallet busy/i.test(e.message)&&/active action/i.test(e.message)||/wallet has in-flight action/i.test(e.message))return!0;let t=/batch nonce\s+(\d+)\s+does not match on-chain nonce\s+(\d+)/i.exec(e.message);if(t===null)return!1;let n=t[1],r=t[2];return n===void 0||r===void 0?!1:BigInt(n)<BigInt(r)}function s8(e){return{data:e.data,target:e.to,value:`${e.value??0n}`}}function i8(e){let t={chainId:e.chainId,name:Goe,verifyingContract:e.wallet,version:Koe};return{domain:t,message:{calls:e.calls.map(n=>({data:n.data,target:n.target,value:BigInt(n.value)})),deadline:BigInt(e.deadline),nonce:BigInt(e.nonce),wallet:e.wallet},primaryType:"Batch",types:{Batch:Xoe,Call:Qoe,EIP712Domain:fo.extractEip712DomainTypes(t)}}}function ase(e,t){if(e.length===1){let[n]=e;return{data:n.data,operation:0,to:n.to,value:n.value??0n}}return{data:YN(e),operation:1,to:t,value:0n}}function lse(e){return{baseGas:"0",gasPrice:"0",gasToken:ts,operation:`${e}`,refundReceiver:ts,safeTxnGas:"0"}}function cse(e){return{domain:{chainId:e.chainId,verifyingContract:e.safeAddress},message:{baseGas:0n,data:e.data,gasPrice:0n,gasToken:ts,nonce:BigInt(e.nonce),operation:e.operation,refundReceiver:ts,safeTxGas:0n,to:e.to,value:e.value},primaryType:"SafeTx",types:{EIP712Domain:zoe,SafeTx:Woe}}}function a8(e){return{kind:"signGaslessMessage",payload:e}}function l8(e){return{kind:"signGaslessTypedData",payload:e}}function use(e,t,n,r,o,s,i,a,l){return zn(Je.keccak256(we.concat(we.fromString("rlx:"),we.fromHex(e),we.fromHex(t),we.fromHex(n),we.fromNumber(BigInt(r),{size:32}),we.fromNumber(BigInt(o),{size:32}),we.fromNumber(BigInt(s),{size:32}),we.fromNumber(BigInt(i),{size:32}),we.fromHex(a),we.fromHex(l)),{as:"Hex"}))}function dse(e){let t=e.slice(2),n=Number.parseInt(t.slice(128,130),16),r=n===0||n===1?n+31:n===27||n===28?n+4:n;return zn(`0x${t.slice(0,128)}${r.toString(16).padStart(2,"0")}`)}async function JN(e,t){let n=F(t,pse),r=n.amount==="max"?lr:n.amount;return async function*(){return e.account.walletType===Se.EOA?bn(yield h8(Qn(e.environment.chainId,yf(n.tokenAddress,n.spenderAddress,r)))):yield*await Or(e,{calls:[yf(n.tokenAddress,n.spenderAddress,r)],metadata:n.metadata??`Approve ${n.amount} of ${n.tokenAddress} to ${n.spenderAddress}`})}.call(null)}function Nf(e,t){return JN(e,t).then(wn(e.signer))}async function ZN(e,t){let n=F(t,mse);return async function*(){return e.account.walletType===Se.EOA?bn(yield f8(Qn(e.environment.chainId,bf(n.tokenAddress,n.operatorAddress,n.approved)))):yield*await Or(e,{calls:[bf(n.tokenAddress,n.operatorAddress,n.approved)],metadata:n.metadata??`${n.approved?"Approve":"Revoke"} ${n.operatorAddress} on ${n.tokenAddress}`})}.call(null)}function Of(e,t){return ZN(e,t).then(wn(e.signer))}async function Lf(e,t){let{user:n}=F(t,hse),r=await m8(e,n);return{isFullyApproved:r.erc20.length===0&&r.erc1155.length===0,missing:r}}async function eO(e){let t=await m8(e,e.account.wallet),n=t.erc20.map(o=>yf(o.tokenAddress,o.spenderAddress,o.amount)),r=t.erc1155.map(o=>bf(o.tokenAddress,o.operatorAddress,!0));return async function*(){if(!(n.length===0&&r.length===0)){if(e.account.walletType===Se.EOA){for(let o of n)await bn(yield h8(Qn(e.environment.chainId,o))).wait();for(let o of r)await bn(yield f8(Qn(e.environment.chainId,o))).wait();return}await(yield*await Or(e,{calls:[...n,...r],metadata:"Trading setup approvals"})).wait()}}.call(null)}function xv(e){return eO(e).then(wn(e.signer)).then(()=>{})}async function m8(e,t){let n=fse(e),r=[...n.erc20.map(a=>DN(a.tokenAddress,t,a.spenderAddress)),...n.erc1155.map(a=>BN(a.tokenAddress,t,a.operatorAddress))],o=await e.rpc.ethCallBatch(r),s=o.slice(0,n.erc20.length),i=o.slice(n.erc20.length);try{return{erc20:n.erc20.filter((a,l)=>UN(s[l])<a.amount),erc1155:n.erc1155.filter((a,l)=>!MN(i[l]))}}catch(a){throw new C("Expected JSON-RPC approval checks to return ABI-encoded values",{cause:a})}}function fse(e){let{contracts:t}=e.environment;return{erc20:[{amount:lr,spenderAddress:t.standardExchange,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.negRiskExchange,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.collateralAdapter,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.negRiskCollateralAdapter,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.protocolV2Router,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.exchangeV3,tokenAddress:t.collateralToken},{amount:lr,spenderAddress:t.perpsDepositContract,tokenAddress:t.collateralToken}],erc1155:[{operatorAddress:t.standardExchange,tokenAddress:t.conditionalTokens},{operatorAddress:t.negRiskExchange,tokenAddress:t.conditionalTokens},{operatorAddress:t.collateralAdapter,tokenAddress:t.conditionalTokens},{operatorAddress:t.negRiskCollateralAdapter,tokenAddress:t.conditionalTokens},{operatorAddress:t.autoRedeemOperator,tokenAddress:t.conditionalTokens},{operatorAddress:t.binaryModule,tokenAddress:t.conditionalTokens},{operatorAddress:t.negRiskModule,tokenAddress:t.conditionalTokens},{operatorAddress:t.protocolV2Router,tokenAddress:t.positionManager},{operatorAddress:t.exchangeV3,tokenAddress:t.positionManager},{operatorAddress:t.autoRedeemOperator,tokenAddress:t.positionManager}]}}function h8(e){return{kind:"sendErc20ApprovalTransaction",request:e}}function f8(e){return{kind:"sendErc1155ApprovalForAllTransaction",request:e}}async function tO(e,t){return X(e.clob.post("/auth/api-key",{headers:E8(t)}).andThen(z(_C)))}async function nO(e,t){return X(e.clob.get("/auth/derive-api-key",{headers:E8(t)}).andThen(z(_C)))}async function Av(e,t){try{return await tO(e,t)}catch(n){if(!(n instanceof O)||n.status!==400)throw n}return nO(e,t)}async function Tv(e){return(await X(e.secureClob.get("/auth/api-keys").andThen(z(v3)))).apiKeys}async function Sv(e){await X(e.secureClob.del("/auth/api-key").andThen(z(h.z.literal("OK"))))}async function x8(e){return X(e.secureClob.post("/auth/builder-api-key").andThen(z(k3)))}async function T8(e){return X(e.secureClob.get("/auth/builder-api-key").andThen(z(x3)))}async function P8(e){await X(e.clob.del("/auth/builder-api-key").andThen(z(h.z.literal("OK"))))}function E8(e){return{POLY_ADDRESS:e.address,POLY_NONCE:`${e.nonce}`,POLY_SIGNATURE:e.signature,POLY_TIMESTAMP:`${e.timestamp}`}}function Ev(e,t){let n=F(t,yse),{cursor:r}=n;return Fe(o=>e.clob.get("/builder/trades",{params:ve({after:n.after,assetId:n.assetId??n.tokenId,before:n.before,builderCode:n.builderCode,id:n.id,market:n.market,nextCursor:o},Ee({assetId:"asset_id",builderCode:"builder_code"}))}).andThen(z(A3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function Iv(e,t){let n=F(t,bse);return(await X(e.clob.get("/midpoint",{params:sc(n)}).andThen(z(P3)))).mid}async function Cv(e,t){let n=F(t,wse);return X(e.clob.post("midpoints",{json:Xv(n)}).andThen(z(E3)))}async function I8(e,t){let n=F(t,vse);return(await X(e.clob.get("/tick-size",{params:sc(n)}).andThen(z(W3)))).minimumTickSize}async function C8(e,t){let n=F(t,kse);return(await X(e.clob.get("/neg-risk",{params:sc(n)}).andThen(z(U3)))).negRisk}async function rO(e,t){let n=F(t,xse);return X(e.clob.get(`/markets-by-token/${n.assetId??n.tokenId}`).andThen(z(L3)))}async function oO(e,t){let n=F(t,Ase);return X(e.clob.get(`/clob-markets/${n.conditionId}`).andThen(z(D3)))}async function sO(e,t){let n=F(t,Tse);return X(e.clob.get(`/fees/builder-fees/${n.builderCode}`).andThen(z(T3)).mapErr(r=>r instanceof O&&r.status===404?new E(`Unknown builder code: ${n.builderCode}`,{cause:r}):r))}async function Ov(e,t){let n=F(t,Sse);return(await X(e.clob.get("/price",{params:sc(n)}).andThen(z(R3)))).price}async function Dv(e,t){let n=F(t,Pse);return X(e.clob.post("prices",{json:Dse(n)}).andThen(z(I3)))}async function Hd(e,t){let n=F(t,Ese);return X(e.clob.get("/book",{params:sc(n)}).andThen(z(q3)))}async function Mv(e,t){let n=F(t,Rse);return X(e.clob.post("books",{json:Xv(n)}).andThen(z(H3)))}async function qv(e,t){let n=F(t,Ise);return(await X(e.clob.get("/spread",{params:sc(n)}).andThen(z(_3)))).spread}async function $v(e,t){let n=F(t,_se);return X(e.clob.post("spreads",{json:Xv(n)}).andThen(z(C3)))}async function jv(e,t){let n=F(t,Cse);return X(e.clob.get("/last-trade-price",{params:sc(n)}).andThen(z(N3)))}async function Wv(e,t){let n=F(t,Nse);return X(e.clob.post("last-trades-prices",{json:Xv(n)}).andThen(z(O3)))}function Kv(e,t={}){let{cursor:n,...r}=F(t,Ose);return Fe(o=>e.clob.get("/rewards/markets/current",{params:ve({...r,nextCursor:o},Ee())}).andThen(z(V3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),n)}function Qv(e,t){let{cursor:n,...r}=F(t,Lse);return Fe(o=>e.clob.get(`rewards/markets/${r.conditionId}`,{params:ve({nextCursor:o,sponsored:r.sponsored},Ee())}).andThen(z(j3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),n)}function Xv(e){return e.map(t=>({token_id:t.assetId??t.tokenId}))}function Dse(e){return e.map(t=>({token_id:t.assetId??t.tokenId,side:t.side}))}function sc(e){let{assetId:t,tokenId:n,...r}=e;return ve({...r,tokenId:e.assetId??e.tokenId},Ee())}async function Zv(e){return B8(e),X(e.combos.post("/v1/collateral-return/plan",{json:{wallet:e.account.wallet},timeout:D8}).andThen(z(w4)))}async function iO(e,t){let{plan:n}=F(t,Use);if(ge(e.supportsGasless,"Collateral return execution requires a Relayer API Key or Builder API Key in the client configuration."),B8(e),!Wt(n.wallet,e.account.wallet))throw new E("The collateral return plan was created for a different wallet than the authenticated account.");if(n.chainId!==e.environment.chainId)throw new E(`The collateral return plan was created for chain ${n.chainId}, but the client is configured for chain ${e.environment.chainId}.`);return async function*(){let r=[{data:n.routerCall.data,to:n.routerCall.to,value:0n}];for(let o=0;o<=Y4;o+=1)try{let s=yield*Bse(e,r);try{return await Q4(e,n.planHash,s)}catch(i){let a=hv(i);if(a===void 0||s.type!==_r.WALLET)throw i;let l=yield*fv(e,s,r,a);return await Q4(e,n.planHash,l)}}catch(s){if(!yv(s)||o===Y4)throw s;await ns(e.environment.relayerPollFrequencyMs)}ge(!1,"Expected collateral return submit retry loop to return")}.call(null)}function tk(e,t){return iO(e,t).then(wn(e.signer))}function B8(e){ge(e.account.walletType===Se.DEPOSIT_WALLET||e.account.walletType===Se.GNOSIS_SAFE||e.account.walletType===Se.POLY_PROXY,"Collateral return supports Deposit Wallet, Safe Wallet, and Proxy Wallet accounts")}function Bse(e,t){switch(e.account.walletType){case Se.GNOSIS_SAFE:return gv(e,t,uN);case Se.POLY_PROXY:return mv(e,t,uN);default:return qd(e,t,uN)}}async function Q4(e,t,n){let r=await X(e.combos.post("/v1/collateral-return/submit",{json:{envelope:n,plan_hash:t},timeout:D8}).andThen(z(QC)));return new Cf(e,r)}function $se(e){if(e.holdersOnly===!0||e.getPositions===!0)return;if(e.order===void 0)return{ascending:!1,order:"createdAt",parentEntityId:e.parentEntityId,parentEntityType:e.parentEntityType};let t=Hse.safeParse(e.order);if(t.success)return{ascending:e.ascending??!0,order:t.data,parentEntityId:e.parentEntityId,parentEntityType:e.parentEntityType}}function rk(e,t){let{cursor:n,pageSize:r,...o}=F(t,Mse),s=$se(o);return Fe(i=>{if(i===void 0)return s===void 0?X4(e,o,{offset:0,pageSize:r}):J4(e,s,r);let a=v6(i);if(a===void 0)throw new E("Invalid pagination cursor");let l=S6(a,s);return l===void 0||s===void 0?X4(e,o,A6(a,M8)):J4(e,s,r,l)},n)}function X4(e,t,n){return e.gamma.get("/comments",{params:ve({ascending:t.ascending,getPositions:t.getPositions,holdersOnly:t.holdersOnly,limit:n.pageSize,offset:n.offset,order:t.order,parentEntityId:t.parentEntityId,parentEntityType:t.parentEntityType},Ee())}).andThen(z(Hh)).map(r=>{let o=r.filter(s=>s.parentCommentID==null).length>=n.pageSize;return{items:r,hasMore:o,limitReached:o&&n.offset+n.pageSize>lO,nextCursor:o?aa({offset:n.offset+n.pageSize,pageSize:n.pageSize}):void 0}})}function J4(e,t,n,r){return e.gamma.get("/comments/keyset",{params:ve({afterCursor:r,ascending:t.ascending,limit:n,order:t.order,parentEntityId:t.parentEntityId,parentEntityType:t.parentEntityType},Ee())}).andThen(z(k_)).map(o=>({items:o.items,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor===void 0?void 0:T6(o.nextCursor,t)}))}async function sk(e,t){let n=F(t,Fse);return X(e.gamma.get(`comments/${n.id}`,{params:ve({getPositions:n.getPositions},Ee())}).andThen(z(Hh)))}function ak(e,t){let{address:n,cursor:r,pageSize:o,...s}=F(t,qse);return Fe(i=>{let a=Md(i,o,M8);return e.gamma.get(`comments/user_address/${n}`,{params:ve({ascending:s.ascending,limit:a.pageSize,offset:a.offset,order:s.order},Ee())}).andThen(z(Hh)).map(l=>{let c=l.length>=a.pageSize;return{items:l,hasMore:c,limitReached:c&&a.offset+a.pageSize>lO,nextCursor:c?aa({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},r)}function F8(e,t){let n;try{n=new URL(e)}catch(a){throw new E("Expected a valid Polymarket URL.",{cause:a})}if(n.protocol!=="https:"||n.hostname!=="polymarket.com"&&n.hostname!=="www.polymarket.com")throw new E("Expected a valid Polymarket URL.");let[r,o,...s]=n.pathname.split("/").filter(Boolean),i=s[0];if(t==="market"&&r==="event"&&o!==void 0&&s.length<=1)return i??o;if(r!==t||o===void 0||s.length>0)throw new E(`Expected a Polymarket ${t} URL.`);return o}function ck(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,Vse);return Fe(s=>e.gamma.get("/events/keyset",{params:Xse({...o,pageSize:r,cursor:s===void 0?void 0:Wse(s,o)})}).andThen(z(b_)).map(i=>({items:i.items,hasMore:i.nextCursor!==void 0,nextCursor:i.nextCursor===void 0?void 0:T6(i.nextCursor,o)})),n)}function Wse(e,t){let n=v6(e);return n===void 0?e:S6(n,t)??e}async function dk(e,t){let n=F(t,jse);if("id"in n)return X(e.gamma.get(`events/${n.id}`,{params:Jse(n)}).andThen(z(ei)));let r="url"in n?F8(n.url,"event"):n.slug;return X(e.gamma.get(`events/slug/${r}`,{params:Zse(n)}).andThen(z(ei)))}async function mk(e,t){let n=F(t,zse);return X(e.gamma.get(`events/${n.id}/tags`).andThen(z(w_)))}async function fk(e,t){let{conditionIds:n,eventIds:r,questionId:o}=F(t,Yse);return X(nn(()=>e.data.get("/v2/resolutions",{params:tn({questionId:o,condition:n,eventId:r})})).andThen(z(o4)))}async function yk(e,t){let{eventIds:n}=F(t,Qse);return X(nn(()=>e.data.get("/v2/live-volume",{params:tn({eventId:n})})).andThen(z(Q$)))}function Xse(e){return ve(e,Ee({cursor:"after_cursor",excludeTagIds:"exclude_tag_id",gameIds:"game_id",ids:"id",pageSize:"limit",seriesIds:"series_id",tagIds:"tag_id"}))}function Jse(e){return ve({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},Ee())}function Zse(e){return ve({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},Ee())}function wk(e,t={}){let{cursor:n,pageSize:r,window:o}=F(t,eie);return Fe(s=>nn(()=>e.data.get("/v2/builders/leaderboard",{params:tn({timePeriod:o,limit:r,cursor:s})})).andThen(z(Z$)),n)}async function kk(e,t={}){let{interval:n,bucketLimit:r}=F(t,tie);return X(nn(()=>e.data.get("/v2/builders/volume",{params:tn({interval:n,limit:r})})).andThen(z(e4)))}function Ak(e,t={}){let{category:n,cursor:r,pageSize:o,sortBy:s,window:i}=F(t,nie);return Fe(a=>nn(()=>e.data.get("/v2/leaderboard",{params:tn({category:n,cursor:a,limit:o,sortBy:s,timePeriod:i})})).andThen(z(t4)),r)}async function Df(e,t){let{category:n,user:r,window:o}=F(t,rie);return X(nn(()=>e.data.get("/v2/leaderboard",{params:tn({category:n,timePeriod:o,user:r})})).andThen(z(n4)))}function Pk(e,t={}){let{category:n,cursor:r,pageSize:o,window:s}=F(t,oie);return Fe(i=>nn(()=>e.data.get("/v2/biggest-winners",{params:tn({category:n,cursor:i,limit:o,timePeriod:s})})).andThen(z(r4)),r)}function Ek(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,sie);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/market-clarifications",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(z(G3)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?aa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}function Uf(e,t={}){let n=F(t,iie);return Fe(r=>e.gamma.get("/markets/keyset",{params:kie({...n,cursor:r??n.cursor})}).andThen(z(d_)).map(o=>({items:o.items,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor})),n.cursor)}function _k(e,t={}){let n=F(t,pie);return Fe(r=>e.rfq.get("/v1/rfq/combo-markets",{params:xie({...n,cursor:r??n.cursor})}).andThen(z(m4)).map(o=>({items:o.markets,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor})),n.cursor)}async function Nk(e,t){let n=F(t,uie);return"id"in n?Aie(e,n):"url"in n?Z4(e,{includeTag:n.includeTag,locale:n.locale,slug:F8(n.url,"market")}):Z4(e,n)}async function Lk(e,t){let n=F(t,die);return X(e.gamma.get(`markets/${n.id}/tags`).andThen(z(p_)))}function Uk(e,t){let{conditionIds:n,cursor:r,includePnl:o,minBalance:s,pageSize:i}=F(t,mie);return Fe(a=>nn(()=>e.data.get("/v2/holders",{params:tn({condition:n,limit:i,cursor:a,includePnl:o,minBalance:s})})).andThen(z(K$)),r)}function Mk(e,t){let{assetId:n,cursor:r,pageSize:o,...s}=F(t,wie);return Fe(i=>nn(()=>e.data.get("/v2/prices-history",{params:tn({...s,tokenId:n,limit:o,cursor:i})})).andThen(z(G$)),r)}async function qk(e,t={}){let{conditionIds:n}=F(t,vie);return X(nn(()=>e.data.get("/v2/oi",{params:tn({condition:n})})).andThen(z(Y$)))}function kie(e){return ve(e,Ee({cursor:"after_cursor",ids:"id",pageSize:"limit"}))}function xie(e){return ve({cursor:e.cursor,exclude:e.exclude?.join(","),pageSize:e.pageSize},{cursor:"cursor",exclude:"exclude",pageSize:"limit"})}async function Z4(e,t){return X(e.gamma.get(`markets/slug/${t.slug}`,{params:ve({includeTag:t.includeTag,locale:t.locale},Ee())}).andThen(z(Cw)))}async function Aie(e,t){return X(e.gamma.get(`markets/${t.id}`,{params:ve({includeTag:t.includeTag,locale:t.locale},Ee())}).andThen(z(Cw)))}function uO(e){if(!(e instanceof O))return e;let t=Tie(e);return t===void 0?e:new O(e.message,{cause:e,...e.code!==void 0?{code:e.code}:{},restriction:t,...e.retryAfter!==void 0?{retryAfter:e.retryAfter}:{},status:e.status})}function Tie(e){if(e.status===425)return"restarting";if(e.status===503&&e.code==="post_only_mode")return"post_only"}async function $k(e,t){let n=F(t,Sie);return Yk(e,"/order",{orderID:n.orderId})}async function jk(e,t){let n=F(t,Pie);return Yk(e,"/orders",n.orderIds)}async function Wk(e){return Yk(e,"/cancel-all")}async function Kk(e,t){let n=F(t,Rie);return Yk(e,"/cancel-market-orders",{asset_id:n.assetId??n.tokenId,market:n.market})}async function Yk(e,t,n){return X(e.secureClob.del(t,{json:n,rateLimitBucket:"cancel"}).mapErr(uO).andThen(z(S3)))}async function Xk(e,t){let n=F(t,Iie),r=n.side===Ue.BUY?n.amount:n.shares;return dO(e,{amount:r,assetId:n.assetId,orderType:n.orderType,side:n.side})}async function dO(e,t){let n=await Hd(e,{assetId:t.assetId});return Jk({amount:t.amount,orderBook:n,orderType:t.orderType,side:t.side})}function Jk(e){let{orderBook:t}=e,n=e.side===Ue.BUY?Cie(t.asks,e.amount,e.orderType):Nie(t.bids,e.amount,e.orderType);return ge(_ie(n,t.tickSize),`Resolved market price fell outside the valid range for tick size ${t.tickSize}.`),n}function _ie(e,t){return e>=t&&e<=1-t}function Cie(e,t,n){if(e.length===0)throw new So("No resting liquidity.");let r=0;for(let s=e.length-1;s>=0;s-=1){let i=e[s];if(i!==void 0&&(r+=Number.parseFloat(i.size)*Number.parseFloat(i.price),r>=t))return Number.parseFloat(i.price)}if(n===cn.FOK)throw new So("Insufficient liquidity for full fill.");let o=e[0];return Number.parseFloat(o.price)}function Nie(e,t,n){if(e.length===0)throw new So("No resting liquidity.");let r=0;for(let s=e.length-1;s>=0;s-=1){let i=e[s];if(i!==void 0&&(r+=Number.parseFloat(i.size),r>=t))return Number.parseFloat(i.price)}if(n===cn.FOK)throw new So("Insufficient liquidity for full fill.");let o=e[0];return Number.parseFloat(o.price)}function $d(e){return async function(t){F(t,j8);let n=z8(e,t);return X(e.secureClob.post("/order",{json:n,rateLimitBucket:"order"}).mapErr(uO).andThen(z(NC)))}}function tx(e){return async function(t){F(t,Die);let n=t.map(r=>z8(e,r));return X(e.secureClob.post("/orders",{json:n,rateLimitBucket:"order"}).mapErr(uO).andThen(z($3)))}}function z8(e,t){return ge(t.postOnly!==!0||t.orderType===cn.GTC||t.orderType===cn.GTD,"Post-only orders are only supported for GTC and GTD order types."),{deferExec:!1,order:{builder:t.builder,expiration:`${t.expiration}`,maker:t.maker,makerAmount:t.makerAmount,metadata:t.metadata,salt:Number(BigInt(t.salt)),side:t.side,signature:t.signature,signatureType:t.signatureType,signer:t.signer,takerAmount:t.takerAmount,timestamp:t.timestamp,tokenId:t.tokenId},orderType:t.orderType,owner:e.credentials.key,...t.postOnly===!0?{postOnly:!0}:{}}}function Uie(e){try{let t=BigInt(e);return t>=0n&&t<=Oie}catch{return!1}}function K8(e){let t=zt.encode([{name:"legs",type:"uint256[]"}],[e]),n=Je.keccak256(zt.encode([{name:"moduleId",type:"uint256"},{name:"data",type:"bytes"}],[G8,t])),r=VI(`0x03${n.slice(34)}0000000000000000000000000000`);return{conditionId:r,positionIds:[BigInt(`${r}00`).toString(),BigInt(`${r}01`).toString()]}}function Y8(e){if(e.length===0||e.length>n6)throw new E(`Combo legs must include 1 to ${n6} position IDs`);let t=e.map(n=>{let r=pO(n),o=r.toString(16).padStart(W8*2,"0"),s=Number.parseInt(o.slice(0,2),16),i=Number.parseInt(o.slice(-2),16);if(s!==1&&s!==2||i>1)throw new E("Combo legs must be binary or neg-risk YES/NO position IDs");return{value:r,conditionId:o.slice(0,-2)}});t.sort((n,r)=>n.value<r.value?-1:n.value>r.value?1:0);for(let n=1;n<t.length;n+=1){let r=t[n-1],o=t[n];if(r===void 0||o===void 0)throw new E("Invalid combo leg set");if(r.value===o.value)throw new E("Combo legs must not contain duplicate position IDs");if(r.conditionId===o.conditionId)throw new E("Combo legs must not contain both outcomes for the same condition")}return t.map(n=>n.value)}function nx(e){try{return(pO(e)&qie)===0n}catch{return!1}}function Hie(e){let t=pO(e).toString(16).padStart(W8*2,"0"),n=BigInt(`0x${t.slice(0,2)}`),r=Number.parseInt(t.slice(-2),16);if(n!==Bie&&n!==Mie&&n!==G8)throw new E("Position ID must use a supported protocol v2 module");if(r!==0&&r!==1)throw new E("Protocol v2 position ID must be a YES/NO position ID");return{conditionId:_h(`0x${t.slice(0,-2)}`),outcomeIndex:r}}function pO(e){let t=e.trim(),n;if(t.length===0)throw new E("Position ID must be a uint256 value");try{n=BigInt(t)}catch{throw new E("Position ID must be a uint256 value")}if(n<0n||n>Fie)throw new E("Position ID must be a uint256 value");return n}function Q8(e){let t=e*Number(rc),n=Math.round(t),r=Vie*Math.max(1,Math.abs(t)),o=Math.abs(t-n)<=r?n:Math.trunc(t);return BigInt(o)}function bN(e){let t=Math.round(e*Number(rc)),n=t/Number(rc);if(!Number.isSafeInteger(t)||Math.abs(e-n)>$ie)throw new E("has unsupported precision.");return BigInt(t)}function X8(e){return Number(e)/Number(rc)}function mO(e){return ge(Number.isInteger(e)&&e>=0&&e<=dN,`Decimal places must be an integer between 0 and ${dN}.`),10n**BigInt(dN-e)}function hO(e,t,n,r){ge(e>=0n,"Value must be non-negative."),ge(t>=0n,"Multiplier must be non-negative."),ge(n>0n,"Denominator must be positive.");let o=e*t,s=o/n;return r==="up"&&o%n!==0n?s+1n:s}function J8(e,t,n){let r=mO(t);return hO(e,1n,r,n)*r}function Z8(e){switch(e){case .1:return{amount:3,size:2};case .01:return{amount:4,size:2};case .005:return{amount:5,size:2};case .0025:return{amount:6,size:2};case .001:return{amount:5,size:2};case 1e-4:return{amount:6,size:2}}ge(!1,`Unsupported tick size: ${e}`)}function e5(e,t){let n=bN(e),r=bN(t);if(n<r||n>rc-r)throw new E(`must be between ${t} and ${1-t} for tick size ${t}.`);if(n%r!==0n)throw new E(`${e} must be a multiple of tick size ${t}.`);return n}function jie(e,t){return t?e.environment.contracts.negRiskExchange:e.environment.contracts.standardExchange}function Bf(e,t,n){return nx(t)?e.environment.contracts.exchangeV3:jie(e,n)}function wN(e,t,n,r){let o=mO(n);return hO(e,t,rc*o,r)*o}function zie(e,t,n,r){let o=mO(n);return hO(e,rc,t*o,r)*o}function Wie(e){let t=Z8(e.tickSize),n=J8(Q8(e.size),t.size,"down");return e.side===Ue.BUY?{offeredAmount:wN(n,e.price,t.amount,"down"),requestedAmount:n}:{offeredAmount:n,requestedAmount:wN(n,e.price,t.amount,"down")}}function Gie(e){let t=Z8(e.tickSize),n=J8(Q8(e.amount),t.size,"down"),r=e.protectPrice?"up":"down";return e.side===Ue.BUY?{offeredAmount:n,requestedAmount:zie(n,e.price,t.amount,r)}:{offeredAmount:n,requestedAmount:wN(n,e.price,t.amount,r)}}function x0(e,t,n,r){let o=e.get(t);if(o!==void 0&&(o.expiresAt===void 0||o.expiresAt>Date.now()))return o.promise;let s={promise:r()};return s.promise.then(()=>{s.expiresAt=Date.now()+n},()=>{e.get(t)===s&&e.delete(t)}),e.set(t,s),s.promise}function r6(e,t=vN){return{expiresAt:Date.now()+t,promise:Promise.resolve(e)}}function rx(e,t){return fO(e).resolveMarket(t)}function kN(e,t){return fO(e).fetchCurrentMarket(t)}function Yie(e,t){return fO(e).resolveBuilderTakerFeeRate(t)}function fO(e){let t=o6.get(e);if(t!==void 0)return t;let n=new Kie({fetchBuilderTakerFeeRate:async r=>(await sO(e,{builderCode:r})).taker,fetchMarket:r=>oO(e,{conditionId:r}),resolveCondition:r=>rO(e,{assetId:r})});return o6.set(e,n),n}async function Jie(e,t){let n=await Zie(e,{assetId:t.assetId,price:t.price}),r=Wie({price:n.price,side:t.side,size:t.size,tickSize:n.tickSize});return{assetId:t.assetId,builderCode:t.builderCode,chainId:e.environment.chainId,exchangeAddress:n.exchangeAddress,expiration:t.expiration??0,funderAddress:n.funderAddress,offeredAmount:r.offeredAmount,orderType:t.expiration===void 0?cn.GTC:cn.GTD,side:t.side,signer:n.signerAddress,requestedAmount:r.requestedAmount}}async function Zie(e,t){let n=await rx(e,t.assetId);try{return i6(e,t,n)}catch(r){if(!(r instanceof E))throw r;let o=await kN(e,t.assetId);return i6(e,t,o)}}function i6(e,t,n){let r=eae(t.price,n.tickSize);return{exchangeAddress:Bf(e,t.assetId,n.negRisk),funderAddress:e.account.wallet,price:r,signerAddress:e.account.signer,tickSize:n.tickSize}}function eae(e,t){try{return e5(e,t)}catch(n){throw n instanceof E?new E(`Price ${n.message}`,{cause:n}):n}}async function nae(e,t){let n=await rae(e,t,t.assetId),r=Gie({amount:n.resolvedAmount,price:n.price,protectPrice:r5(t),side:t.side,tickSize:n.tickSize});return{assetId:t.assetId,builderCode:t.builderCode,chainId:e.environment.chainId,exchangeAddress:n.exchangeAddress,expiration:0,funderAddress:n.funderAddress,offeredAmount:r.offeredAmount,orderType:t.orderType,side:t.side,signer:n.signerAddress,requestedAmount:r.requestedAmount}}async function rae(e,t,n){return r5(t)?oae(e,t,n):sae(e,t,n)}async function oae(e,t,n){let r=t.side===Ue.BUY?t.amount:t.shares;if(t.side===Ue.BUY&&t.maxSpend!==void 0){let{builderTakerFeeRate:s,market:i}=await o5(e,n,t.builderCode);try{return c6(e,t,n,r,s,t.maxSpend,i)}catch(a){if(!(a instanceof E))throw a;let l=await kN(e,n);return c6(e,t,n,r,s,t.maxSpend,l)}}let o=await rx(e,n);try{return u6(e,t,n,r,o)}catch(s){if(!(s instanceof E))throw s;let i=await kN(e,n);return u6(e,t,n,r,i)}}function c6(e,t,n,r,o,s,i){let a=n5(t,i.tickSize),l=X8(a);return{exchangeAddress:Bf(e,n,i.negRisk),funderAddress:e.account.wallet,price:a,resolvedAmount:s5({amount:r,builderTakerFeeRate:o,maxSpend:s,platformFeeExponent:i.feeInfo.exponent,platformFeeRate:i.feeInfo.rate,price:l}),signerAddress:e.account.signer,tickSize:i.tickSize}}function u6(e,t,n,r,o){let s=n5(t,o.tickSize);return{exchangeAddress:Bf(e,n,o.negRisk),funderAddress:e.account.wallet,price:s,resolvedAmount:r,signerAddress:e.account.signer,tickSize:o.tickSize}}async function sae(e,t,n){let r=t.side===Ue.BUY?t.amount:t.shares,o=t.side===Ue.BUY&&t.maxSpend!==void 0?o5(e,n,t.builderCode):void 0,[s,i]=await Promise.all([Hd(e,{assetId:n}),o]);if(s.assetId!==n)throw new C(`Order book returned asset ${s.assetId} for requested asset ${n}.`);let a=bN(Jk({amount:r,orderBook:s,orderType:t.orderType,side:t.side}));return{exchangeAddress:Bf(e,n,s.negRisk),funderAddress:e.account.wallet,price:a,resolvedAmount:iae(t,r,X8(a),i),signerAddress:e.account.signer,tickSize:s.tickSize}}function iae(e,t,n,r){return e.side!==Ue.BUY||e.maxSpend===void 0||r===void 0?t:s5({amount:t,builderTakerFeeRate:r.builderTakerFeeRate,maxSpend:e.maxSpend,platformFeeExponent:r.market.feeInfo.exponent,platformFeeRate:r.market.feeInfo.rate,price:n})}function n5(e,t){return e.side===Ue.BUY?(ge(e.maxPrice!==void 0,"Protected BUY market order requires maxPrice."),d6("maxPrice",e.maxPrice,t)):(ge(e.minPrice!==void 0,"Protected SELL market order requires minPrice."),d6("minPrice",e.minPrice,t))}function d6(e,t,n){try{return e5(t,n)}catch(r){throw r instanceof E?new E(`${e} ${r.message}`,{cause:r}):r}}function r5(e){return e.side===Ue.BUY&&e.maxPrice!==void 0||e.side===Ue.SELL&&e.minPrice!==void 0}async function o5(e,t,n){let[r,o]=await Promise.all([rx(e,t),Yie(e,n)]);return{builderTakerFeeRate:o,market:r}}function s5(e){let t=e.platformFeeRate*(e.price*(1-e.price))**e.platformFeeExponent,n=e.amount/e.price*t,r=e.amount+n+e.amount*e.builderTakerFeeRate;return e.maxSpend<=r?e.maxSpend/(1+t/e.price+e.builderTakerFeeRate):e.amount}function ox(e){let t=mae(e.domain,e.order);return e.order.signatureType!==Rr.POLY_1271?t:{domain:p5(e.domain),message:{chainId:e.domain.chainId,contents:t.message,name:aae,salt:xN,verifyingContract:e.order.signer,version:lae},primaryType:"TypedDataSign",types:{EIP712Domain:a5,Order:l5,TypedDataSign:pae}}}function sx(e){if(e.order.signatureType!==Rr.POLY_1271)return e.signature;let t=we.toHex(we.fromString(AN)),n=AN.length.toString(16).padStart(4,"0");return ZF(`0x${e.signature.slice(2)}${hae(e.domain).slice(2)}${fae(e.order).slice(2)}${t.slice(2)}${n}`)}function gO(e){return{chainId:e.chainId,exchange:e.exchange,protocolVersion:"3"}}function c5(e,t,n){return e===Ue.SELL?n.toString():((t*n+999999n)/1000000n).toString()}function u5(e,t,n){return e===Ue.SELL?(t*n/1000000n).toString():n.toString()}function d5(e){return{builder:e.builder??xN,maker:e.maker,makerAmount:BigInt(e.makerAmount),metadata:e.metadata??xN,salt:BigInt(e.salt),side:ix(e.side),signatureType:e.signatureType,signer:e.signer,takerAmount:BigInt(e.takerAmount),timestamp:BigInt(e.timestamp),tokenId:BigInt(e.tokenId)}}function mae(e,t){return{domain:p5(e),message:d5(t),primaryType:"Order",types:{EIP712Domain:a5,Order:l5}}}function p5(e){return{chainId:e.chainId,name:i5,verifyingContract:e.exchange,version:e.protocolVersion}}function hae(e){return zn(Je.keccak256(zt.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"address"}],[uae,dae,gae(e.protocolVersion),BigInt(e.chainId),e.exchange]),{as:"Hex"}))}function fae(e){let t=d5(e);return zn(Je.keccak256(zt.encode([{type:"bytes32"},{type:"uint256"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},{type:"uint8"},{type:"uint8"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"}],[cae,t.salt,t.maker,t.signer,t.tokenId,t.makerAmount,t.takerAmount,t.side,t.signatureType,t.timestamp,t.metadata,t.builder]),{as:"Hex"}))}function gae(e){return zn(Je.keccak256(we.fromString(e),{as:"Hex"}))}function ix(e){return e===0||e===1?e:e===Ue.BUY?0:1}function m5(e,t){let n=oc(t);return{builder:e.builderCode??p6,chainId:e.chainId,exchangeAddress:e.exchangeAddress,expiration:e.expiration,maker:n.maker,makerAmount:e.offeredAmount.toString(),metadata:p6,orderType:e.orderType,protocolVersion:nx(e.assetId)?"3":"2",salt:yae().toString(),side:e.side,signatureType:n.signatureType,signer:n.signer,takerAmount:e.requestedAmount.toString(),timestamp:Date.now().toString(),tokenId:e.assetId}}function h5(e,t){let{chainId:n,exchangeAddress:r,protocolVersion:o,...s}=e;return{...s,signature:t}}function yae(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)&(1n<<53n)-1n}function f5(e){return ox({domain:y5(e),order:e})}function g5(e,t){return sx({domain:y5(e),order:e,signature:t})}function y5(e){return{chainId:e.chainId,exchange:e.exchangeAddress,protocolVersion:e.protocolVersion}}function ax(e){return{kind:"signOrder",payload:e}}async function lx(e,t){let n=F(t,tae);return async function*(){let r=await nae(e,n),o=m5(r,e.account),s=rs(yield ax(f5(o)));return h5(o,N0(e.account,g5(o,s)))}.call(null)}async function cx(e,t){let n=F(t,Xie);return async function*(){let r=await Jie(e,n),o=m5(r,e.account),s=rs(yield ax(f5(o))),i=h5(o,N0(e.account,g5(o,s)));return n.postOnly===!0?{...i,postOnly:!0}:i}.call(null)}async function w5(e,t){return x5(e,lx(e,t))}async function k5(e,t){return x5(e,cx(e,t))}async function x5(e,t){let n=await t;return async function*(){let r=yield*n;return $d(e)(r)}.call(null)}function xae(e){return e.status===Qi.Confirmed||e.status===Qi.Failed}function m6(e){return e.status===Qi.Failed}async function dx(e,t,n){let{timeoutMs:r=wae}=F(n,kae),o=[...new Set(t.tradeIds)];if(o.length===0)return[...t.transactionsHashes];let s=new Map,i=Date.now()+r;for(;s.size<o.length;){let l=o.filter(u=>!s.has(u)),c=await Promise.all(l.map(u=>Tf(e,{id:u}).firstPage()));for(let u of c)for(let d of u.items)o.includes(d.id)&&xae(d)&&s.set(d.id,d);if(s.size===o.length)break;if(Date.now()>=i){let u=o.filter(d=>!s.has(d));throw new tt(`Timed out waiting for trades to settle: ${u.join(", ")}`)}await ns(bae)}let a=[...s.values()];if(a.every(m6))throw new en(`Every fill of order ${t.orderId} failed execution: ${o.join(", ")}`);return[...new Set(a.filter(l=>!m6(l)).map(l=>l.transactionHash))].map(l=>et.parse(l))}function A5(e,t){return e===Ue.BUY?sa.COLLATERAL:nx(t)?sa.CONDITIONAL_V2:sa.CONDITIONAL}async function Aae(e,t){let n=A5(t.side,t.assetId),{allowances:r}=await W0(e,t.side===Ue.BUY?{assetType:n}:{assetType:n,assetId:t.assetId});return Tae(r,t.spenderAddress)}function Tae(e,t){return Object.entries(e).find(([n])=>Wt(n,t))?.[1]??0n}function Mf(e,t){return lx(e,t).then(wn(e.signer))}function hx(e,t){return Mf(e,t).then(n=>T5(e,n))}function Ff(e,t){return cx(e,t).then(wn(e.signer))}function yx(e,t){return Ff(e,t).then(n=>T5(e,n))}async function T5(e,t){let n=$d(e);try{return await n(t)}catch(r){if(!Pae(r))throw r;let o=await Sae(e,t,n);if(o===void 0)throw r;return o}}async function Sae(e,t,n){return await Eae(e,t)?n(t):void 0}function Pae(e){return e instanceof O&&e.status===400&&e.message.includes("allowance is not enough")}async function Eae(e,t){let n=t.tokenId,r=await rx(e,n),o=Bf(e,n,r.negRisk),s=BigInt(t.makerAmount);return await Aae(e,{assetId:n,spenderAddress:o,side:t.side})>=s?!1:(await(t.side===Ue.BUY?await Nf(e,{amount:"max",spenderAddress:o,tokenAddress:e.environment.contracts.collateralToken}):await Of(e,{operatorAddress:o,tokenAddress:nx(n)?e.environment.contracts.positionManager:e.environment.contracts.conditionalTokens})).wait(),await ON(e,{assetType:A5(t.side,n),tokenId:t.side===Ue.SELL?n:void 0}),!0)}function Rae(e){let t=fo.getSignPayload(wO(e));return rs(rw.toHex(ad.sign({payload:t,privateKey:e.privateKey})))}function wO(e){let t={chainId:e.chainId,name:"Polymarket",version:"1"};return{domain:t,message:{data:Je.keccak256(sN(S5(e.op)),{as:"Hex"}),salt:BigInt(e.salt),ts:BigInt(e.timestamp)},primaryType:"Op",types:{EIP712Domain:fo.extractEip712DomainTypes(t),Op:[{name:"data",type:"bytes32"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}]}}}function S5(e){return Array.isArray(e)?e.filter(t=>t!==void 0).map(S5):e}function qf(){let[e]=crypto.getRandomValues(new Uint32Array(1));return ge(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}function h6(e,t){let[n,r=""]=e.split("."),[o,s=""]=t.split("."),i=Math.max(r.length,s.length),a=BigInt(`${n}${r.padEnd(i,"0")}`),l=BigInt(`${o}${s.padEnd(i,"0")}`);return a<l?e:t}async function wx(e,t){let n=F(t,_ae);return X(e.perps.get("/v1/info/builder",{params:ve(n,Ee())}).andThen(z(Jh)))}async function Nae(e,t,n){let r=F(n,P5);if(r.builderAddress===void 0)throw new E("A builder address is required when the session has no builder attribution.");let o=Oae(await t.fetchBuilderApprovals({builder:r.builderAddress}),r.builderAddress),s={...F({builder:r.builderAddress,maxFeeRate:r.maxFeeRate,approvalVersion:o},Cae),chainId:e.environment.chainId,salt:qf(),timestamp:Date.now()},i;try{i=await e.signer.signTypedData(Lae(s))}catch(a){throw ue.fromError(a,"Could not sign builder consent")}return X(e.perps.post("/v1/account/builder-approvals",{json:Dae(s,i)}).andThen(z(zw)))}function Oae(e,t){return(e.find(n=>n.builder.toLowerCase()===t.toLowerCase())?.approvalVersion??0)+1}function Lae(e){return wO({chainId:e.chainId,op:["approveBuilder",[e.builder,e.maxFeeRate,e.approvalVersion]],salt:e.salt,timestamp:e.timestamp})}function Dae(e,t){return{op:{type:"approveBuilder",args:{builder:e.builder,max_fee_rate:e.maxFeeRate,approval_version:e.approvalVersion}},salt:e.salt,sig:t,ts:e.timestamp}}function Uae(e,t){let n=f6(e.get("Poly-RateLimit-Remaining"),/^-?\d+$/),r=f6(e.get("Poly-RateLimit-Reset"),/^\d+$/),o=Bae(e.get("Poly-RateLimit-Tier")),s=e.get("Poly-RateLimit-Warning")?.trim().toLowerCase()==="true";if(!(n===void 0&&r===void 0&&o===void 0&&!s))return{...t===void 0?{}:{bucket:t},remaining:n,reset:r,tier:o,warning:s}}function f6(e,t){let n=e?.trim();if(n===void 0||!t.test(n))return;let r=Number(n);return Number.isSafeInteger(r)?r:void 0}function Bae(e){if(!(e===null||e.trim()===""))return e}function Kae(e,t){if(t===void 0)return new WebSocket(e);try{let n=Reflect.construct(WebSocket,[e,{headers:t}]);if(n instanceof WebSocket)return n}catch(n){throw new _("WebSocket headers require a header-capable WebSocket implementation.",{cause:n})}throw new _("WebSocket headers require a header-capable WebSocket implementation.")}function Yae(e,t){let n=Math.min(t.baseMs*2**e,t.maxMs);return Math.random()*n}function Qae(e,t,n){let r=new Set(n.seenKeys),o=e.filter(l=>!r.has(String(l.transferId)));if(!t)return{items:o,hasMore:!1};let s=e.at(-1);if(s===void 0)throw new C("Perps internal-transfer history reported more records without a continuation timestamp.");let i=Math.min(n.endTimestamp,s.createdTimestamp+1);if(i===n.endTimestamp&&o.length===0)throw new C("Perps internal-transfer history cannot continue within a full millisecond without skipping records.");let a=new Set(i===n.endTimestamp?n.seenKeys:[]);for(let l of e)l.createdTimestamp>=i-1&&a.add(String(l.transferId));return{items:o,hasMore:!0,nextCursor:btoa(JSON.stringify({...n,endTimestamp:i,seenKeys:Array.from(a)}))}}async function Zae(e){return await X(e.get("/v1/account/balances").andThen(z(R_)))}async function ele(e){return await X(e.get("/v1/account/portfolio").andThen(z(__)))}async function tle(e){return await X(e.get("/v1/account/stats").andThen(z(I_)))}async function nle(e){return await X(e.get("/v1/account/auto-cancel").andThen(z(k4)))}async function ole(e,t){let n=F(t,rle);return await X(e.get("/v1/account/config",{params:Xr(n)}).andThen(z(O_)))}async function ile(e,t){let n=F(t,sle);return await X(e.get("/v1/account/open-orders",{params:Xr(n)}).andThen(z(wC)))}async function cle(e,t){let n=F(t,lle);return await X(e.get("/v1/account/orders",{params:Xr(n)}).andThen(z(bC)))}function dle(e,t={}){let n=F(t,ule);return Fe(r=>e.get("/v1/account/fills",{params:Xr({startTimestamp:n.start,endTimestamp:n.end,sort:n.sort,cursor:r??n.cursor})}).andThen(z(kC)).map(o=>{let s=o.data.at(-1);return!o.more||s===void 0?{items:o.data,hasMore:!1}:{items:o.data,hasMore:!0,nextCursor:String(s.tradeId)}}),n.cursor)}function fle(e,t={}){let{cursor:n,params:r}=F(t,hle);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps funding payment params."),s={kind:"perpsFundingPayments",seenKeys:[],...r}):s=Io(o,TO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/funding",{params:Xr(l)}).andThen(z(C_)).map(u=>{let d=u.data.filter(p=>!c.has(`${p.instrumentId}:${p.timestamp}:${p.funding}`));return SO({getKey:p=>`${p.instrumentId}:${p.timestamp}:${p.funding}`,getTimestamp:p=>p.timestamp,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function wle(e,t={}){let{cursor:n,params:r}=F(t,ble);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps deposit params."),s={kind:"perpsDeposits",seenKeys:[],...r}):s=Io(o,TO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/deposits",{params:Xr(l)}).andThen(z(V_)).map(u=>{let d=u.data.filter(p=>!c.has(p.hash));return SO({getKey:p=>p.hash,getTimestamp:Kle,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Ale(e,t={}){let{cursor:n,params:r}=F(t,xle);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps withdrawal params."),s={kind:"perpsWithdrawals",seenKeys:[],...r}):s=Io(o,TO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/withdrawals",{params:Xr(l)}).andThen(z(z_)).map(u=>{let d=u.data.filter(p=>!c.has(String(p.withdrawalId)));return SO({getKey:p=>String(p.withdrawalId),getTimestamp:Yle,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Rle(e,t={}){let{cursor:n,params:r}=F(t,Ele);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps internal-transfer params."),s={kind:"perpsInternalTransfers",seenKeys:[],...r}):s=Io(o,Sle,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s;return e.get("/v1/account/internal-transfers",{params:Xr(l)}).andThen(z(K_)).map(c=>Qae(c.data,c.more,s))},n)}function Nle(e,t){let{cursor:n,params:r}=F(t,Cle);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps equity history params."),s={kind:"perpsEquityHistory",...r}):s=Io(o,C5,"Invalid Perps account pagination cursor");let{kind:i,...a}=s;return e.get("/v1/account/equity",{params:Xr(a)}).andThen(z(L_)).map(l=>{let c=l.data.at(-1),u=l.more&&c!==void 0&&c.timestamp<s.endTimestamp;return{items:l.data,hasMore:u,nextCursor:u?di({...s,startTimestamp:c.timestamp+O5(s.interval)}):void 0}})},n)}function Ule(e,t){let{cursor:n,params:r}=F(t,Dle);return Fe(o=>{let s;o===void 0?(ge(r!==void 0,"Expected initial Perps PnL history params."),s={kind:"perpsPnlHistory",...r}):s=Io(o,C5,"Invalid Perps account pagination cursor");let{kind:i,...a}=s;return e.get("/v1/account/pnl",{params:Xr(a)}).andThen(z(D_)).map(l=>{let c=l.data.at(-1),u=l.more&&c!==void 0&&c.timestamp<s.endTimestamp;return{items:l.data,hasMore:u,nextCursor:u?di({...s,startTimestamp:c.timestamp+O5(s.interval)}):void 0}})},n)}function Hle(e,t={}){let{cursor:n,params:r}=F(t,qle);return Fe(o=>{let s;o===void 0?ge(r!==void 0,"Expected initial Perps notifications params."):s=Io(o,Ble,"Invalid Perps account pagination cursor");let i=s===void 0?r?.sinceSeq:s.sinceSeq,a=s===void 0?r?.limit:s.limit;return e.get("/v1/account/notifications",{params:Xr({cursor:s?.cursor,limit:a,sinceSeq:i})}).andThen(z(uC)).map(l=>{let c=l.has_more&&l.next_cursor!==null;return{items:l.items,hasMore:c,nextCursor:c&&l.next_cursor!==null?di({kind:"perpsNotifications",cursor:l.next_cursor,limit:a,sinceSeq:i}):void 0}})},n)}async function $le(e){return(await X(e.get("/v1/account/notifications",{params:Xr({limit:1})}).andThen(z(dC)))).unread}async function Wle(e,t){let n=F(t,zle),r=await X(e.post("/v1/account/notifications/read",{json:n}).andThen(z(pC)));if(r.status==="err")throw new O(r.error??"Perps notifications read request was rejected.",{status:200})}function Gle(e){return btoa(JSON.stringify({ts:e.timestamp,id:e.id})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function xx(e,t){let n=Date.now(),{end:r,start:o,...s}=e;return{...s,endTimestamp:r??n,startTimestamp:o??n-t}}function N5(e){return{endTimestamp:e.end??Date.now(),interval:e.interval,startTimestamp:e.start}}function Xr(e){return ve(e,Ee())}function Kle(e){return e.confirmedTimestamp??e.createdTimestamp}function Yle(e){return e.confirmedTimestamp??e.createdTimestamp}function SO(e){let t=e.responseData.at(-1),n=e.items.at(-1),r=(n===void 0?void 0:e.getTimestamp(n))??(t===void 0?void 0:e.getTimestamp(t)),o=e.responseMore&&r!==void 0&&r>e.state.startTimestamp;if(!o)return{items:e.items,hasMore:o};let s=n===void 0?r-1:r,i=new Set(e.state.endTimestamp===s?e.state.seenKeys:[]);for(let a of e.items)e.getTimestamp(a)===s&&i.add(e.getKey(a));return{items:e.items,hasMore:o,nextCursor:di({...e.state,endTimestamp:s,seenKeys:Array.from(i)})}}function O5(e){switch(e){case"1h":return 3600*1e3;case"4h":return 14400*1e3;case"1d":return P0;case"1w":return 7*P0}ge(!1,`Unsupported Perps account history interval: ${String(e)}`)}async function Xle(e,t){let n=F(t,Qle);return(await X(e.get("/v1/account/builder-approvals",{params:ve(n,Ee())}).andThen(z(F_)))).data}function Zle(e,t){let n=F(t,L5);return Fe(r=>e.get("/v1/account/builder-earnings",{params:r===void 0?ve(n,{start:"start_timestamp",end:"end_timestamp",asOfSequence:"as_of_sequence"}):new URLSearchParams({cursor:r})}).andThen(z(H_)).map(o=>{if(!o.more)return{items:o.data,hasMore:!1};if(o.cursor===void 0||o.cursor===r)throw new C("Builder earnings pagination did not return a new cursor");return{items:o.data,hasMore:!0,nextCursor:o.cursor}}))}async function ece(e,t){let n=F(t,L5);return X(e.get("/v1/account/builder-earnings-summary",{params:ve(n,{start:"start_timestamp",end:"end_timestamp",asOfSequence:"as_of_sequence"})}).andThen(z($_)))}async function ice(e,t){let n=F(t,sce),r=e.builderAttribution;return await e.executeCommand({op:["createOrders",n.orders.map(o=>RO(o,r))],expiresAt:n.expiresAt},h.z.array(sf))}function cce(e){return e.takeProfit!==void 0||e.stopLoss!==void 0}async function uce(e,t){if(cce(t))return await dce(e,t);let n=F(t,lce),r=e.builderAttribution,[,o]=await e.executeCommandWithEvent({op:["createOrders",[RO(n,r)]],expiresAt:n.expiresAt},D5,B5(n.clientOrderId));return{order:o.payload}}async function dce(e,t){let n=F(t,ace),r=e.builderAttribution,o=[RO(n,r)],s=n.side===Ue.SELL;n.takeProfit!==void 0&&o.push(I0({buy:s,instrumentId:n.instrumentId,kind:ra.TakeProfit,quantity:n.quantity,builderAttribution:r,trigger:n.takeProfit})),n.stopLoss!==void 0&&o.push(I0({buy:s,instrumentId:n.instrumentId,kind:ra.StopLoss,quantity:n.quantity,builderAttribution:r,trigger:n.stopLoss}));let[i,a]=await e.executeCommandWithEvent({op:["createOrders",o,vd.Order],expiresAt:n.expiresAt},D5,B5(n.clientOrderId)),l=1,c={};return n.takeProfit!==void 0&&(c.takeProfit=R0(Qs(i[l++],"Expected Perps take-profit acknowledgement."))),n.stopLoss!==void 0&&(c.stopLoss=R0(Qs(i[l],"Expected Perps stop-loss acknowledgement."))),{order:a.payload,tpSl:c}}async function hce(e,t){let n=F(t,mce),r=e.builderAttribution,o=Bce(await e.fetchPortfolio(),n.instrumentId),s=[];n.takeProfit!==void 0&&s.push(I0({buy:o,instrumentId:n.instrumentId,kind:ra.TakeProfit,quantity:"0",builderAttribution:r,trigger:n.takeProfit})),n.stopLoss!==void 0&&s.push(I0({buy:o,instrumentId:n.instrumentId,kind:ra.StopLoss,quantity:"0",builderAttribution:r,trigger:n.stopLoss}));let i=await e.executeCommand({op:["createOrders",s,vd.Position],expiresAt:n.expiresAt},h.z.array(sf));for(let c of i)if(c.status==="err")throw new O(c.error,{status:200});let a=0,l={};return n.takeProfit!==void 0&&(l.takeProfit=R0(Qs(i[a++],"Expected Perps take-profit acknowledgement."))),n.stopLoss!==void 0&&(l.stopLoss=R0(Qs(i[a],"Expected Perps stop-loss acknowledgement."))),{tpSl:l}}async function wce(e,t){let n=F(t,bce),[r]=n.orderId!==void 0?await PN(e,{orderIds:[n.orderId],expiresAt:n.expiresAt,retry:n.retry,signal:n.signal}):await PN(e,{clientOrderIds:[n.clientOrderId],expiresAt:n.expiresAt,retry:n.retry,signal:n.signal});return Qs(r,"Expected Perps cancel order result.")}async function PN(e,t){let n=F(t,vce);return n.orderIds!==void 0?await g6(n.orderIds,n,async r=>await e.executeCommand({op:["cancelOrders",r],expiresAt:n.expiresAt},h.z.array(Kw))):await g6(n.clientOrderIds,n,async r=>await e.executeCommand({op:["cancelOrdersCOID",r],expiresAt:n.expiresAt},h.z.array(Kw)))}async function g6(e,t,n){let r=t.retry===!1?1:t.retry.maxAttempts,o=t.retry===!1?Number.POSITIVE_INFINITY:Math.min(Date.now()+t.retry.maxElapsedMs,t.expiresAt??Number.POSITIVE_INFINITY),s=new Array(e.length),i=e.map((l,c)=>({identifier:l,resultIndex:c})),a=0;for(Tce(t.signal);i.length>0;){if(a>0){let u=o-Date.now(),d=xce(a);if(u<=0||d>=u||!await Ace(d,t.signal)||t.signal?.aborted||Date.now()>=o)break}let l;try{l=await n(i.map(({identifier:d})=>d));let u=kce(l);if(u!==void 0)throw new O(u,{status:200});if(l.length!==i.length)throw new C("Perps cancel response did not include one result per requested order.")}catch(u){throw a===0?u:new Jw("Perps cancellation retry failed.",{cause:u,results:s.map(d=>Qs(d,"Expected a previous Perps cancel result.")),pendingIndexes:i.map(({resultIndex:d})=>d)})}a+=1;let c=[];for(let[u,d]of l.entries()){let p=Qs(i[u],"Expected a pending Perps cancellation.");s[p.resultIndex]=d,a<r&&d.status==="err"&&d.error===Sd.OrderInFlight&&c.push(p)}i=c}return s.map(l=>Qs(l,"Expected a final Perps cancel result."))}function kce(e){let[t]=e;if(!(e.length!==1||t?.status!=="err"||t.orderId!==void 0||t.clientOrderId!==void 0))return t.error}function xce(e){let t=Math.min(fce*2**(e-1),gce);return Math.random()*t}function Ace(e,t){if(t?.aborted)return Promise.resolve(!1);if(e<=0)return Promise.resolve(!0);if(t===void 0)return new Promise(r=>gn(()=>r(!0),e));let n=t;return new Promise(r=>{let o=gn(()=>{n.removeEventListener("abort",s),r(!0)},e);function s(){clearTimeout(o),r(!1)}n.addEventListener("abort",s,{once:!0})})}function Tce(e){if(e?.aborted)throw Xw.fromReason(e.reason)}async function Pce(e,t){let n=F(t,Sce),r=["cancelAll",n.instrumentId===void 0?[]:[n.instrumentId]];await e.executeDeleteCommand({path:"/v1/trade/orders/all",op:r,responseSchema:fC,expiresAt:n.expiresAt})}async function _ce(e,t,n){let r=F(n,Rce),o=["autoCancel",[r.cancelAt]],s=t(o,r.expiresAt);await X(e.patch("/v1/trade/auto-cancel",{json:{...s,op:_0(o)}}).andThen(z(nN)).mapErr(i=>i instanceof O&&i.message.startsWith(`${Ice} (`)?new lf("Auto-cancel daily trigger limit reached.",{cause:i}):i))}async function Nce(e,t,n){let r=F(n,Cce),o=["autoCancel",[0]],s=t(o,r.expiresAt);await X(e.patch("/v1/trade/auto-cancel",{json:{...s,op:_0(o)}}).andThen(z(nN)))}async function Lce(e,t){let n=F(t,Oce);return await e.executeCommand({op:["updateLeverage",[n.instrumentId,n.leverage,n.crossMargin]]},gC)}async function Uce(e,t){let n=F(t,Dce),r=n.amount,o=await e.executeCommand({op:["updateMargin",[n.instrumentId,r]]},of);if(o.status==="err")throw new O(o.error,{status:200})}function U5(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16));return Er.parse(Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""))}function B5(e){return t=>t.type==="order"&&t.payload.clientOrderId===e}function R0(e){if(e.status==="err")throw new O(e.error,{status:200});return{orderId:e.orderId}}function Bce(e,t){let n=e.positions.find(o=>o.instrumentId===t),r=n===void 0?0:Mce(n.size);if(r===0)throw new E(`No open Perps position for instrument ${t}.`);return r<0}function Mce(e){let t=e.trim(),n=t.replace(/^[+-]/,"").replace(".","");return/^0*$/.test(n)?0:t.startsWith("-")?-1:1}function RO(e,t){return[e.instrumentId,e.side===Ue.BUY,e.price===void 0?void 0:e.price,e.quantity,e.timeInForce,e.postOnly??!1,e.reduceOnly===!0?!0:void 0,e.clientOrderId,void 0,void 0,t===void 0?void 0:[t.builderAddress,t.feeRate]]}function I0(e){return[e.instrumentId,e.buy,e.trigger.limitPrice===void 0?void 0:e.trigger.limitPrice,e.quantity,void 0,!1,!0,void 0,[e.trigger.limitPrice===void 0?!0:void 0,e.trigger.triggerPrice,e.kind],void 0,e.builderAttribution==null?void 0:[e.builderAttribution.builderAddress,e.builderAttribution.feeRate]]}function _0(e){let[t,n,r]=e;switch(t){case"createOrders":return Hce({args:n.map(Fce),type:t},r);case"cancelOrders":case"cancelOrdersCOID":return{type:t,args:n};case"autoCancel":{let[o]=n;return{type:t,args:{time:o}}}case"cancelAll":{let[o]=n;return{type:t,args:o===void 0?{}:{iid:o}}}case"updateLeverage":{let[o,s,i]=n;return{type:t,args:{cross:i,iid:o,lev:s}}}case"updateMargin":{let[o,s]=n;return{type:t,args:{amt:s,iid:o}}}default:ge(!1,`Unsupported Perps command: ${String(t)}`)}}function Fce(e){let t={iid:e[0],buy:e[1],po:e[5],qty:e[3]};return e[4]!==void 0&&(t.tif=e[4]),e[6]&&(t.ro=e[6]),e[2]!==void 0&&(t.p=e[2]),e[7]!==void 0&&(t.c=e[7]),e[8]!==void 0&&(t.tr=qce(e[8])),e[10]!==void 0&&(t.builder={address:e[10][0],fee_rate:e[10][1]}),t}function qce(e){let t={tpsl:e[2],trp:e[1]};return e[0]!==void 0&&(t.market=e[0]),t}function Hce(e,t){return t!==void 0&&(e.grp=t),e}function Gce(e){let t,n;return{promise:new Promise((r,o)=>{t=r,n=o}),reject:n,resolve:t,schema:e}}function Kce(e){return Array.isArray(e)?!1:IO(e)!==void 0}function IO(e){if(Array.isArray(e)){for(let n of e){let r=IO(n);if(r!==void 0)return r}return}if(typeof e!="object"||e===null)return;let t=e;if(t.status==="err")return{error:typeof t.error=="string"?t.error:"Perps command failed."}}function Yce(){let[e]=globalThis.crypto.getRandomValues(new Uint32Array(1));return ge(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}async function Qce(e,t){let{label:n,...r}=t,o=await e.signTransfer(r);return e.submitTransfer({...r,signature:o,...n===void 0?{}:{label:n}})}async function Cx(e,t){let n=F(t,Xce);return X(e.perps.get("/v1/info/instruments",{params:ve(n,Ee())}).andThen(z(Q_)))}async function Ox(e,t){let n=F(t,Jce),[r]=await Hf(e,n);if(r===void 0)throw new C(`Perps ticker ${n.instrumentId} was not returned by the API`);return r}async function Hf(e,t){let n=F(t,Zce),r=ve(n,Ee()),[o,s]=await Promise.all([X(e.perps.get("/v1/info/tickers",{params:r}).andThen(z(X_))),X(e.perps.get("/v1/info/statistics",{params:r}).andThen(z(Z_)))]),i=new Map(s.map(a=>[a.instrumentId,a]));return o.map(a=>{let l=i.get(a.instrumentId);return{...a,openPrice:l?.openPrice,volume24h:l?.volume}})}async function Ux(e,t){let n=F(t,tue);return X(e.perps.get("/v1/info/book",{params:ve(n,Ee())}).andThen(z(tC)))}function Mx(e,t){let{cursor:n,params:r}=F(t,oue);return Fe(o=>{let s=o===void 0?fue(r):bue(o);return e.perps.get("/v1/info/klines",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,interval:s.interval,startTimestamp:s.startTimestamp},Ee())}).andThen(z(lC)).map(i=>{let a=i.data.at(-1),l=i.more&&a!==void 0;return{items:i.data,hasMore:l,nextCursor:l?di({...s,startTimestamp:a.timestamp+kue(s.interval)}):void 0}})},n)}function qx(e,t){let{cursor:n,params:r}=F(t,aue);return Fe(o=>{let s=o===void 0?gue(r):wue(o);return e.perps.get("/v1/info/funding",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},Ee())}).andThen(z(iC)).map(i=>{let a=i.data.at(-1),l=i.more&&a!==void 0&&a.timestamp>s.startTimestamp;return{items:i.data,hasMore:l,nextCursor:l?di({...s,endTimestamp:a.timestamp-1}):void 0}})},n)}function $x(e,t){let{cursor:n,params:r}=F(t,uue);return Fe(o=>{let s=o===void 0?yue(r):vue(o),i=new Set(s.seenTradeIds);return e.perps.get("/v1/info/trades",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},Ee())}).andThen(z(sC)).map(a=>{let l=a.data.filter(m=>!i.has(m.tradeId)),c=a.data.at(-1),u=l.at(-1),d=u?.timestamp??c?.timestamp,p=a.more&&d!==void 0&&d>s.startTimestamp;return{items:l,hasMore:p,nextCursor:p?di({...s,endTimestamp:u===void 0?d-1:d,seenTradeIds:u===void 0?[]:xue(s,l,u)}):void 0}})},n)}async function jx(e){return(await X(e.perps.get("/v1/info/fees").andThen(z(aC)))).feeSchedule}function hue(e){let t=Date.now();return{endTimestamp:e.end??t,instrumentId:e.instrumentId,interval:e.interval,startTimestamp:e.start??t-F5}}function H5(e){let t=Date.now();return{endTimestamp:e.end??t,instrumentId:e.instrumentId,startTimestamp:e.start??t-F5}}function fue(e){return ge(e!==void 0,"Expected initial Perps candles params."),{kind:"perpsCandles",...e}}function gue(e){return ge(e!==void 0,"Expected initial Perps funding params."),{kind:"perpsFundingHistory",...e}}function yue(e){return ge(e!==void 0,"Expected initial Perps trades params."),{kind:"perpsTrades",seenTradeIds:[],...e}}function bue(e){return Io(e,due,"Invalid Perps pagination cursor")}function wue(e){return Io(e,pue,"Invalid Perps pagination cursor")}function vue(e){return Io(e,mue,"Invalid Perps pagination cursor")}function kue(e){switch(e){case"1s":return 1e3;case"1m":return 60*1e3;case"5m":return 300*1e3;case"15m":return 900*1e3;case"1h":return 3600*1e3;case"4h":return 14400*1e3;case"1d":return 1440*60*1e3;case"1w":return 10080*60*1e3}ge(!1,`Unsupported Perps kline interval: ${String(e)}`)}function xue(e,t,n){let r=new Set(e.endTimestamp===n.timestamp?e.seenTradeIds:[]);for(let o of t)o.timestamp===n.timestamp&&r.add(o.tradeId);return Array.from(r)}async function Qx(e,t={}){let n=F(t,Rue),r="credentials"in n?await Bue(e,n.credentials):await Uue(e,n);return e.webSockets.perpsSession.connect(r,n.builderAttribution,Nae.bind(null,e),n.includeBuilderFills)}async function Xx(e,t){let n=F(t,_ue),r={type:"deleteProxy",args:{proxy:n.proxy}},o=["deleteProxy",[n.proxy]],s=qf(),i=Date.now(),a=await z5(e,{salt:s,signedOp:o,timestamp:i}),l=await X(e.perps.del("/v1/account/proxy",{json:{op:r,salt:s,sig:a,ts:i}}).andThen(z(M_)));if(l.status==="err")throw new O(l.error??"Perps credentials revocation was rejected.",{status:200})}async function _O(e,t){let n=F(t,Cue),{contracts:r}=e.environment,o=VN(r.perpsDepositContract,r.collateralToken,n.amount,e.account.signer);return async function*(){return e.account.walletType===Se.EOA?bn(yield Wue(Qn(e.environment.chainId,o))):yield*await Or(e,{calls:[o],metadata:n.metadata??`Deposit ${n.amount} of ${r.collateralToken} to Perps`})}.call(null)}function Jx(e,t){return _O(e,t).then(wn(e.signer))}async function Zx(e,t){let n=F(t,Nue),r=Math.floor(Date.now()/1e3),o=qf(),s={type:"withdraw",args:{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:n.amount.toString(),to:e.account.wallet}},i=await Fue(e,{amount:n.amount,salt:o,timestamp:r}),a=await X(e.perps.post("/v1/account/withdraw",{json:{op:s,salt:o,sig:i,ts:r}}).andThen(z(W_)));if(a.status==="err")throw new O(a.error??"Perps withdrawal was rejected.",{status:200});if(a.withdrawalId===void 0)throw new C("Perps withdrawal response did not include a withdrawal ID.");return a.withdrawalId}async function eA(e,t){jue(e);let n=F(t,Due);if(Wt(n.recipient,e.account.signer))throw new E("Perps collateral cannot be transferred to the authenticated account.");return Qce({signTransfer({account:r,token:o,amount:s,recipient:i,salt:a,timestamp:l}){return z5(e,{salt:a,signedOp:["internalTransfer",[r,o,s,i]],timestamp:l})},async submitTransfer(r){let o={op:{type:"internalTransfer",args:{account:r.account,token:r.token,amount:r.amount,to:r.recipient}},salt:r.salt,sig:r.signature,ts:r.timestamp};return r.label!==void 0&&(o.label=r.label),(await X(e.perps.post("/v1/account/internal-transfer",{json:o}).andThen(z(Y_)))).transferId}},{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:n.amount,recipient:n.recipient,label:n.label,salt:qf(),timestamp:Date.now()})}async function Uue(e,t){let n=$ue(),r=W5(n),o=e.account.signer,s=Date.now()+t.expiresIn,i=Date.now(),a=qf(),l={args:{expiry:s,owner:o,proxy:r},type:"createProxy"},c=await Mue(e,{expiresAt:s,proxy:r,salt:a,timestamp:i}),u={op:l,salt:a,sig:c,ts:i};t.label!==void 0&&(u.label=t.label);let d=await X(e.perps.post("/v1/account/proxy",{json:u}).andThen(z(B_))),p={expiresAt:s,privateKey:n,proxy:r,secret:d.secret};return j5(e,p)}async function Bue(e,t){return Vue(t),j5(e,t)}async function j5(e,t){let n=await X(e.perps.get("/v1/account/credentials",{headers:zue(t)}).andThen(z(U_)));if(!Wt(n.address,e.account.signer))throw new C("Perps credentials belong to a different signer account.");let r=n.keys.find(o=>Wt(o.proxy,t.proxy));if(r===void 0)throw new C("Perps credentials were not returned by the API.");if(r.expiresAt<=Date.now())throw new C("Perps credentials are expired.");return{...t,expiresAt:r.expiresAt}}async function Mue(e,t){try{return await e.signer.signTypedData(Hue({chainId:e.environment.chainId,...t}))}catch(n){throw ue.fromError(n,"Could not sign the Perps proxy credentials request")}}async function z5(e,t){try{return await e.signer.signTypedData(wO({chainId:e.environment.chainId,op:t.signedOp,salt:t.salt,timestamp:t.timestamp}))}catch(n){throw ue.fromError(n,"Could not sign the Perps operation request")}}async function Fue(e,t){try{return await e.signer.signTypedData(que({account:e.account.signer,chainId:e.environment.chainId,contract:e.environment.contracts.perpsDepositContract,token:e.environment.contracts.collateralToken,to:e.account.wallet,...t}))}catch(n){throw ue.fromError(n,"Could not sign the Perps withdrawal request")}}function que(e){let t={chainId:e.chainId,name:"Polymarket",verifyingContract:e.contract,version:"1"};return{domain:t,message:{account:e.account,amount:e.amount,fee:0n,salt:e.salt,token:e.token,to:e.to,ts:e.timestamp},primaryType:"Withdraw",types:{EIP712Domain:fo.extractEip712DomainTypes(t),Withdraw:[{name:"account",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"to",type:"address"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}]}}}function Hue(e){let t={chainId:e.chainId,name:"Polymarket",version:"1"};return{domain:t,message:{addr:e.proxy,exp:e.expiresAt,salt:e.salt,ts:e.timestamp},primaryType:"CreateProxy",types:{CreateProxy:[{name:"addr",type:"address"},{name:"exp",type:"uint64"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}],EIP712Domain:fo.extractEip712DomainTypes(t)}}}function $ue(){return JF(ad.randomPrivateKey(),"Generated invalid Perps proxy key.")}function W5(e){return Be(Qo.fromPublicKey(ad.getPublicKey({privateKey:e})))}function Vue(e){let t=W5(e.privateKey);if(!Wt(t,e.proxy))throw new E("Perps credentials private key does not match the proxy address.")}function jue(e){if(e.account.signerType!=="OWNER")throw new E("Perps collateral transfers must be signed by the account owner.")}function zue(e){return{"POLYMARKET-PROXY":e.proxy,"POLYMARKET-SECRET":e.secret}}function Wue(e){return{kind:"sendPerpsDepositTransaction",request:e}}function $f(e,t){let{cursor:n,pageSize:r,window:o,...s}=F(t,Gue);return Fe(i=>nn(()=>e.data.get("/v2/positions",{params:tn({...s,...o,limit:r,cursor:i})})).andThen(z(U$)),n)}function Vf(e,t){let{cursor:n,pageSize:r,...o}=F(t,Que);return Fe(s=>nn(()=>e.data.get("/v2/positions/combos",{params:tn({...o,limit:r,cursor:s})})).andThen(z(H$)),n)}async function jf(e,t){let{conditionIds:n,...r}=F(t,Xue);return X(nn(()=>e.data.get("/v2/value",{params:tn({...r,condition:n})})).andThen(z(B$)))}async function zf(e,t){let n=F(t,Jue);return X(nn(()=>e.data.get("/v2/user-stats",{params:tn(n)})).andThen(z(M$)))}async function Wf(e,t){let n=F(t,Zue);return X(nn(()=>e.data.get("/v2/user-pnl",{params:tn(n)})).andThen(z(F$)))}async function Gf(e,t){let{window:n,...r}=F(t,ede);return X(nn(()=>e.data.get("/v2/user-volume",{params:tn({...r,...n})})).andThen(z(q$)))}async function Kf(e,t){let n=F(t,tde);return X(e.data.get("/v1/accounting/snapshot",{params:toe(n)}).andThen(Ire))}function nde(e,t){if(!Gr(e.conditionId))throw new C(`Missing condition ID for ${t}`);if(!Gr(e.version))throw new C(`Missing market version for ${t}`);let n=e.outcomes.yes.tokenId,r=e.outcomes.no.tokenId,o=e.outcomes.yes.positionId,s=e.outcomes.no.positionId;if(e.version===ta.V2){if(Gr(o)!==Gr(s))throw new C(`Incomplete market position IDs for ${t}`);if(!Gr(o)||!Gr(s))throw new C(`Missing market position IDs for ${t}`);return{marketId:e.id,conditionId:e.conditionId,protocol:"v2",outcomeIds:[o,s]}}if(Gr(n)!==Gr(r))throw new C(`Incomplete market token IDs for ${t}`);if(Gr(n)&&Gr(r)){if(!Gr(e.state.negRisk))throw new C(`Missing negative-risk flag for ${t}`);return{marketId:e.id,conditionId:e.conditionId,protocol:"ctf",negRisk:e.state.negRisk,outcomeIds:[n,r]}}throw new C(`Missing market token IDs for ${t}`)}async function cA(e,t){let n=F(t,G5),r=await DO(e,{conditionId:n.conditionId}),o=r.protocol==="ctf"?jN(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId,n.amount):cv(e.environment.contracts.protocolV2Router,r.conditionId,n.amount);return async function*(){return e.account.walletType===Se.EOA?bn(yield EN(Qn(e.environment.chainId,o))):yield*await Or(e,{calls:[o],metadata:n.metadata??`Split ${n.amount} positions for market ${r.marketId} (condition ${r.conditionId})`})}.call(null)}async function uA(e,t){let n=F(t,Y5),r=Y8(n.legs),o=dv(e.environment.contracts.combinatorialModule,r),s=K8(r),i=cv(e.environment.contracts.protocolV2Router,s.conditionId,n.amount);return async function*(){return e.account.walletType===Se.EOA?(await bn(yield EN(Qn(e.environment.chainId,o))).wait(),bn(yield EN(Qn(e.environment.chainId,i)))):yield*await Or(e,{calls:[o,i],metadata:n.metadata??`Split ${n.amount} combo positions for condition ${s.conditionId}`})}.call(null)}async function CO(e,t){let n=F(t,rde);return n.legs!==void 0?uA(e,n):cA(e,n)}function J5(e,t){return cA(e,t).then(wn(e.signer))}function eV(e,t){return uA(e,t).then(wn(e.signer))}function dA(e,t){return CO(e,t).then(wn(e.signer))}async function mA(e,t){let n=F(t,tV),r=await DO(e,{conditionId:n.conditionId}),o=Rf(await e.rpc.ethCall(Ef(r.positionErc1155Address,e.account.wallet,r.outcomeIds))),s=fV(r.conditionId,o,n.amount),i=r.protocol==="ctf"?zN(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId,s):uv(e.environment.contracts.protocolV2Router,r.conditionId,s);return async function*(){return e.account.walletType===Se.EOA?bn(yield RN(Qn(e.environment.chainId,i))):yield*await Or(e,{calls:[i],metadata:n.metadata??`Merge ${s} positions for market ${r.marketId} (condition ${r.conditionId})`})}.call(null)}async function hA(e,t){let n=F(t,rV),r=Y8(n.legs),o=dv(e.environment.contracts.combinatorialModule,r),s=K8(r),i=Rf(await e.rpc.ethCall(Ef(e.environment.contracts.positionManager,e.account.wallet,s.positionIds))),a=fV(s.conditionId,i,n.amount),l=uv(e.environment.contracts.protocolV2Router,s.conditionId,a);return async function*(){return e.account.walletType===Se.EOA?(await bn(yield RN(Qn(e.environment.chainId,o))).wait(),bn(yield RN(Qn(e.environment.chainId,l)))):yield*await Or(e,{calls:[o,l],metadata:n.metadata??`Merge ${a} combo positions for condition ${s.conditionId}`})}.call(null)}async function NO(e,t){let n=F(t,ode);return n.legs!==void 0?hA(e,n):mA(e,n)}function iV(e,t){return mA(e,t).then(wn(e.signer))}function lV(e,t){return hA(e,t).then(wn(e.signer))}function fA(e,t){return NO(e,t).then(wn(e.signer))}async function OO(e,t){let n=F(t,sde),r=await DO(e,n.conditionId!==void 0?{conditionId:n.conditionId,closed:!0}:{marketId:n.marketId,closed:!0}),o=await cde(e,r);return async function*(){return e.account.walletType===Se.EOA?yield*ade(e,o):yield*await Or(e,{calls:o,metadata:n.metadata??`Redeem positions for market ${r.marketId} (condition ${r.conditionId})`})}.call(null)}async function yA(e,t){let n=F(t,pV),r=Hie(n.positionId),o=qN(await e.rpc.ethCall(FN(e.environment.contracts.positionManager,e.account.wallet,n.positionId)));if(o===0n)throw new E("Position has no balance to redeem");let s=wf(e.environment.contracts.protocolV2Router,r.conditionId,r.outcomeIndex,o);return async function*(){return e.account.walletType===Se.EOA?bn(yield IN(Qn(e.environment.chainId,s))):yield*await Or(e,{calls:[s],metadata:n.metadata??`Redeem position ${n.positionId}`})}.call(null)}function hV(e,t){return yA(e,t)}async function LO(e,t){let n=F(t,ide);return n.positionId!==void 0?yA(e,n):OO(e,n)}function wA(e,t){return LO(e,t).then(wn(e.signer))}function EN(e){return{kind:"sendSplitPositionTransaction",request:e}}function RN(e){return{kind:"sendMergePositionsTransaction",request:e}}function IN(e){return{kind:"sendRedeemPositionsTransaction",request:e}}async function*ade(e,t){let[n,...r]=t;ge(n!==void 0,"Expected at least one redemption call");let o=n;for(let s of r)await bn(yield IN(Qn(e.environment.chainId,o))).wait(),o=s;return bn(yield IN(Qn(e.environment.chainId,o)))}async function DO(e,t){let n=t.conditionId!==void 0?`condition ${t.conditionId}`:`market ${t.marketId}`,r=await Uf(e,t.conditionId!==void 0?{conditionIds:[t.conditionId],closed:t.closed,pageSize:1}:{ids:[lde(t.marketId)],closed:t.closed,pageSize:1}).firstPage(),[o]=r.items;if(o===void 0)throw new E(`No market found for ${n}`);let s=nde(o,n);return s.protocol==="v2"?{...s,positionErc1155Address:e.environment.contracts.positionManager}:{...s,adapterAddress:s.negRisk?e.environment.contracts.negRiskCollateralAdapter:e.environment.contracts.collateralAdapter,positionErc1155Address:s.negRisk?e.environment.contracts.negRiskAdapter:e.environment.contracts.conditionalTokens}}function lde(e){let t=Number(e);if(!Number.isInteger(t))throw new E(`Market ID must be an integer, received ${e}`);return t}async function cde(e,t){if(t.protocol==="ctf")return[WN(t.adapterAddress,e.environment.contracts.collateralToken,t.conditionId)];let n=Rf(await e.rpc.ethCall(Ef(t.positionErc1155Address,e.account.wallet,t.outcomeIds)));if(n.length!==2)throw new C("Expected two position balances");let[r,o]=n;ge(r!==void 0,"Expected YES position balance"),ge(o!==void 0,"Expected NO position balance");let s=[];if(r>0n&&s.push(wf(e.environment.contracts.protocolV2Router,t.conditionId,0,r)),o>0n&&s.push(wf(e.environment.contracts.protocolV2Router,t.conditionId,1,o)),s.length===0)throw new E(`Market positions have no balance to redeem for condition ${t.conditionId}`);return s}function fV(e,t,n){let r=ude(t);if(r===0n)throw new E(`You have no complementary positions to merge for condition ${e}`);if(n==="max")return r;if(n>r)throw new E(`Requested merge amount ${n} exceeds the maximum mergeable amount ${r} for condition ${e}`);return n}function ude(e){if(e.length!==2)throw new C("Expected two position balances");let[t,n]=e;return ge(t!==void 0,"Expected YES position balance"),ge(n!==void 0,"Expected NO position balance"),t<n?t:n}async function kA(e,t){let n=F(t,dde);return X(e.gamma.get("/public-profile",{params:ve(n,Ee())}).andThen(z(K3)).orElse(r=>r instanceof O&&r.status===404?go(null):Sr(r)))}async function PA(e){return Yf(e),e.webSockets.rfqQuoter.connect()}function BO(e){return e instanceof O?new ms(e.message,{cause:e,code:gV(e.code),status:e.status}):e}function gV(e){return e!==void 0&&wde.has(e)?e:li.RequestFailed}function yV(e){if(!e.hasBuilderApiKey)throw new E("Combo RFQ requests require a Builder API Key in the client configuration, via builderApiKey(...) or remoteBuilderSigning(...).")}function vde(e,t){return BigInt(e)*1000000n+BigInt(t.padEnd(6,"0"))}async function RA(e,t){Yf(e);let n=F(t,kde);yV(e);let r=oc(e.account),o={direction:n.direction===Ue.BUY?Nn.Buy:Nn.Sell,leg_position_ids:n.legPositionIds,maker_address:r.maker,requested_size:n.direction===Ue.BUY?{unit:Qr.Notional,value_e6:n.amount}:{unit:Qr.Shares,value_e6:n.size},side:Eo.Yes,signature_type:r.signatureType,signer_address:r.signer},s=await X(e.builderGateway.post(UO,{json:o,timeout:pde}).andThen(z(g4)).mapErr(BO));if("quote"in s){xde(s,o);let i=s.request.direction===Nn.Buy?Ue.BUY:Ue.SELL,a={blendedPrice:s.quote.blendedPrice,builderCode:s.builderCode,expiresAt:s.expiresAt,makerAmount:s.quote.makerAmount,positionId:s.request.yesPositionId,quoteId:s.quote.quoteId,rfqId:s.rfqId,takerAmount:s.quote.takerAmount,totalRequired:s.quote.totalRequired};if(i===Ue.SELL){if(s.quote.netReceive===void 0)throw new C(`SELL quote for RFQ ${s.rfqId} omitted net sell proceeds.`);return{quote:{...a,direction:i,netReceive:s.quote.netReceive},rfqId:s.rfqId}}return{quote:{...a,direction:i},rfqId:s.rfqId}}return Ade(s)}function xde(e,t){let n=e.request,r=[];if(n.rfqId!==e.rfqId&&r.push("rfq_id"),n.direction!==t.direction&&r.push("direction"),n.side!==t.side&&r.push("side"),(n.legPositionIds.length!==t.leg_position_ids.length||n.legPositionIds.some((o,s)=>o!==t.leg_position_ids[s]))&&r.push("leg_position_ids"),(n.requestedSize.unit!==t.requested_size.unit||n.requestedSize.valueE6!==t.requested_size.value_e6)&&r.push("requested_size"),r.length>0)throw new C(`Builder RFQ response did not echo the submitted ${r.join(", ")}.`)}function Ade(e){switch(e.error?.code){case Cr.NoQuotes:return{quote:null,reason:ci.NoQuotes,rfqId:e.rfqId};case Cr.SizeTooLarge:return{quote:null,reason:ci.SizeTooLarge,rfqId:e.rfqId};default:throw new ms(e.error?.message??"The combo quote request failed.",{code:gV(e.error?.code),status:200,...e.error===void 0?{}:{cause:e.error}})}}async function _A(e,t){Yf(e);let n=F(t,Sde);yV(e);let r=gO({chainId:e.environment.chainId,exchange:e.environment.contracts.exchangeV3}),o=Rde(e,n),s=await _de(e,r,o),i={quote_id:n.quoteId,signed_order:s};function a(){return e.builderGateway.post(`${UO}/${encodeURIComponent(n.rfqId)}/accept`,{json:i,timeout:mde}).andThen(z(eN))}let l=await a();if(l.isErr()&&(l.error instanceof _||l.error instanceof C)&&(l=await a()),l.isErr()){let p=Pde(n.rfqId,l.error);if(p!==void 0)return p;throw BO(l.error)}let c=l.value,u=l.value.takerOrderHash,d=Date.now()+hde;for(;c.status===mn.AwaitingMakerConfirmation;){if(Date.now()>=d)throw new tt(`Timed out waiting for the acceptance outcome of RFQ ${n.rfqId}.`);await ns(fde),c=await LA(e,{rfqId:n.rfqId})}return c.status===mn.Failed||c.status===mn.Expired||c.status===mn.Canceled?{reason:Ede(c.status,c.error?.code),rfqId:c.rfqId,status:"failed",...c.error===void 0?{}:{error:c.error}}:{rfqId:c.rfqId,status:"executing",...u===void 0?{}:{takerOrderHash:u}}}function Pde(e,t){if(t instanceof O&&t.code===Cr.ExpiredRfq)return{error:{code:Cr.ExpiredRfq,message:t.message},reason:Ro.AcceptanceWindowExpired,rfqId:e,status:"failed"}}function Ede(e,t){return e===mn.Expired||t===Cr.ExpiredRfq?Ro.AcceptanceWindowExpired:t===Cr.MakerDeclined?Ro.MakerDeclined:Ro.ExecutionFailed}function Rde(e,t){let n=oc(e.account);return{builder:t.builderCode,maker:n.maker,makerAmount:t.makerAmount,metadata:bde,salt:Ide().toString(),side:ix(t.direction),signatureType:n.signatureType,signer:n.signer,takerAmount:t.takerAmount,timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.positionId}}function Ide(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)}async function _de(e,t,n){let r;try{r=await e.signer.signTypedData(ox({domain:t,order:n}))}catch(o){throw o instanceof bt?o:ue.fromError(o,"Could not sign the combo quote acceptance order.")}return{...n,signature:sx({domain:t,order:n,signature:r})}}async function NA(e,t){Yf(e);let n=F(t,Cde),r=n.timeoutMs??gde,o=n.pollingIntervalMs??yde,s=Date.now()+r;for(;;){let i=await LA(e,{rfqId:n.rfqId});if(i.status===mn.Filled||i.status===us.Confirmed){if(i.txHash===void 0)throw new C(`RFQ ${i.rfqId} reached ${i.status} without a transaction hash.`);return{rfqId:i.rfqId,status:mn.Filled,txHash:i.txHash}}if(i.status===mn.Failed||i.status===mn.Expired||i.status===mn.Canceled)return{rfqId:i.rfqId,status:i.status,...i.error===void 0?{}:{error:i.error}};if(Date.now()>=s)throw new tt(`Timed out after ${r}ms waiting for RFQ ${n.rfqId} to reach a terminal state.`);await ns(o)}}function LA(e,t){Yf(e);let n=F(t,Nde);return X(e.builderGateway.get(`${UO}/${encodeURIComponent(n.rfqId)}`).andThen(z(eN)).mapErr(BO))}function Yf(e){if(e.account.signerType==="SESSION_KEY")throw new E("Combos is not supported with Session Keys")}function UA(e,t){let{cursor:n,pageSize:r,...o}=F(t,Ode);return Fe(s=>{let i=Md(s,r,{maxOffset:b6});return e.gamma.get("/public-search",{params:ve({...o,limitPerType:i.pageSize,page:i.offset},Ee({excludeTagIds:"exclude_tag_id"}))}).andThen(z(Y3)).map(a=>({items:Lde(a),hasMore:a.pagination?.hasMore??!1,limitReached:(a.pagination?.hasMore??!1)&&i.offset+1>b6,totalCount:a.pagination?.totalResults??void 0,nextCursor:a.pagination?.hasMore?aa({offset:i.offset+1,pageSize:i.pageSize}):void 0}))},n??aa({offset:1,pageSize:r}),{events:[],profiles:[],tags:[]})}function Lde(e){return{events:e.events??[],profiles:e.profiles??[],tags:e.tags??[]}}function MA(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,Dde);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/series",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(z(X3)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?aa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function qA(e,t){let n=F(t,Ude);return X(e.gamma.get(`series/${n.id}`,{params:ve({locale:n.locale},Ee())}).andThen(z(UC)))}function bV(e){if(e.kind==="authorization"?e.status===Od.FAILED||e.status===Od.SUPERSEDED||e.status===Od.REPAIR_REQUIRED:e.status===f0.FAILED)throw new en(`Session-key ${e.kind} reached terminal status ${e.status}`)}async function Wd(e){MO(e);let t=await X(e.secureClob.get("/v1/user/session-signers").andThen(z(z3)));if(!Wt(t.wallet,e.account.wallet))throw new C(`Session-key response wallet ${t.wallet} does not match authenticated wallet ${e.account.wallet}`);return t.signers.map(n=>({address:Be(n.address.toLowerCase()),scopes:n.scopes,validUntil:n.validUntil}))}async function VA(e,t){if(MO(e),!e.hasBuilderApiKey)throw new E("Session-key authorization requires builder API-key authentication.");let n=F(t,Fde),r=Math.floor(Date.now()/1e3)+Mde,o=await wn(e.signer)(qd(e,[HN(e.account.wallet,n.address,BigInt(r))])),s={deadline:o.depositWalletParams.deadline,nonce:o.nonce,scopes:n.scopes,sessionSignerAddress:n.address,signature:o.signature,validUntil:`${r}`,walletAddress:e.account.wallet},i=await X(e.relayer.post("/v1/session-signers/authorizations",{headers:{"Idempotency-Key":n.idempotencyKey??globalThis.crypto.randomUUID()},json:s,timeout:wV}).andThen(z(s4)));bV({kind:"authorization",status:i.status});let a=await new Cf(e,i).wait();return{sessionKey:await $de(e,{address:n.address,scopes:n.scopes,validUntil:r}),transaction:a}}async function zA(e,t){if(MO(e),!e.supportsGasless)throw new E("Session-key revocation requires API-key authentication that supports gasless transactions.");let n=F(t,qde),r=await wn(e.signer)(qd(e,[$N(e.account.wallet,n.address)])),o={deadline:r.depositWalletParams.deadline,nonce:r.nonce,sessionSignerAddress:n.address,signature:r.signature,walletAddress:e.account.wallet},s=await X(e.relayer.post("/v1/session-signers/revocations",{headers:{"Idempotency-Key":n.idempotencyKey??globalThis.crypto.randomUUID()},json:o,timeout:wV}).andThen(z(i4)));bV({kind:"revocation",status:s.status}),await Hde(e,n.address)}async function Hde(e,t){for(let n=0;n<e.environment.relayerMaxPolls;n+=1){if(!(await Wd(e)).some(r=>Wt(r.address,t)))return;await ns(e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for session key ${t} to be revoked`)}async function $de(e,t){for(let n=0;n<e.environment.relayerMaxPolls;n+=1){let r=(await Wd(e)).find(o=>Wt(o.address,t.address)&&o.validUntil===t.validUntil&&Vde(o.scopes,t.scopes));if(r!==void 0)return r;await ns(e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for session key ${t.address} to become active`)}function Vde(e,t){let n=new Set(t);return new Set(e).size===n.size&&e.every(r=>n.has(r))}function MO(e){if(e.account.walletType!==Se.DEPOSIT_WALLET)throw new E("Session keys can only be managed for a Deposit Wallet.");if(e.account.signerType!=="OWNER")throw new E("Session keys can only be managed by the Deposit Wallet owner.")}async function GA(e){return X(e.gamma.get("/sports").andThen(z(g_)))}async function YA(e){return X(e.gamma.get("/sports/market-types").andThen(z(y_)))}function Wde(e){return F(e,zde)}async function Qf(e,t){let n=t.map(i=>{switch(F(i,Gde),i.topic){case"prices.crypto":case"prices.crypto.twap":case"prices.equity":if(!e.isSecureClient())throw new E("This subscription requires a secure client.");return Wde(i);case"prices.crypto.chainlink.twap":F(i,Kde);break;case"market":F(i,Yde);break}return i}),r=await Promise.allSettled(n.map(async i=>Qde(e,i))),o=r.flatMap(i=>i.status==="fulfilled"?[i.value]:[]),s=r.find(i=>i.status==="rejected");if(s?.status==="rejected")throw await Promise.allSettled(o.map(i=>i.close())),s.reason;return Xde(o)}function Qde(e,t){switch(t.topic){case"market":return e.webSockets.clobMarket.subscribe(t);case"sports":return e.webSockets.sports.subscribe(t);case"prices.crypto":case"prices.crypto.twap":case"prices.equity":if(!e.isSecureClient())throw new E("This subscription requires a secure client.");return e.webSockets.realtime.subscribe(t);case"comments":case"prices.crypto.binance":case"prices.crypto.chainlink":case"prices.crypto.chainlink.twap":case"prices.equity.pyth":return e.webSockets.rtds.subscribe(t);case"perps.trades":case"perps.bbo":case"perps.book":case"perps.candles":case"perps.tickers":case"perps.statistics":return e.webSockets.perpsSubscriptions.subscribe(t);case"user":return ge(e.isSecureClient(),"A 'user' subscription requires a secure client instance."),e.webSockets.clobUser.subscribe(t)}}function Xde(e){let t;async function n(){t===void 0&&(t=Promise.all(e.map(o=>o.close())).then(()=>{})),await t}let r=V4(...e);return{close:n,[Symbol.asyncIterator](){return r[Symbol.asyncIterator]()}}}function JA(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,Jde);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/tags",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(z(Q3)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?aa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function eT(e,t){let n=F(t,Zde);return"id"in n?X(e.gamma.get(`tags/${n.id}`,{params:ve({includeTemplate:n.includeTemplate,locale:n.locale},Ee())}).andThen(z(Id))):X(e.gamma.get(`tags/slug/${n.slug}`,{params:ve({locale:n.locale},Ee())}).andThen(z(Id)))}async function nT(e,t){if("id"in t){let r=F(t,epe);return X(e.gamma.get(`tags/${r.id}/related-tags`,{params:ve({omitEmpty:r.omitEmpty,status:r.status},Ee())}).andThen(z(LC)))}let n=F(t,tpe);return X(e.gamma.get(`tags/slug/${n.slug}/related-tags`).andThen(z(LC)))}async function oT(e,t){if("id"in t){let r=F(t,npe);return X(e.gamma.get(`tags/${r.id}/related-tags/tags`,{params:ve({locale:r.locale,omitEmpty:r.omitEmpty,status:r.status},Ee())}).andThen(z(DC)))}let n=F(t,rpe);return X(e.gamma.get(`tags/slug/${n.slug}/related-tags/tags`,{params:ve({locale:n.locale,omitEmpty:n.omitEmpty,status:n.status},Ee())}).andThen(z(DC)))}function iT(e,t={}){let{cursor:n,pageSize:r,...o}=F(t,ope);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/teams",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee({providerId:"provider_id"}))}).andThen(z(f_)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?aa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function FO(e,t){let n=F(t,spe);return async function*(){return e.account.walletType===Se.EOA?bn(yield ipe(Qn(e.environment.chainId,S0(n.tokenAddress,n.recipientAddress,n.amount)))):yield*await Or(e,{calls:[S0(n.tokenAddress,n.recipientAddress,n.amount)],metadata:n.metadata??`Transfer ${n.amount} of ${n.tokenAddress} to ${n.recipientAddress}`})}.call(null)}function lT(e,t){return FO(e,t).then(wn(e.signer))}function ipe(e){return{kind:"sendErc20TransferTransaction",request:e}}var h,Ot,x6,Ere,_N,CN,Ore,Lre,Ure,qre,Hre,$re,Vre,jre,zre,Wre,Gre,C6,gf,L0,N6,D0,ooe,soe,B0,ioe,F0,aoe,loe,H0,$0,coe,j0,L6,uoe,D6,doe,U6,poe,G0,moe,Y0,B6,X0,Z0,hoe,tv,rv,foe,sv,goe,av,yoe,lv,boe,woe,voe,LN,koe,M6,xoe,Aoe,Toe,Soe,Poe,F6,q6,H6,Eoe,Roe,Ioe,_oe,Coe,Noe,Ooe,Loe,Doe,$6,Uoe,lr,V6,j6,z6,W6,G6,K6,Y6,Q6,X6,J6,Z6,zoe,Woe,Goe,Koe,Yoe,Qoe,Xoe,Joe,t8,Zoe,ese,n8,ur,K4,r8,nse,rse,o8,c8,Cf,pse,u8,bv,mse,d8,wv,p8,hse,vv,kv,g8,y8,b8,w8,v8,k8,A8,S8,gse,yse,Pv,bse,Rv,wse,_v,vse,R8,kse,_8,xse,N8,Ase,O8,Tse,L8,Sse,Nv,Pse,Lv,Ese,Uv,Rse,Bv,Ise,Fv,_se,Hv,Cse,Vv,Nse,zv,Ose,Gv,Lse,Yv,D8,Jv,Use,Y4,uN,U8,ek,aO,lO,M8,Mse,Fse,qse,nk,Hse,ok,ik,Vse,jse,zse,lk,uk,pk,Gse,Kse,Yse,hk,Qse,gk,eie,bk,tie,vk,cO,nie,xk,rie,Tk,oie,Sk,sie,q8,iie,aie,lie,cie,uie,die,Rk,pie,Ik,Ck,Ok,mie,Dk,hie,fie,yN,H8,$8,gie,yie,bie,wie,Bk,vie,Fk,Sie,Pie,Eie,Rie,Hk,Vk,zk,Gk,kf,xf,V8,e6,t6,Iie,Qk,Oie,Lie,j8,Die,Zk,ex,W8,Bie,Mie,G8,n6,Fie,qie,rc,$ie,dN,Vie,pN,vN,Kie,o6,Qie,s6,Xie,t5,a6,l6,tae,i5,aae,lae,xN,AN,cae,uae,dae,a5,l5,pae,p6,yO,bO,b5,v5,bae,wae,vae,kae,ux,px,mx,fx,gx,vO,Iae,_ae,bx,Cae,P5,vx,vn,Mae,Fae,qae,Hae,$ae,Vae,jae,kO,E5,R5,xO,I5,zae,Wae,Gae,ua,mi,P0,AO,cr,kx,_5,Xae,Jae,TO,C5,rle,sle,ale,lle,ule,ple,mle,hle,gle,yle,ble,vle,kle,xle,Tle,Sle,Ple,Ele,Ile,_le,Cle,Ole,Lle,Dle,Ble,Mle,Fle,qle,Vle,jle,zle,Qle,Ax,Jle,mN,L5,Tx,Sx,PO,tce,nce,rce,EO,A0,T0,oce,sce,ace,lce,D5,pce,mce,TN,SN,fce,gce,yce,E0,bce,vce,Sce,Ece,Rce,Px,Ice,Cce,Oce,Ex,Dce,Rx,$ce,hN,Vce,jce,zce,Wce,fN,Ix,M5,ic,ds,F5,Xce,_x,Jce,Nx,Zce,Lx,eue,tue,Dx,nue,rue,oue,Bx,q5,sue,iue,aue,lue,cue,Fx,uue,Hx,Vx,due,pue,mue,Aue,Tue,Sue,Pue,Eue,Rue,Iue,_ue,$5,Cue,Nue,Oue,Lue,Due,zx,Wx,V5,Gx,Kx,Yx,Gue,tA,Kue,Yue,Que,nA,Xue,rA,Jue,oA,Zue,sA,ede,iA,tde,aA,lA,G5,K5,Y5,Q5,rde,Vd,X5,Z5,pA,tV,nV,rV,oV,ode,jd,sV,aV,gA,cV,uV,sde,dV,pV,mV,ide,bA,dde,vA,ac,xA,lc,AA,cc,TA,SA,UO,pde,mde,hde,fde,gde,yde,bde,ms,wde,y6,C0,kde,EA,Tde,Sde,IA,Cde,CA,Nde,OA,zd,b6,Ode,DA,Dde,Ude,BA,FA,HA,Bde,Mde,wV,Fde,$A,qde,jA,WA,KA,jde,w6,vV,zde,QA,kV,Gde,Kde,Yde,Jde,Zde,epe,tpe,npe,rpe,XA,ZA,tT,rT,ope,sT,spe,xV,aT,cT=L(()=>{"use strict";Zw();cf();cf();OC();Tl();h=require("zod");o0();hw();P$();h0();h0();p4();g0();g0();rN();U4();Qw();lN();j4();Ot=h.z.number().int().positive();x6=h.z.strictObject({offset:h.z.number().int().min(0),pageSize:Ot});Ere=h.z.object({kind:h.z.literal("keyset"),fingerprint:h.z.string(),cursor:h.z.string().min(1)});_N=class{#e;constructor({url:e}){this.#e=e}async ethCall(e){let t=await this.#s({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.to,data:e.data},"latest"]});if("error"in t)throw new O(`JSON-RPC eth_call failed: ${t.error.message}`,{cause:t.error,status:200});if(typeof t.result!="string")throw new C("Expected JSON-RPC eth_call result to be a hex string");if(!I6(t.result))throw new C("Expected JSON-RPC eth_call result to be a hex string");return t.result}async ethCallBatch(e){return e.length===0?[]:this.#t(e)}async ethEstimateGas(e){let t={to:e.to};e.data!==void 0&&(t.data=e.data),e.from!==void 0&&(t.from=e.from),e.gasPrice!==void 0&&(t.gasPrice=G4(e.gasPrice)),e.value!==void 0&&(t.value=G4(e.value));let n=await this.#s({jsonrpc:"2.0",id:1,method:"eth_estimateGas",params:[t]});if("error"in n)throw new O(`JSON-RPC eth_estimateGas failed: ${n.error.message}`,{cause:n.error,status:200});return BigInt(W4(n.result,"eth_estimateGas"))}async#t(e){if(e.length===1)return[await this.ethCall(e[0])];try{return await this.#r(e)}catch(t){if(!(t instanceof O)||t.status<500)throw t;let n=Math.ceil(e.length/2),[r,o]=await Promise.all([this.#t(e.slice(0,n)),this.#t(e.slice(n))]);return[...r,...o]}}async#r(e){let t=await this.#n(e.map((r,o)=>({jsonrpc:"2.0",id:o+1,method:"eth_call",params:[{to:r.to,data:r.data},"latest"]}))),n=new Map;for(let r of t){if("error"in r&&r.id===null)throw new O(`JSON-RPC eth_call failed: ${r.error.message}`,{cause:r.error,status:200});r.id!==null&&n.set(r.id,r)}return e.map((r,o)=>{let s=o+1,i=n.get(s);if(i===void 0)throw new C("Expected JSON-RPC batch response for every request");if("error"in i)throw new O(`JSON-RPC eth_call failed: ${i.error.message}`,{cause:i.error,status:200});return W4(i.result)})}async#s(e){let t;try{t=await u0.post(this.#e,{json:e,throwHttpErrors:!1})}catch(r){throw _.fromError(r)}if(!t.ok)throw new O(`JSON-RPC request to ${this.#e} failed with status ${t.status}`,{status:t.status});let n;try{n=await t.json()}catch(r){throw new C("Expected JSON-RPC response body to be JSON",{cause:r})}if(!z4(n))throw new C("Unexpected JSON-RPC response shape");return n}async#n(e){let t;try{t=await u0.post(this.#e,{json:e,throwHttpErrors:!1})}catch(r){throw _.fromError(r)}if(!t.ok)throw new O(`JSON-RPC request to ${this.#e} failed with status ${t.status}`,{status:t.status});let n;try{n=await t.json()}catch(r){throw new C("Expected JSON-RPC response body to be JSON",{cause:r})}if(!Array.isArray(n)||!n.every(r=>z4(r)))throw new C("Unexpected JSON-RPC response shape");return n}};CN=(e=>(e.OWNER="OWNER",e.SESSION_KEY="SESSION_KEY",e))(CN||{}),Ore="0x0000000000000000000000000000000000000000000000000000000000000000",Lre="0x6492649264926492649264926492649264926492649264926492649264926492";Ure="3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000";qre="0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",Hre="0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",$re=0x61003d3d8160233d3973n;Vre="0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",jre="0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",zre="0x60195155f3363d3d373d3d363d602036600436635c60da",Wre=0x6100523d8160233d3973n,Gre="0x49493a4d";C6=h.z.string().transform(e=>e);gf=h.z.union([h.z.number().int().min(0),h.z.date()]).transform(e=>e instanceof Date?Math.floor(e.getTime()/1e3):e),L0=h.z.union([h.z.literal("full"),h.z.object({start:gf.optional(),end:gf.optional()}).refine(e=>!e.end||e.end>=(e.start??0),"end must not precede start")]).transform(e=>e==="full"?{start:1}:e),N6=Gt.refine(e=>/^[1-9]\d*$/.test(e)&&BigInt(e)<=2147483647n,"Expected a positive 32-bit event ID");D0=B($,O,ue,_,C);ooe=h.z.object({cursor:ye.optional(),id:h.z.string().optional(),market:h.z.string().optional()}),soe=Fd(ooe.shape).default({}),B0=B($,O,ue,_,C,E);ioe=h.z.object({orderId:h.z.string()}),F0=B($,O,ue,_,C,E);aoe={after:h.z.string().optional(),before:h.z.string().optional(),cursor:ye.optional(),id:h.z.string().optional(),makerAddress:h.z.string().optional(),market:h.z.string().optional()},loe=Fd(aoe).default({}),H0=B($,O,ue,_,C,E);$0=B($,O,ue,_,C),coe=h.z.object({ids:h.z.array(h.z.string()).min(1)});j0=B($,O,ue,_,C,E);L6=h.z.object({assetType:p3}),uoe=Fd(L6.shape),D6=B($,O,ue,_,C,E);doe=Fd(L6.shape),U6=B($,O,ue,_,C,E);poe=h.z.object({orderId:h.z.string()}),G0=B($,O,ue,_,C,E);moe=h.z.object({orderIds:h.z.array(h.z.string())}),Y0=B($,O,ue,_,C,E);B6=h.z.object({cursor:ye.optional(),date:h.z.string()}),X0=B($,O,ue,_,C,E);Z0=B($,O,ue,_,C,E);hoe=h.z.object({cursor:ye.optional(),date:h.z.string(),noCompetition:h.z.boolean().optional(),orderBy:h.z.string().optional(),pageSize:Ot.max(500).default(100),position:h.z.string().optional()}),tv=B($,O,ue,_,C,E);rv=B($,O,ue,_,C);foe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J.optional(),takerOnly:h.z.boolean().optional(),filterType:I$.optional(),filterAmount:h.z.number().min(0).optional(),conditionId:h.z.union([xe,ca(xe,20)]).optional(),eventId:h.z.array(Gt).min(1).optional(),side:Nt.optional(),window:L0.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),sv=B($,O,_,C,E);goe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([xe,ca(xe,20)]).optional(),eventId:h.z.array(Gt).min(1).optional(),type:h.z.array(KC).min(1).optional(),side:Nt.optional(),sortDirection:m0.optional(),window:L0.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),av=B($,O,_,C,E);yoe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([Zt,ca(Zt,20)]).optional()}),lv=B($,O,_,C,E);boe=64,woe=/^0x[0-9a-fA-F]{62}$/,voe=/^0x[0-9a-fA-F]{64}$/,LN="0x0000000000000000000000000000000000000000000000000000000000000000",koe=_e.from("function approve(address spender, uint256 amount)"),M6=_e.from("function allowance(address owner, address spender) view returns (uint256)"),xoe=_e.from("function transfer(address recipient, uint256 amount)"),Aoe=_e.from("function authorizeSessionSigner(address sessionSigner, uint256 validUntil)"),Toe=_e.from("function revokeSessionSigner(address sessionSigner)"),Soe=_e.from("function deposit(address token, uint256 amount, address to)"),Poe=_e.from("function setApprovalForAll(address operator, bool approved)"),F6=_e.from("function isApprovedForAll(address account, address operator) view returns (bool)"),q6=_e.from("function balanceOf(address account, uint256 id) view returns (uint256)"),H6=_e.from("function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])"),Eoe=_e.from("function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Roe=_e.from("function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Ioe=_e.from("function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)"),_oe=_e.from("function split(bytes31 conditionId, uint256 amount)"),Coe=_e.from("function merge(bytes31 conditionId, uint256 amount)"),Noe=_e.from("function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)"),Ooe=_e.from("function prepareCondition(uint256[] legs) returns (bytes31)"),Loe=_e.from("function multiSend(bytes)"),Doe=_e.from("function proxy((uint8 typeCode, address to, uint256 value, bytes data)[] calls) returns (bytes[])"),$6=[1n,2n],Uoe=[1n,2n],lr=(1n<<256n)-1n,V6=B(E);j6=B(E);z6=B(E);W6=B(E);G6=B(E);K6=B(E);Y6=B(E);Q6=B(E);X6=B(E);J6=B(E);Z6=B($,O,tt,en,_,C,E);B(bt,ue);B(bt,ue);zoe=[{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Woe=[{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"},{name:"operation",type:"uint8"},{name:"safeTxGas",type:"uint256"},{name:"baseGas",type:"uint256"},{name:"gasPrice",type:"uint256"},{name:"gasToken",type:"address"},{name:"refundReceiver",type:"address"},{name:"nonce",type:"uint256"}],Goe="DepositWallet",Koe="1",Yoe=600,Qoe=[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],Xoe=[{name:"wallet",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"calls",type:"Call[]"}],Joe=h.z.object({address:h.z.string(),type:h.z.enum(_r)}),t8=B($,O,_,C,E);Zoe=h.z.object({transactionId:ea}),ese=h.z.object({wallet:J,type:h.z.enum(Se)}),n8=B($,O,_,C,E);ur=h.z.string().max(500),K4=10,r8=B($,O,_,C,E);nse=h.z.object({data:h.z.custom(ln),to:J,value:h.z.bigint().optional()}),rse=h.z.object({calls:h.z.array(nse).min(1).transform(e=>XF(e)),metadata:ur}),o8=B($,O,_,C,E);c8=B($,O,_,C,E,tt,en),Cf=class{#e;transactionHash;transactionId;constructor(e,t){this.#e=e,this.transactionHash=t.transactionHash,this.transactionId=t.transactionId}async wait(){let e=0;for(;e<this.#e.environment.relayerMaxPolls;){let t=await XN(this.#e,{transactionId:this.transactionId});if(t.state===Ld.STATE_CONFIRMED){let n=t.transactionHash??this.transactionHash;if(n===null)throw new C("Expected submitted transaction to have a transaction hash once settled");return{transactionHash:n,transactionId:t.transactionId}}if(t.state===Ld.STATE_FAILED||t.state===Ld.STATE_INVALID)throw new en(t.errorMsg??`Transaction ${t.transactionId} reached terminal state ${t.state}`);e+=1,await ns(this.#e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for transaction ${this.transactionId} to settle`)}},pse=h.z.object({amount:h.z.union([h.z.bigint(),h.z.literal("max")]),metadata:ur.optional(),spenderAddress:J,tokenAddress:J}),u8=B(E);bv=B(bt,$,O,ue,_,C,E);mse=h.z.object({approved:h.z.boolean().default(!0),metadata:ur.optional(),operatorAddress:J,tokenAddress:J}),d8=B(E);wv=B(bt,$,O,ue,_,C,E);p8=B(O,_,C,E),hse=h.z.object({user:J}),vv=B(O,_,C,E);kv=B(bt,$,O,ue,tt,en,_,C,E);g8=B($,O,_,C);y8=B($,O,_,C);b8=B($,O,_,C);w8=B($,O,ue,_,C);v8=B($,O,ue,_,C);k8=B($,O,ue,_,C);A8=B($,O,ue,_,C);S8=B($,O,ue,_,C);gse=h.z.object({after:h.z.string().optional(),before:h.z.string().optional(),builderCode:bo,cursor:ye.optional(),id:h.z.string().optional(),market:h.z.string().optional()}),yse=Fd(gse.shape),Pv=B($,O,_,C,E);bse=Nr({}),Rv=B($,O,_,C,E);wse=h.z.array(Nr({})).min(1),_v=B($,O,_,C,E);vse=Nr({}),R8=B($,O,_,C,E);kse=Nr({}),_8=B($,O,_,C,E);xse=Nr({}),N8=B($,O,_,C,E);Ase=h.z.object({conditionId:xe}),O8=B($,O,_,C,E);Tse=h.z.object({builderCode:bo}),L8=B($,O,_,C,E);Sse=Nr({side:Nt}),Nv=B($,O,_,C,E);Pse=h.z.array(Nr({side:Nt})).min(1),Lv=B($,O,_,C,E);Ese=Nr({}),Uv=B($,O,_,C,E);Rse=h.z.array(Nr({})).min(1),Bv=B($,O,_,C,E);Ise=Nr({}),Fv=B($,O,_,C,E);_se=h.z.array(Nr({})).min(1),Hv=B($,O,_,C,E);Cse=Nr({}),Vv=B($,O,_,C,E);Nse=h.z.array(Nr({})).min(1),zv=B($,O,_,C,E);Ose=h.z.object({cursor:ye.optional(),sponsored:h.z.boolean().optional()}).default({}),Gv=B($,O,_,C,E);Lse=h.z.object({conditionId:xe,cursor:ye.optional(),sponsored:h.z.boolean().optional()}),Yv=B($,O,_,C,E);D8=2*6e4,Jv=B($,O,_,C);Use=h.z.object({plan:b4}),Y4=10,uN="Collateral return",U8=B(O,_,C,E);ek=B(bt,$,O,ue,_,C,E);aO=100,lO=200,M8={maxOffset:lO,maxPageSize:aO},Mse=h.z.object({ascending:h.z.boolean().optional(),cursor:ye.optional(),pageSize:Ot.max(aO).default(20),getPositions:h.z.boolean().optional(),holdersOnly:h.z.boolean().optional(),order:h.z.string().optional(),parentEntityId:h.z.union([Gt,Mh]),parentEntityType:Js}),Fse=h.z.object({getPositions:h.z.boolean().optional(),id:Xs}),qse=h.z.object({address:h.z.string(),ascending:h.z.boolean().optional(),cursor:ye.optional(),order:h.z.string().optional(),pageSize:Ot.max(aO).default(20)}),nk=B(Ol,$,O,_,C,E),Hse=h.z.enum(["id","createdAt"]);ok=B($,O,_,C,E);ik=B(Ol,$,O,_,C,E);Vse=h.z.object({ascending:h.z.boolean().optional(),closed:h.z.boolean().default(!1),cursor:ye.optional(),pageSize:Ot.optional(),cyom:h.z.boolean().optional(),endDateMax:oe.optional(),endDateMin:oe.optional(),ended:h.z.boolean().optional(),eventDate:Wn.optional(),eventWeek:h.z.number().int().optional(),excludeTagIds:h.z.array(h.z.number().int()).optional(),featured:h.z.boolean().optional(),featuredOrder:h.z.boolean().optional(),gameIds:h.z.array(h.z.number().int()).optional(),ids:h.z.array(h.z.number().int()).optional(),includeBestLines:h.z.boolean().optional(),includeChat:h.z.boolean().optional(),includeChildren:h.z.boolean().optional(),includeTemplate:h.z.boolean().optional(),liquidityMax:h.z.number().optional(),liquidityMin:h.z.number().optional(),live:h.z.boolean().optional(),locale:h.z.string().optional(),order:h.z.string().optional(),parentEventId:h.z.number().int().optional(),partnerSlug:h.z.string().optional(),recurrence:h.z.enum(["daily","weekly","monthly"]).optional(),relatedTags:h.z.boolean().optional(),seriesIds:h.z.array(h.z.number().int()).optional(),slug:h.z.array(h.z.string()).optional(),startDateMax:oe.optional(),startDateMin:oe.optional(),startTimeMax:oe.optional(),startTimeMin:oe.optional(),tagIds:h.z.array(h.z.number().int()).optional(),tagMatch:h.z.enum(["any","all"]).optional(),tagSlug:h.z.string().optional(),titleSearch:h.z.string().optional(),volumeMax:h.z.number().optional(),volumeMin:h.z.number().optional()}),jse=h.z.union([h.z.object({id:h.z.string(),includeBestLines:h.z.boolean().optional(),includeChat:h.z.boolean().optional(),includeTemplate:h.z.boolean().optional(),locale:h.z.string().optional()}),h.z.object({slug:h.z.string(),includeBestLines:h.z.boolean().optional(),includeChat:h.z.boolean().optional(),includeTemplate:h.z.boolean().optional(),locale:h.z.string().optional()}),h.z.object({url:h.z.string(),includeBestLines:h.z.boolean().optional(),includeChat:h.z.boolean().optional(),includeTemplate:h.z.boolean().optional(),locale:h.z.string().optional()})]),zse=h.z.object({id:h.z.string()}),lk=B($,O,_,C,E);uk=B($,O,_,C,E);pk=B($,O,_,C,E);Gse=h.z.array(ql).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct condition ids"),Kse=h.z.array(N6).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct event ids"),Yse=h.z.union([h.z.object({questionId:vo,conditionIds:h.z.never().optional(),eventIds:h.z.never().optional()}),h.z.object({questionId:h.z.never().optional(),conditionIds:Gse,eventIds:h.z.never().optional()}),h.z.object({questionId:h.z.never().optional(),conditionIds:h.z.never().optional(),eventIds:Kse})]),hk=B($,O,_,C,E);Qse=h.z.object({eventIds:h.z.array(N6).min(1).transform(e=>[...new Set(e)])}),gk=B($,O,_,C,E);eie=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),window:ff.optional()}),bk=B($,O,_,C,E);tie=h.z.object({interval:X$.optional(),bucketLimit:h.z.number().int().positive().max(90).optional()}),vk=B($,O,_,C,E);cO=h.z.string().min(1),nie=h.z.object({category:cO.optional(),cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),sortBy:J$.optional(),window:ff.optional()}),xk=B($,O,_,C,E);rie=h.z.object({category:cO.optional(),user:J,window:ff.optional()}),Tk=B($,O,_,C,E);oie=h.z.object({category:cO.optional(),cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),window:ff.optional()}),Sk=B($,O,_,C,E);sie=h.z.object({marketId:h.z.union([h.z.string(),h.z.array(h.z.string())]).optional(),eventId:h.z.union([h.z.string(),h.z.array(h.z.string())]).optional(),questionId:h.z.union([h.z.string(),h.z.array(h.z.string())]).optional(),state:h.z.union([h.z.enum(uf),h.z.array(h.z.enum(uf))]).optional(),showInFrontend:h.z.boolean().optional(),txHash:h.z.string().optional(),order:h.z.string().optional(),ascending:h.z.boolean().optional(),cursor:ye.optional(),pageSize:Ot.max(100).default(20)}),q8=B($,O,_,C,E);iie=h.z.object({ascending:h.z.boolean().optional(),closed:h.z.boolean().optional(),clobTokenIds:h.z.array(h.z.string()).optional(),cursor:ye.optional(),pageSize:Ot.optional(),conditionIds:h.z.array(xe).optional(),cyom:h.z.boolean().optional(),decimalized:h.z.boolean().optional(),endDateMax:oe.optional(),endDateMin:oe.optional(),gameId:h.z.string().optional(),ids:h.z.array(h.z.number().int()).optional(),includeTag:h.z.boolean().optional(),liquidityNumMax:h.z.number().optional(),liquidityNumMin:h.z.number().optional(),locale:h.z.string().optional(),order:h.z.string().optional(),positionIds:h.z.array(Xe).optional(),questionIds:h.z.array(h.z.string()).optional(),relatedTags:h.z.boolean().optional(),rfqEnabled:h.z.boolean().optional(),rewardsMinSize:h.z.number().optional(),slug:h.z.array(h.z.string()).optional(),sportsMarketTypes:h.z.array(h.z.string()).optional(),startDateMax:oe.optional(),startDateMin:oe.optional(),tagId:h.z.number().int().optional(),tagMatch:h.z.enum(["any","all"]).optional(),umaResolutionStatus:h.z.string().optional(),volumeNumMax:h.z.number().optional(),volumeNumMin:h.z.number().optional()}),aie=h.z.object({id:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),lie=h.z.object({slug:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),cie=h.z.object({url:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),uie=h.z.union([aie,lie,cie]),die=h.z.object({id:h.z.string()}),Rk=B($,O,_,C,E);pie=h.z.object({cursor:ye.optional(),pageSize:Ot.max(100).optional(),exclude:h.z.array(xe).optional()}),Ik=B($,O,_,C,E);Ck=B($,O,_,C,E);Ok=B($,O,_,C,E);mie=h.z.object({conditionIds:ca(ql,20),cursor:ye.optional(),includePnl:h.z.boolean().optional(),minBalance:h.z.number().nonnegative().optional(),pageSize:Ot.max(1e3).default(100)}).superRefine(({conditionIds:e,includePnl:t,pageSize:n},r)=>{t&&(e.length!==1&&r.addIssue({code:"custom",message:"includePnl requires exactly one conditionId",path:["conditionIds"]}),n>100&&r.addIssue({code:"custom",message:"includePnl supports pageSize at most 100",path:["pageSize"]}))}),Dk=B($,O,_,C,E);hie=360*60*60,fie=253402300799,yN=gf.pipe(h.z.number().int().positive().max(fie)),H8=h.z.string().min(1).pipe(Me),$8={assetId:H8,bucketSeconds:h.z.number().int().min(60).max(86400).optional(),cursor:ye.optional(),pageSize:Ot.max(1e4).default(1e4)},gie=h.z.object({...$8,interval:W$,start:h.z.never().optional(),end:h.z.never().optional(),asOf:h.z.never().optional()}).superRefine(({bucketSeconds:e,interval:t},n)=>{let r=t===Po.Max||t===Po.OneMonth?600:t===Po.OneWeek?300:60;e!==void 0&&e<r&&n.addIssue({code:"custom",message:`bucketSeconds must be at least ${r} for this interval`,path:["bucketSeconds"]})}),yie=h.z.object({...$8,start:yN,end:yN.optional(),interval:h.z.never().optional(),asOf:h.z.never().optional()}).superRefine(({end:e,start:t},n)=>{if(e!==void 0&&e<t){n.addIssue({code:"custom",message:"end must not precede start",path:["end"]});return}(e??Math.floor(Date.now()/1e3))-t>hie&&n.addIssue({code:"custom",message:"start to end must span at most 15 days",path:["end"]})}),bie=h.z.object({assetId:H8,asOf:yN,interval:h.z.never().optional(),start:h.z.never().optional(),end:h.z.never().optional(),bucketSeconds:h.z.never().optional(),cursor:h.z.never().optional(),pageSize:h.z.never().optional()}),wie=h.z.union([gie,yie,bie]),Bk=B($,O,_,C,E);vie=h.z.object({conditionIds:ca(ql,20).optional()}),Fk=B($,O,_,C,E);Sie=h.z.object({orderId:h.z.string()}),Pie=h.z.object({orderIds:h.z.array(h.z.string()).min(1).max(3e3)}),Eie=h.z.object({market:h.z.string().optional()}),Rie=Fd(Eie.shape).refine(e=>e.market!==void 0||e.assetId!==void 0||e.tokenId!==void 0,{message:"At least one of market or assetId is required.",path:["market"]}),Hk=B(O,$,ue,_,C,E);Vk=B(O,$,ue,_,C,E);zk=B(O,$,ue,_,C);Gk=B(O,$,ue,_,C,E);kf=h.z.object({assetId:Me,tokenId:h.z.never().optional()}),xf=h.z.object({assetId:h.z.never().optional(),tokenId:Me}),V8=h.z.object({orderType:h.z.union([h.z.literal(cn.FAK),h.z.literal(cn.FOK)]).default(cn.FOK)}),e6=V8.extend({side:h.z.literal(Ue.BUY),amount:ko}),t6=V8.extend({side:h.z.literal(Ue.SELL),shares:ko}),Iie=h.z.union([e6.extend(kf.shape),e6.extend(xf.shape),t6.extend(kf.shape),t6.extend(xf.shape)]).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t})),Qk=B(So,$,O,_,C,E);Oie=BigInt(Number.MAX_SAFE_INTEGER),Lie=h.z.string().refine(Uie,{message:"Order salt must be a non-negative JavaScript-safe integer."}),j8=h.z.looseObject({salt:Lie}),Die=h.z.array(j8).min(1).max(15),Zk=B($,O,ue,_,C,E),ex=B($,O,ue,_,C,E);W8=32,Bie=1n,Mie=2n,G8=3n,n6=50,Fie=(1n<<256n)-1n,qie=(1n<<64n)-1n<<40n;rc=1000000n,$ie=8*Number.EPSILON,dN=6,Vie=8*Number.EPSILON;pN=600*1e3,vN=Number.POSITIVE_INFINITY,Kie=class{#e;#t=new Map;#r=new Map;#s=new Map;constructor(e){this.#e=e}async resolveMarket(e){let t=await this.#n(e);return{feeInfo:t.feeInfo,negRisk:t.negRisk,tickSize:t.tickSize}}async resolveBuilderTakerFeeRate(e){return e===void 0?0:x0(this.#t,e,pN,()=>this.#e.fetchBuilderTakerFeeRate(e))}async fetchCurrentMarket(e){let t=await x0(this.#r,e,vN,()=>this.#e.resolveCondition(e)),n=await this.#i(t);return this.#o(e,t,n),this.#s.set(t,r6(n,pN)),{feeInfo:n.feeInfo,negRisk:n.negRisk,tickSize:n.tickSize}}async#n(e){let t=await x0(this.#r,e,vN,()=>this.#e.resolveCondition(e)),n=await x0(this.#s,t,pN,()=>this.#i(t));return this.#o(e,t,n),n}#o(e,t,n){if(!n.assetIds.has(e))throw this.#r.delete(e),this.#s.delete(t),new C(`Market ${t} does not include asset ${e}.`)}async#i(e){let t=await this.#e.fetchMarket(e),n=new Set(t.tokens.map(({assetId:r})=>r));for(let r of n)this.#r.set(r,r6(e));return{feeInfo:t.feeInfo,negRisk:t.negRisk,tickSize:t.tickSize,assetIds:n}}};o6=new WeakMap;Qie=180,s6=h.z.strictObject({price:ko,size:ko,side:Nt,builderCode:bo.optional(),postOnly:h.z.boolean().default(!1),expiration:h.z.number().int().nonnegative().optional()}),Xie=h.z.union([s6.extend(kf.shape),s6.extend(xf.shape)]).superRefine((e,t)=>{if(e.expiration!==void 0){let n=Math.floor(Date.now()/1e3)+Qie;e.expiration<n&&t.addIssue({code:"custom",message:"Expiration must be at least 3 minutes in the future.",path:["expiration"]})}}).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t}));t5=h.z.object({builderCode:bo.optional(),orderType:h.z.union([h.z.literal(cn.FAK),h.z.literal(cn.FOK)]).default(cn.FAK)}),a6=t5.extend({side:h.z.literal(Ue.BUY),amount:ko,maxSpend:ko.optional(),maxPrice:ko.optional()}),l6=t5.extend({side:h.z.literal(Ue.SELL),shares:ko,minPrice:ko.optional()}),tae=h.z.union([a6.extend(kf.shape),a6.extend(xf.shape),l6.extend(kf.shape),l6.extend(xf.shape)]).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t}));i5="Polymarket CTF Exchange",aae="DepositWallet",lae="1",xN="0x0000000000000000000000000000000000000000000000000000000000000000",AN="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",cae=Je.keccak256(we.fromString(AN),{as:"Hex"}),uae=Je.keccak256(we.fromString("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),{as:"Hex"}),dae=Je.keccak256(we.fromString(i5),{as:"Hex"}),a5=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],l5=[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"signer",type:"address"},{name:"tokenId",type:"uint256"},{name:"makerAmount",type:"uint256"},{name:"takerAmount",type:"uint256"},{name:"side",type:"uint8"},{name:"signatureType",type:"uint8"},{name:"timestamp",type:"uint256"},{name:"metadata",type:"bytes32"},{name:"builder",type:"bytes32"}],pae=[{name:"contents",type:"Order"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"}];p6="0x0000000000000000000000000000000000000000000000000000000000000000";yO=B(So,$,O,ue,_,C,E);bO=B($,O,ue,_,C,E);b5=yO;v5=bO;bae=250,wae=3e4,vae={timeoutMs:h.z.number().int().positive().optional()},kae=h.z.object(vae).default({}),ux=B($,O,ue,tt,en,_,C,E);px=B(bt,So,$,O,ue,_,C,E);mx=B(bt,So,$,O,ue,tt,en,_,C,E);fx=B(bt,$,O,ue,_,C,E);gx=B(bt,$,O,ue,tt,en,_,C,E);vO=h.z.string().regex(/^\d+(?:\.\d{1,28})?$/,"Expected a non-negative fixed-point fee rate with at most 28 fractional digits."),Iae=h.z.object({builderAddress:J,feeRate:vO});_ae=h.z.object({address:J}),bx=B($,O,_,C,E);Cae=h.z.strictObject({builder:J,maxFeeRate:vO,approvalVersion:h.z.number().int().positive().max(Number.MAX_SAFE_INTEGER)}),P5=h.z.strictObject({builderAddress:J.optional(),maxFeeRate:vO}),vx=B($,O,ue,_,C,E);vn=class{#e;#t;#r;#s;constructor({root:e,headers:t,resolveHeaders:n,onRateLimitUpdate:r}){this.#e=u0.create({prefixUrl:e,throwHttpErrors:!1}),this.#t=t,this.#r=n,this.#s=r}get(e,t={}){return this.#o("GET",e,t)}post(e,t={}){return this.#o("POST",e,t)}patch(e,t={}){return this.#o("PATCH",e,t)}del(e,t={}){return this.#o("DELETE",e,t)}#n(e){return e.startsWith("/")?e.slice(1):e}#o(e,t,n){return this.#c(this.#i(e,t,n),n.rateLimitBucket)}async#i(e,t,n){let r=this.#a(e,t,n),o=await this.#r?.(r),s=this.#l(this.#t,r.headers,o);return r.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json"),this.#e(this.#n(t),{body:r.body,headers:s,method:e,searchParams:r.params,...n.timeout!==void 0&&{timeout:n.timeout}})}#a(e,t,n){return{body:"json"in n?this.#u(n.json):void 0,headers:n.headers,json:"json"in n?n.json:void 0,method:e,params:"params"in n?n.params:void 0,path:t}}#u(e){if(e!==void 0)return JSON.stringify(e)}#l(...e){let t=new Headers;for(let n of e)if(n!==void 0)for(let[r,o]of new Headers(n).entries())t.set(r,o);return t}#c(e,t){return _n.fromPromise(e.then(async n=>{let r=Uae(n.headers,t);if(r!==void 0&&this.#p(r),n.ok)return n;let o=this.#d(n);if(n.status===429)throw new $(`Request to ${n.url} was rate limited`,{rateLimit:r,retryAfter:o});let{code:s,message:i,retryAfter:a}=await this.#m(n);throw new O(i,{code:s,retryAfter:o??a,status:n.status})}),n=>n instanceof $||n instanceof O?n:_.fromError(n))}#p(e){try{Promise.resolve(this.#s?.(e)).catch(()=>{})}catch{}}#d(e){let t=e.headers.get("retry-after");if(!(t===null||!/^\d+$/.test(t)))return Number(t)}async#m(e){let t=e.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")){let{error:n,code:r,retry_after_seconds:o}=await e.clone().json().catch(()=>({}));if(n){let s=typeof r=="string"&&r!==""?r:void 0,i=s===void 0&&e.status!==400&&typeof n=="string"&&/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/.test(n)?n:void 0,a=s??i;return{message:`${String(n)} (${e.url})`,...a!==void 0?{code:a}:{},...typeof o=="number"&&Number.isFinite(o)&&o>=0?{retryAfter:o}:{}}}}if(t?.includes("text/plain")){let n=await e.clone().text().then(r=>r.trim(),()=>"");if(n)return{message:`${n} (${e.url})`}}return e.headers.get("server")?.toLowerCase()?.includes("cloudflare")?{message:`Request to ${e.url} was blocked by Cloudflare with status ${e.status}`}:t?.includes("text/html")||t?.includes("application/xhtml+xml")?{message:`Request to ${e.url} failed with status ${e.status} and an unexpected HTML response body`}:{message:`Request to ${e.url} failed with status ${e.status} and unreadable response body`}}},Mae=1e4,Fae=3e4,qae=5e3,Hae=10*6e4,$ae=3e4,Vae=25e3,jae=65e3,kO=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e("PING")},Mae)}handleMessage(e){return e!=="PONG"?!1:(this.#e=Date.now(),!0)}isStale(e){return e-this.#e>Fae}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},E5=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e("PING")},qae)}handleMessage(){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>Hae}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},R5=class{#e=0;#t;start(e){this.#e=Date.now(),this.#t=e}stop(){this.#t=void 0}handleMessage(e){return e!=="ping"?!1:(this.#e=Date.now(),this.#t?.("pong"),!0)}isStale(e){return e-this.#e>$ae}},xO=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e(JSON.stringify({id:0,req:"post",op:{type:"ping"}}))},Vae)}handleMessage(){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>jae}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},I5=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>e('{"op":"ping"}'),3e4)}handleMessage(e){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>=9e4}stop(){clearInterval(this.#t),this.#t=void 0}},zae=5e3,Wae=250,Gae=3e4,ua=class{#e;#t=0;get isScheduled(){return this.#e!==void 0}schedule(e){if(this.#e!==void 0||!e.shouldReconnect())return;let t=e.delayPolicy?.(this.#t)??Yae(this.#t,{baseMs:Wae,maxMs:Gae});this.#t+=1,this.#e=gn(()=>{this.#e=void 0,this.#r(e)},t)}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0)}resetBackoff(){this.#t=0,this.stop()}async#r(e){if(e.shouldReconnect())try{await e.reconnect()}catch{this.schedule(e)}}},mi=class{#e;#t;#r;#s;#n;#o;#i;constructor(e={}){this.#e=e.heartbeat,this.#t=e.connectTimeoutMs,this.#r=e.closeTimeoutMs}connect(e){if(this.#n?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:!0});if(this.#c(),this.#o!==void 0)return this.#o;let t=this.#u(e).then(()=>({reusedOpenSocket:!1})).catch(n=>{throw this.#o===t&&(this.#o=void 0),n});return this.#o=t,t}send(e){return this.#a(JSON.stringify(e))}#a(e){return this.#n?.readyState!==WebSocket.OPEN?!1:(this.#n.send(e),!0)}async close(){this.#s?.();let e=await this.#m();this.#d(),!(e===void 0||e.readyState===WebSocket.CLOSED)&&await new Promise(t=>{let n=this.#r===void 0?void 0:gn(t,this.#r);e.addEventListener("close",()=>{clearTimeout(n),t()},{once:!0}),e.readyState!==WebSocket.CLOSING&&e.close()})}async#u(e){let t=await e.prepare?.();return new Promise((n,r)=>{let o=Kae(e.url,e.headers),s,i=()=>{o.removeEventListener("open",a),clearTimeout(s),this.#s=void 0,r(new _("WebSocket connection did not open.")),o.close()},a=()=>{clearTimeout(s),this.#s=void 0,o.removeEventListener("error",l),this.#l(o),this.#p(),e.onOpen(t),n(o)},l=c=>{clearTimeout(s),this.#s=void 0,o.removeEventListener("open",a),r(new _(`WebSocket connection failed: ${e.url}`,{cause:c}))};o.addEventListener("open",a,{once:!0}),this.#t!==void 0&&(this.#s=i,s=gn(i,this.#t)),o.addEventListener("error",l,{once:!0}),o.addEventListener("message",c=>{if(this.#n!==o)return;let u=String(c.data);if(this.#e?.handleMessage(u))return;let d;try{d=JSON.parse(u)}catch{return}e.onMessage(d)}),o.addEventListener("close",c=>{this.#n===o&&(this.#c(),e.onConnectionLost({code:c.code||1005,reason:c.reason??""}))}),o.addEventListener("error",()=>e.onError())})}#l(e){this.#n=e,this.#o=void 0}#c(){this.#d(),this.#n=void 0}#p(){this.#d();let e=this.#e;e!==void 0&&(e.start(t=>this.#a(t)),this.#i=ud(()=>{if(!e.isStale(Date.now()))return;let t=this.#n;t?.readyState===WebSocket.OPEN&&t.close()},zae))}#d(){this.#i!==void 0&&(clearInterval(this.#i),this.#i=void 0),this.#e?.stop()}async#m(){let e=this.#n,t=this.#o;return this.#n=void 0,this.#o=void 0,e!==void 0?e:t?.then(()=>this.#n,()=>{})}};P0=1440*60*1e3,AO=90*P0,cr=h.z.number().int().nonnegative(),kx=h.z.object({start:cr.optional(),end:cr.optional()}),_5=h.z.object({interval:$w,start:cr,end:cr.optional()}),Xae=h.z.enum(["perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),Jae=h.z.enum(["perpsEquityHistory","perpsPnlHistory"]),TO=h.z.object({kind:Xae,startTimestamp:cr,endTimestamp:cr,instrumentId:Ae.optional(),depositStatus:kd.optional(),withdrawalStatus:xd.optional(),hash:et.optional(),seenKeys:h.z.array(h.z.string())}),C5=h.z.object({kind:Jae,startTimestamp:cr,endTimestamp:cr,interval:$w});rle=h.z.object({instrumentId:Ae.optional()}).default({});sle=h.z.object({instrumentId:Ae.optional()}).default({});ale=h.z.object({orderId:Cn.optional(),clientOrderId:Er.optional(),instrumentId:Ae.optional(),start:cr.optional(),end:cr.optional()}).default({}),lle=ale.transform(({end:e,start:t,...n})=>({...n,endTimestamp:e,startTimestamp:t}));ule=h.z.object({start:cr.optional(),end:cr.optional(),sort:E_.optional(),cursor:ye.optional()});ple=kx.extend({cursor:ye.optional(),instrumentId:Ae.optional()}),mle=h.z.object({cursor:ye}),hle=h.z.union([ple.transform(({cursor:e,...t})=>({cursor:e,params:xx(t,P0)})),mle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);gle=kx.extend({cursor:ye.optional(),depositStatus:kd.optional(),hash:et.optional()}),yle=h.z.object({cursor:ye}),ble=h.z.union([gle.transform(({cursor:e,...t})=>({cursor:e,params:xx(t,AO)})),yle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);vle=kx.extend({cursor:ye.optional(),withdrawalStatus:xd.optional(),hash:et.optional()}),kle=h.z.object({cursor:ye}),xle=h.z.union([vle.transform(({cursor:e,...t})=>({cursor:e,params:xx(t,AO)})),kle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Tle=kx.extend({cursor:ye.optional()}),Sle=h.z.object({kind:h.z.literal("perpsInternalTransfers"),startTimestamp:cr,endTimestamp:cr,seenKeys:h.z.array(h.z.string())}),Ple=h.z.object({cursor:ye}),Ele=h.z.union([Tle.transform(({cursor:e,...t})=>({cursor:e,params:xx(t,AO)})),Ple.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Ile=_5.extend({cursor:ye.optional()}),_le=h.z.object({cursor:ye}),Cle=h.z.union([Ile.transform(({cursor:e,...t})=>({cursor:e,params:N5(t)})),_le.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Ole=_5.extend({cursor:ye.optional()}),Lle=h.z.object({cursor:ye}),Dle=h.z.union([Ole.transform(({cursor:e,...t})=>({cursor:e,params:N5(t)})),Lle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Ble=h.z.object({kind:h.z.literal("perpsNotifications"),cursor:h.z.string().min(1),sinceSeq:h.z.number().int().nonnegative().optional(),limit:h.z.number().int().positive().optional()}),Mle=h.z.object({sinceSeq:h.z.number().int().nonnegative().optional(),limit:h.z.number().int().positive().optional(),cursor:ye.optional()}),Fle=h.z.object({cursor:ye}),qle=h.z.union([Mle.transform(({cursor:e,...t})=>({cursor:e,params:t})),Fle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Vle=h.z.object({ids:h.z.array(h.z.string().min(1)).min(1)}),jle=h.z.object({upTo:h.z.object({id:h.z.string().min(1),timestamp:h.z.number().int().nonnegative()})}),zle=h.z.union([Vle.transform(({ids:e})=>({ids:e})),jle.transform(({upTo:e})=>({before:Gle(e)}))]);Qle=h.z.object({builder:J.optional()}).default({}),Ax=B($,O,_,C,E);Jle=2160*60*60*1e3,mN=h.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),L5=h.z.object({start:mN.optional(),end:mN.optional(),asOfSequence:mN.optional()}).refine(({start:e,end:t})=>e===void 0||t===void 0||e<=t,{message:"end must not precede start",path:["end"]}).refine(({start:e,end:t})=>e===void 0||t===void 0||t-e<=Jle,{message:"The reporting window must not exceed 90 days",path:["end"]}).default({}),Tx=B($,O,_,C,E);Sx=B($,O,_,C,E);PO=h.z.object({instrumentId:Ae,side:Nt,quantity:Ao,reduceOnly:h.z.boolean().default(!1),clientOrderId:Er.optional()}),tce=PO.extend({price:Ao,timeInForce:h.z.literal(ti.GTC),postOnly:h.z.boolean().default(!1)}),nce=PO.extend({price:Ao.optional(),timeInForce:h.z.literal(ti.IOC),postOnly:h.z.never().optional()}),rce=PO.extend({price:Ao.optional(),timeInForce:h.z.literal(ti.FOK),postOnly:h.z.never().optional()}),EO=h.z.discriminatedUnion("timeInForce",[tce,nce,rce]),A0=h.z.object({triggerPrice:Ao,limitPrice:Ao.optional()}),T0=h.z.object({triggerPrice:Ao}),oce=h.z.union([h.z.object({takeProfit:A0,stopLoss:A0.optional()}),h.z.object({takeProfit:A0.optional(),stopLoss:A0})]),sce=h.z.object({orders:h.z.array(EO).min(1),expiresAt:h.z.number().int().positive().optional()});ace=h.z.intersection(EO,h.z.intersection(oce,h.z.object({clientOrderId:Er.default(U5),expiresAt:h.z.number().int().positive().optional()}))),lce=h.z.intersection(EO,h.z.object({clientOrderId:Er.default(U5),expiresAt:h.z.number().int().positive().optional(),takeProfit:h.z.never().optional(),stopLoss:h.z.never().optional()})),D5=h.z.array(sf).min(1).refine(e=>e.every(t=>t.status==="ok"),"Expected successful Perps order acknowledgements.");pce=h.z.union([h.z.object({takeProfit:T0,stopLoss:T0.optional()}),h.z.object({takeProfit:T0.optional(),stopLoss:T0})]),mce=h.z.intersection(pce,h.z.object({instrumentId:Ae,expiresAt:h.z.number().int().positive().optional()}));TN=4,SN=2e3,fce=100,gce=1e3,yce=h.z.object({maxAttempts:h.z.number().int().positive().default(TN),maxElapsedMs:h.z.number().int().positive().default(SN)}).default({maxAttempts:TN,maxElapsedMs:SN}),E0=h.z.object({expiresAt:h.z.number().int().positive().optional(),retry:h.z.union([h.z.literal(!1),yce]).default({maxAttempts:TN,maxElapsedMs:SN}),signal:h.z.custom(e=>e instanceof AbortSignal,"Expected an AbortSignal.").optional()}),bce=h.z.union([E0.extend({orderId:Cn,clientOrderId:h.z.undefined().optional()}),E0.extend({clientOrderId:Er,orderId:h.z.undefined().optional()})]);vce=h.z.union([E0.extend({orderIds:h.z.array(Cn).min(1),clientOrderIds:h.z.undefined().optional()}),E0.extend({clientOrderIds:h.z.array(Er).min(1),orderIds:h.z.undefined().optional()})]);Sce=h.z.object({instrumentId:Ae.optional(),expiresAt:h.z.number().int().positive().optional()}).default({});Ece=5e3,Rce=h.z.object({cancelAt:h.z.number().int().positive(),expiresAt:h.z.number().int().positive().optional()}).superRefine((e,t)=>{let n=Date.now()+Ece;e.cancelAt<n&&t.addIssue({code:"custom",message:"cancelAt must be at least 5 seconds in the future.",path:["cancelAt"]})}),Px=B(lf,$,O,ue,_,C,E),Ice="auto_cancel_daily_limit_reached";Cce=h.z.object({expiresAt:h.z.number().int().positive().optional()}).default({});Oce=h.z.object({instrumentId:Ae,leverage:h.z.number().int().positive(),crossMargin:h.z.boolean()}),Ex=B(O,ue,_,E);Dce=h.z.object({instrumentId:Ae,amount:Ao}),Rx=B(O,ue,_,E);$ce=3e4,hN=3e4,Vce=2e3,jce=["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications","tpsl"],zce=new Set(["notifications","builderFills"]),Wce=h.z.object({id:h.z.number().int().positive().optional(),data:h.z.unknown().optional()}).passthrough(),fN=h.z.union([of,h.z.array(of)]).transform(e=>Array.isArray(e)?e.find(t=>t.status==="err")??e[0]:e),Ix=B($,O,ue,_,C,E),M5=class{credentials;#e;#t;#r;#s;#n;#o;#i=new mi({heartbeat:new xO});#a=Bd({objectMode:!0});#u=new Map;#l=new Set;#c=new ua;#p=new Map;#d;#m;#y=Promise.resolve();#h;#f=1;#g;constructor(e){this.#e=e.approveBuilderFee,this.#h=e.includeBuilderFills??!1,this.#m=e.builderAttribution===void 0||typeof e.builderAttribution=="string"?void 0:Object.freeze(F(e.builderAttribution,Iae)),this.#d=typeof e.builderAttribution=="string"?F(e.builderAttribution,J):this.#m?.builderAddress,this.#t=new vn({headers:e.headers,resolveHeaders:async()=>this.#T(),root:e.restUrl}),this.#r=e.chainId,this.credentials=e.credentials,this.#s=e.headers,this.#n=e.onClose,this.#o=e.wsUrl}get builderAttribution(){return this.#m}get closed(){return this.#g!==void 0}async connect(){if(this.#d!==void 0&&this.#m===void 0){let e=await X(this.#t.get("/v1/info/builder",{params:new URLSearchParams({address:this.#d})}).andThen(z(Jh)));if(!e.registered||!e.enabled||!e.admissionEnabled)throw new E("Builder attribution is not active for this builder address.");let t=(await this.fetchBuilderApprovals({builder:this.#d})).find(r=>r.builder.toLowerCase()===this.#d?.toLowerCase()),n=h6(e.maxFeeRate,t?.maxFeeRate??"0");this.#m=/[1-9]/.test(n)?Object.freeze({builderAddress:this.#d,feeRate:n}):void 0}await this.#x(!1)}async close(){this.#g===void 0&&(this.#g=this.#P()),await this.#g}[Symbol.asyncIterator](){return this.#a[Symbol.asyncIterator]()}async approveBuilderFee(e){let t=F(e,P5);return this.#b(()=>({...t,builderAddress:t.builderAddress===void 0?this.#d:t.builderAddress}))}async revokeBuilderFee(e){return this.#b(()=>{let t=e??this.#d;if(t===void 0)throw new E("A builder address is required when the session has no active builder attribution.");return{builderAddress:t,maxFeeRate:"0"}})}#b(e){let t=this.#y.catch(()=>{}).then(async()=>{if(this.closed)throw new _("Perps session closed.");if(this.#e===void 0)throw new E("Builder approval requires a session opened with a secure client.");let n=await this.#e(this,e());if(/^0+(?:\.0+)?$/.test(n.maxFeeRate))this.#d?.toLowerCase()===n.builder.toLowerCase()&&(this.#m=void 0,this.#d=void 0);else{let r=await X(this.#t.get("/v1/info/builder",{params:new URLSearchParams({address:n.builder})}).andThen(z(Jh)));this.#d=n.builder;let o=h6(r.maxFeeRate,n.maxFeeRate);this.#m=/[1-9]/.test(o)?Object.freeze({builderAddress:n.builder,feeRate:o}):void 0}return n});return this.#y=t,t}async fetchBuilderApprovals(e){return await Xle(this.#t,e)}listBuilderEarnings(e){return Zle(this.#t,e)}async fetchBuilderEarningsSummary(e){return await ece(this.#t,e)}async fetchBalances(){return await Zae(this.#t)}async fetchPortfolio(){return await ele(this.#t)}async fetchStats(){return await tle(this.#t)}async fetchAccountConfig(e){return await ole(this.#t,e)}async fetchAutoCancelStatus(){return await nle(this.#t)}async fetchOpenOrders(e){return await ile(this.#t,e)}async fetchOrders(e){return await cle(this.#t,e)}listFills(e={}){return dle(this.#t,e)}listFundingPayments(e={}){return fle(this.#t,e)}listDeposits(e={}){return wle(this.#t,e)}listInternalTransfers(e={}){return Rle(this.#t,e)}listWithdrawals(e={}){return Ale(this.#t,e)}listEquityHistory(e){return Nle(this.#t,e)}listPnlHistory(e){return Ule(this.#t,e)}listNotifications(e={}){return Hle(this.#t,e)}async fetchUnreadNotificationsCount(){return await $le(this.#t)}async markNotificationsRead(e){await Wle(this.#t,e)}async placeOrder(e){return await uce(this,e)}async postOrders(e){return await ice(this,e)}async placePositionTpSl(e){return await hce(this,e)}async cancelOrder(e){return await wce(this,e)}async cancelOrders(e){return await PN(this,e)}async cancelAllOrders(e){await Pce(this,e)}async armAutoCancel(e){await _ce(this.#t,(t,n)=>this.#k(t,n),e)}async disarmAutoCancel(e){await Nce(this.#t,(t,n)=>this.#k(t,n),e)}async updateLeverage(e){return await Lce(this,e)}async updateMargin(e){await Uce(this,e)}async#x(e){await this.#i.connect({onConnectionLost:()=>this.#N(),onError:()=>{},onMessage:t=>this.#S(t),onOpen:()=>{},headers:this.#s,url:this.#o}),await this.#A(),await this.#v(),this.#c.resetBackoff(),e&&(this.#p.clear(),this.#a.push({reason:"reconnect",type:"resync"}))}async#A(){await this.#w({id:this.#f++,op:{args:{proxy:this.credentials.proxy,secret:this.credentials.secret},type:"auth"},req:"post"},fN,$ce,"Perps session authentication timed out.")}async#v(){await this.#w({id:this.#f++,req:"sub",chs:jce},fN,hN,"Perps session subscription timed out."),this.#h&&this.#w({id:this.#f++,req:"sub",chs:["builderFills"]},fN,hN,"Perps builder fills subscription timed out.").catch(()=>{})}#T(){return{"POLYMARKET-PROXY":this.credentials.proxy,"POLYMARKET-SECRET":this.credentials.secret}}async executeCommand(e,t){let n=_0(e.op),r=this.#k(e.op,e.expiresAt);return await this.#w({...r,id:this.#f++,op:n,req:"post"},t,hN,"Perps command response timed out.")}async executeCommandWithEvent(e,t,n){let r=this.#L(n),o=this.executeCommand(e,t);o.then(()=>this.#D(r,Vce),()=>{});try{let[s,i]=await Promise.all([o,r.promise]);return[s,i]}finally{this.#E(r)}}async executeDeleteCommand(e){let t=this.#k(e.op,e.expiresAt);return await X(this.#t.del(e.path,{json:{...t,op:_0(e.op)}}).andThen(z(e.responseSchema)))}#k(e,t){let n=Yce(),r=Date.now(),o;try{o=Rae({chainId:this.#r,op:e,privateKey:this.credentials.privateKey,salt:n,timestamp:r})}catch(i){throw ue.fromError(i,"Could not sign the Perps session command")}let s={salt:n,sig:o,ts:r};return t!==void 0&&(s.exp=t),s}async#w(e,t,n,r){let o=Gce(t);this.#u.set(e.id,o);let s=gn(()=>{o.reject(new _(r))},n);try{if(!this.#i.send(e))throw new _("Perps session transport is not open.");return await o.promise}finally{clearTimeout(s),this.#u.delete(e.id)}}async#P(){this.#c.stop(),this.#R(new _("Perps session closed.")),this.#_(new _("Perps session closed.")),this.#a.end(),await this.#i.close(),this.#n(this)}#S(e){if(this.#C(e)||NH.safeParse(e).success)return;let t=OH.safeParse(e);if(!t.success)return;let n=t.data;this.#O(n),this.#I(n)}#C(e){let t=Wce.safeParse(e);if(!t.success||t.data.id===void 0)return!1;let n=this.#u.get(t.data.id);if(n===void 0)return!0;let r=n.schema.safeParse(t.data.data);if(!r.success){let o=IO(t.data.data??t.data);return o!==void 0?n.reject(new O(o.error,{status:200})):n.reject(new _("Perps session unexpected response.")),!0}return Kce(r.data)?n.reject(new O(r.data.error,{status:200})):n.resolve(r.data),!0}#N(){this.#R(new _("Perps session connection closed.")),this.#_(new _("Perps session connection closed.")),this.#g===void 0&&this.#c.schedule({reconnect:()=>this.#x(!0),shouldReconnect:()=>this.#g===void 0})}#R(e){for(let t of this.#u.values())t.reject(e);this.#u.clear()}#O(e){if(zce.has(e.channel))return;let t=this.#p.get(e.channel);this.#p.set(e.channel,e.sequence),!(t===void 0||e.sequence===t+1)&&this.#I({channel:e.channel,previousSequence:t,reason:"sequence_gap",sequence:e.sequence,type:"resync"})}#I(e){this.#U(e),this.#a.push(e)}#L(e){let t,n,r={promise:new Promise((o,s)=>{t=o,n=s}),predicate:e,reject:n,resolve:t};return this.#l.add(r),r}#D(e,t){this.#l.has(e)&&(e.timeout=gn(()=>{this.#E(e),e.reject(new tt("Perps event wait timed out."))},t))}#U(e){for(let t of Array.from(this.#l))t.predicate(e)&&(this.#E(t),t.resolve(e))}#E(e){this.#l.delete(e)&&e.timeout!==void 0&&clearTimeout(e.timeout)}#_(e){for(let t of Array.from(this.#l))this.#E(t),t.reject(e)}};ic=B($,O,_,C,E),ds=h.z.number().int().nonnegative(),F5=1440*60*1e3,Xce=h.z.object({instrumentId:Ae.optional(),category:Xh.optional()}).default({}),_x=ic;Jce=h.z.object({instrumentId:Ae}),Nx=ic;Zce=h.z.object({instrumentId:Ae.optional()}).default({}),Lx=ic;eue=h.z.union([h.z.literal(10),h.z.literal(100),h.z.literal(500),h.z.literal(1e3)]),tue=h.z.object({instrumentId:Ae,depth:eue.default(100)}),Dx=ic;nue=h.z.object({instrumentId:Ae,interval:Hw,start:ds.optional(),end:ds.optional(),cursor:ye.optional()}),rue=h.z.object({cursor:ye}),oue=h.z.union([nue.transform(({cursor:e,...t})=>({cursor:e,params:hue(t)})),rue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Bx=ic;q5=h.z.object({instrumentId:Ae,start:ds.optional(),end:ds.optional()}),sue=q5.extend({cursor:ye.optional()}),iue=h.z.object({cursor:ye}),aue=h.z.union([sue.transform(({cursor:e,...t})=>({cursor:e,params:H5(t)})),iue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),lue=q5.extend({cursor:ye.optional()}),cue=h.z.object({cursor:ye}),Fx=ic;uue=h.z.union([lue.transform(({cursor:e,...t})=>({cursor:e,params:H5(t)})),cue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Hx=ic;Vx=B($,O,_,C);due=h.z.object({kind:h.z.literal("perpsCandles"),instrumentId:Ae,interval:Hw,startTimestamp:ds,endTimestamp:ds}),pue=h.z.object({kind:h.z.literal("perpsFundingHistory"),instrumentId:Ae,startTimestamp:ds,endTimestamp:ds}),mue=h.z.object({kind:h.z.literal("perpsTrades"),instrumentId:Ae,startTimestamp:ds,endTimestamp:ds,seenTradeIds:h.z.array(na)});Aue=h.z.custom(e=>FI(e),"Expected a hex-encoded 32-byte private key."),Tue=h.z.object({proxy:h.z.string().transform(e=>Be(e)),privateKey:Aue,secret:h.z.string().min(1),expiresAt:h.z.number().int().positive()}),Sue=10080*60*1e3,Pue=h.z.strictObject({builderAttribution:J.optional(),includeBuilderFills:h.z.boolean().optional(),expiresIn:h.z.number().int().positive().default(Sue),label:h.z.string().min(1).optional()}),Eue=h.z.strictObject({builderAttribution:J.optional(),includeBuilderFills:h.z.boolean().optional(),credentials:Tue}),Rue=h.z.union([Pue,Eue]),Iue=h.z.object({proxy:h.z.string()}),_ue=Iue.transform(e=>({proxy:Be(e.proxy)})),$5=h.z.bigint().positive().max(lr),Cue=h.z.object({amount:$5,metadata:ur.optional()}),Nue=h.z.object({amount:$5}),Oue=Ao.refine(e=>/^\d+(?:\.\d+)?$/.test(e)&&/[1-9]/.test(e),"Expected a positive fixed-point decimal amount."),Lue=h.z.string().min(1).refine(e=>new TextEncoder().encode(e).byteLength<=64,"Expected a label no longer than 64 UTF-8 bytes."),Due=h.z.object({recipient:J,amount:Oue,label:Lue.optional()}),zx=B($,O,ue,_,C,E),Wx=B($,O,ue,_,C,E),V5=B(E),Gx=B(bt,$,O,ue,_,C,E),Kx=B($,O,ue,_,C,E),Yx=B($,O,ue,_,C,E);Gue=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J.optional(),conditionId:h.z.union([ql,ca(ql,20)]).optional(),status:_$.optional(),eventId:h.z.array(Gt).min(1).optional(),filterType:N$.optional(),filterAmount:h.z.number().min(0).optional(),includeArchived:h.z.boolean().optional(),sortBy:C$.optional(),sortDirection:m0.optional(),window:L0.optional()}).refine(e=>e.user!==void 0||e.conditionId,{message:"Provide user or conditionId",path:["user"]}).refine(e=>e.user!==void 0||!Array.isArray(e.conditionId)||e.conditionId.length===1,{message:"Without user, provide exactly one conditionId",path:["conditionId"]}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}).refine(e=>e.user!==void 0||e.eventId===void 0,{message:"eventId requires user",path:["eventId"]}).refine(e=>!(e.includeArchived&&e.status==="CLOSED"),{message:"includeArchived does not apply to CLOSED positions",path:["includeArchived"]}).refine(e=>e.status!==ai.RedeemableLost||e.user!==void 0,{message:"REDEEMABLE_LOST requires user",path:["user"]}),tA=B($,O,_,C,E);Kue=h.z.union([Nd,h.z.tuple([Nd],Nd).refine(e=>e.length===1||!e.includes(ii.Redeemable),{message:"REDEEMABLE must be the sole status value"})]),Yue=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([Zt,ca(Zt,20)]).optional(),status:Kue.optional(),sortBy:O$.optional(),sortDirection:m0.optional(),updatedAfter:gf.optional(),updatedBefore:gf.optional()}),Que=Yue.refine(e=>e.updatedBefore===void 0||e.updatedAfter===void 0||e.updatedBefore>=e.updatedAfter,{message:"updatedBefore must not precede updatedAfter",path:["updatedBefore"]}),nA=B($,O,_,C,E);Xue=h.z.object({user:J,conditionIds:ca(ql,20).optional()}),rA=B($,O,_,C,E);Jue=h.z.object({user:J}),oA=B($,O,_,C,E);Zue=h.z.object({user:J,interval:YC.optional(),fidelity:d0.optional()}),sA=B($,O,_,C,E);ede=h.z.object({user:J,window:L0.optional()}),iA=B($,O,_,C,E);tde=h.z.object({user:h.z.string()}),aA=B($,O,_,C,E);lA=B($,O,_,C,E),G5=h.z.object({amount:h.z.bigint().min(0n),conditionId:xe,metadata:ur.optional()}),K5=lA;Y5=h.z.object({amount:h.z.bigint().positive(),legs:h.z.array(Xe).min(1).max(50),metadata:ur.optional()}),Q5=lA;rde=h.z.union([G5.extend({legs:h.z.never().optional()}),Y5.extend({conditionId:h.z.never().optional()})]);Vd=B(bt,$,O,ue,tt,en,_,C,E),X5=Vd;Z5=Vd;pA=B($,O,_,C,E),tV=h.z.object({amount:h.z.union([h.z.bigint().positive(),h.z.literal("max")]),conditionId:xe,metadata:ur.optional()}),nV=pA;rV=h.z.object({amount:h.z.union([h.z.bigint().positive(),h.z.literal("max")]),legs:h.z.array(Xe).min(1).max(50),metadata:ur.optional()}),oV=pA;ode=h.z.union([tV.extend({legs:h.z.never().optional()}),rV.extend({conditionId:h.z.never().optional()})]);jd=B(bt,$,O,ue,tt,en,_,C,E),sV=jd;aV=jd;gA=B($,O,_,C,E),cV=h.z.object({conditionId:xe,marketId:h.z.never().optional(),amount:h.z.never().optional(),positionId:h.z.never().optional(),metadata:ur.optional()}),uV=h.z.object({conditionId:h.z.never().optional(),marketId:Ji,amount:h.z.never().optional(),positionId:h.z.never().optional(),metadata:ur.optional()}),sde=h.z.union([cV,uV]),dV=gA;pV=h.z.object({positionId:Xe,conditionId:h.z.never().optional(),marketId:h.z.never().optional(),metadata:ur.optional()});mV=gA;ide=h.z.union([cV,uV,pV]);bA=B(bt,$,O,ue,tt,en,_,C,E);dde=h.z.object({address:h.z.string()}),vA=B($,O,_,C,E);ac=class extends Ct{name="RfqQuoteRejectedError";code;errorId;rfqId;constructor(e,t){super(e,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId}},xA=B(Yr,ac,ue,tt,_,E),lc=class extends Ct{name="RfqCancelQuoteRejectedError";code;errorId;rfqId;quoteId;constructor(e,t){super(e,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId,this.quoteId=t.quoteId}},AA=B(Yr,lc,tt,_),cc=class extends Ct{name="RfqConfirmationRejectedError";code;errorId;rfqId;quoteId;constructor(e,t){super(e,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId,this.quoteId=t.quoteId}},TA=B(Yr,cc,tt,_),SA=B(Yr,_,E);UO="/v1/builder/rfq/requests",pde=3e4,mde=3e4,hde=3e4,fde=500,gde=3e4,yde=1e3,bde="0x0000000000000000000000000000000000000000000000000000000000000000",ms=class extends Ct{name="RfqRequestRejectedError";status;code;constructor(e,t){super(e,t),this.status=t.status,this.code=t.code}};wde=new Set(Object.values(li));y6=h.z.array(h.z.string().regex(/^\d+$/,"Leg position IDs must be numeric strings.").transform(e=>BigInt(e).toString())).min(2,"Combo requests require at least 2 legs.").max(50,"Combo requests allow at most 50 legs.").refine(e=>new Set(e).size===e.length,"Leg position IDs must not contain duplicates.").transform(e=>[...e].sort((t,n)=>{let r=BigInt(t),o=BigInt(n);return r<o?-1:r>o?1:0})),C0=h.z.union([h.z.number(),h.z.string()]).transform((e,t)=>{let n=/^(\d+)(?:\.(\d*))?$/.exec(String(e));if(n===null)return t.addIssue({code:"custom",message:"Value must be a valid decimal."}),h.z.NEVER;let[,r="",o=""]=n;if(o.length>6)return t.addIssue({code:"custom",message:"Value must have at most 6 decimal places."}),h.z.NEVER;let s=vde(r,o);return s<=0n?(t.addIssue({code:"custom",message:"Value must be greater than 0."}),h.z.NEVER):s.toString()});kde=h.z.discriminatedUnion("direction",[h.z.object({amount:C0,direction:h.z.literal(Ue.BUY),legPositionIds:y6,side:h.z.literal(Eo.Yes).optional()}),h.z.object({direction:h.z.literal(Ue.SELL),legPositionIds:y6,side:h.z.literal(Eo.Yes).optional(),size:C0})]),EA=B($,ms,_,C,E);Tde=Nt,Sde=h.z.object({blendedPrice:h.z.string(),builderCode:h.z.string().regex(/^0x[0-9a-fA-F]{64}$/,"builderCode must be a 32-byte hex string.").transform(kw),direction:Tde,expiresAt:h.z.number().int().nonnegative(),makerAmount:C0.transform(Sl),netReceive:h.z.string().optional(),positionId:h.z.string().regex(/^\d+$/,"positionId must be a numeric string.").transform(Aw),quoteId:h.z.string().min(1).transform(Tw),rfqId:h.z.string().min(1).transform(md),takerAmount:C0.transform(Sl),totalRequired:h.z.string()}),IA=B(bt,$,ms,ue,tt,_,C,E);Cde=h.z.object({pollingIntervalMs:h.z.number().int().positive().optional(),rfqId:h.z.string().min(1).transform(md),timeoutMs:h.z.number().int().positive().optional()}),CA=B($,ms,tt,_,C,E);Nde=h.z.object({rfqId:h.z.string().min(1).transform(md)}),OA=B($,ms,_,C,E);zd=(e=>(e.Volume="volume",e.Volume24Hr="volume_24hr",e.Liquidity="liquidity",e.Competitive="competitive",e.ClosedTime="closed_time",e.StartDate="start_date",e.EndDate="end_date",e))(zd||{}),b6=100,Ode=h.z.object({q:h.z.string().trim().min(1),ascending:h.z.boolean().optional(),cache:h.z.boolean().optional(),cursor:ye.optional(),eventsStatus:h.z.string().min(1).optional(),eventsTag:h.z.array(h.z.string()).optional(),excludeTagIds:h.z.array(h.z.number().int()).optional(),keepClosedMarkets:h.z.number().int().optional(),optimized:h.z.boolean().optional(),pageSize:Ot.default(10),presets:h.z.array(h.z.string()).optional(),recurrence:h.z.enum(["daily","weekly","monthly"]).optional(),searchProfiles:h.z.boolean().optional(),searchTags:h.z.boolean().optional(),sort:h.z.enum(zd).optional()}),DA=B(Ol,$,O,_,C,E);Dde=h.z.object({ascending:h.z.boolean().optional(),closed:h.z.boolean().optional(),cursor:ye.optional(),excludeEvents:h.z.boolean().optional(),locale:h.z.string().optional(),order:h.z.string().optional(),pageSize:Ot.max(50).default(20),recurrence:h.z.enum(["daily","weekly","monthly"]).optional(),slug:h.z.array(h.z.string()).optional()}),Ude=h.z.object({id:h.z.string(),locale:h.z.string().optional()}),BA=B($,O,_,C,E);FA=B($,O,_,C,E);HA=B($,O,ue,_,C,E);Bde=[yo.ALL],Mde=4315*60*60,wV=300*1e3,Fde=h.z.object({address:J,idempotencyKey:h.z.string().trim().min(1).optional(),scopes:h.z.array(Ih).min(1).default(Bde)}).superRefine((e,t)=>{Wt(e.address,ts)&&t.addIssue({code:"custom",message:"Session key address must not be the zero address.",path:["address"]}),e.scopes.includes(yo.ALL)&&e.scopes.some(n=>n!==yo.ALL)&&t.addIssue({code:"custom",message:"Session key scope ALL cannot be combined with another scope.",path:["scopes"]})}).transform(e=>({...e,address:Be(e.address.toLowerCase())})),$A=B(bt,$,O,ue,tt,en,_,C,E);qde=h.z.object({address:J,idempotencyKey:h.z.string().trim().min(1).optional()}).superRefine((e,t)=>{Wt(e.address,ts)&&t.addIssue({code:"custom",message:"Session key address must not be the zero address.",path:["address"]})}).transform(e=>({...e,address:Be(e.address.toLowerCase())})),jA=B(bt,$,O,ue,tt,en,_,C,E);WA=B($,O,_,C);KA=B($,O,_,C);jde=h.z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._:/-]+$/),w6=h.z.string().max(64).regex(/^[a-z0-9]+usd$/,{error:"Use a canonical lowercase USD pair such as btcusd. Slash-separated symbols and USDT pairs are not supported."}),vV=(e=>(e.Update="update",e.Subscribe="subscribe",e))(vV||{}),zde=h.z.discriminatedUnion("topic",[h.z.strictObject({topic:h.z.literal("prices.crypto"),symbols:h.z.array(w6).min(1)}),h.z.strictObject({topic:h.z.literal("prices.crypto.twap"),symbols:h.z.array(w6).min(1)}),h.z.strictObject({topic:h.z.literal("prices.equity"),symbol:jde,types:h.z.array(h.z.enum(vV)).optional()})]);QA=B(_,E,O,Yr),kV=(e=>(e.Market="market",e.User="user",e.Sports="sports",e.Crypto="prices.crypto",e.Twap="prices.crypto.twap",e.Equity="prices.equity",e.Comments="comments",e.LegacyBinance="prices.crypto.binance",e.LegacyChainlink="prices.crypto.chainlink",e.LegacyTwap="prices.crypto.chainlink.twap",e.LegacyEquity="prices.equity.pyth",e.PerpsTrades="perps.trades",e.PerpsBbo="perps.bbo",e.PerpsBook="perps.book",e.PerpsCandles="perps.candles",e.PerpsTickers="perps.tickers",e.PerpsStatistics="perps.statistics",e))(kV||{}),Gde=h.z.object({topic:h.z.enum(kV)}),Kde=h.z.object({topic:h.z.literal("prices.crypto.chainlink.twap"),windowSeconds:h.z.union([h.z.literal(30),h.z.literal(60)]),symbols:h.z.array(h.z.string()).optional()}),Yde=h.z.union([h.z.object({topic:h.z.literal("market"),assetIds:h.z.array(h.z.string()),tokenIds:h.z.never().optional(),customFeatureEnabled:h.z.boolean().optional()}),h.z.object({topic:h.z.literal("market"),assetIds:h.z.never().optional(),tokenIds:h.z.array(h.z.string()),customFeatureEnabled:h.z.boolean().optional()})]);Jde=h.z.object({ascending:h.z.boolean().optional(),cursor:ye.optional(),includeTemplate:h.z.boolean().optional(),isCarousel:h.z.boolean().optional(),locale:h.z.string().optional(),order:h.z.string().optional(),pageSize:Ot.max(100).default(20)}),Zde=h.z.union([h.z.object({id:h.z.string(),includeTemplate:h.z.boolean().optional(),locale:h.z.string().optional()}),h.z.object({slug:h.z.string(),locale:h.z.string().optional()})]),epe=h.z.object({id:h.z.string(),omitEmpty:h.z.boolean().optional(),status:h.z.enum(["active","closed","all"]).optional()}),tpe=h.z.object({slug:h.z.string()}),npe=h.z.object({id:h.z.string(),locale:h.z.string().optional(),omitEmpty:h.z.boolean().optional(),status:h.z.enum(["active","closed","all"]).optional()}),rpe=h.z.object({locale:h.z.string().optional(),slug:h.z.string(),omitEmpty:h.z.boolean().optional(),status:h.z.enum(["active","closed","all"]).optional()}),XA=B($,O,_,C,E);ZA=B($,O,_,C,E);tT=B($,O,_,C,E);rT=B($,O,_,C,E);ope=h.z.object({abbreviation:h.z.array(h.z.string()).optional(),ascending:h.z.boolean().optional(),cursor:ye.optional(),league:h.z.array(h.z.string()).optional(),name:h.z.array(h.z.string()).optional(),order:h.z.string().optional(),pageSize:Ot.max(100).default(20),providerId:h.z.array(h.z.number().int()).optional()}),sT=B($,O,_,C,E);spe=h.z.object({amount:h.z.bigint(),metadata:ur.optional(),recipientAddress:J,tokenAddress:J}),xV=B(E);aT=B(bt,$,O,ue,_,C,E)});var KV={};fr(KV,{AcceptComboQuoteError:()=>IA,ActivityType:()=>p0,ApproveErc1155ForAllError:()=>wv,ApproveErc20Error:()=>bv,ApprovePerpsBuilderFeeError:()=>vx,ArmPerpsAutoCancelError:()=>Px,AssetType:()=>sa,AuthorizeSessionKeyError:()=>$A,AutoCancelDailyLimitError:()=>lf,BiggestWinnerKind:()=>Ql,BuilderVolumeInterval:()=>Kl,CancelAllError:()=>zk,CancelMarketOrdersError:()=>Gk,CancelOrderError:()=>Hk,CancelOrdersError:()=>Vk,CancelledSigningError:()=>bt,CollateralReturnKnownOperationKind:()=>Dd,CombinatorialPrepareConditionCallError:()=>J6,ComboAcceptFailureReason:()=>Ro,ComboActivityType:()=>Wl,ComboKnownStatus:()=>Iw,ComboPositionSortBy:()=>Vl,ComboPositionStatus:()=>ii,ComboQuoteUnavailableReason:()=>ci,CommentParentEntityType:()=>Rh,ConnectionLostError:()=>Yr,CreateLimitOrderError:()=>fx,CreateMarketOrderError:()=>px,CreateSecureClientError:()=>Ame,CtfMergePositionsCallError:()=>G6,CtfRedeemPositionsCallError:()=>K6,CtfSplitPositionCallError:()=>W6,DepositToPerpsError:()=>Gx,DownloadAccountingSnapshotError:()=>aA,DropNotificationsError:()=>j0,Erc20ApprovalCallError:()=>V6,Erc20TransferCallError:()=>j6,EstimateMarketPriceError:()=>Qk,ExecuteCollateralReturnPlanError:()=>ek,FetchBuilderVolumeError:()=>vk,FetchClosedOnlyModeError:()=>D0,FetchCommentsByIdError:()=>ok,FetchEventError:()=>uk,FetchEventLiveVolumeError:()=>gk,FetchEventTagsError:()=>pk,FetchLastTradePriceError:()=>Vv,FetchLastTradePricesError:()=>zv,FetchMarketError:()=>Ck,FetchMarketTagsError:()=>Ok,FetchMidpointError:()=>Rv,FetchMidpointsError:()=>_v,FetchNotificationsError:()=>$0,FetchOpenInterestError:()=>Fk,FetchOrderBookError:()=>Uv,FetchOrderBooksError:()=>Bv,FetchOrderError:()=>F0,FetchOrderScoringError:()=>G0,FetchOrdersScoringError:()=>Y0,FetchPerpsBookError:()=>Dx,FetchPerpsBuilderApprovalsError:()=>Ax,FetchPerpsBuilderEarningsSummaryError:()=>Sx,FetchPerpsBuilderStatusError:()=>bx,FetchPerpsFeesError:()=>Vx,FetchPerpsInstrumentsError:()=>_x,FetchPerpsTickerError:()=>Nx,FetchPerpsTickersError:()=>Lx,FetchPortfolioValueError:()=>rA,FetchPriceError:()=>Nv,FetchPricesError:()=>Lv,FetchPublicProfileError:()=>vA,FetchRelatedTagResourcesError:()=>rT,FetchRelatedTagsError:()=>tT,FetchResolutionsError:()=>hk,FetchRewardPercentagesError:()=>rv,FetchRfqStatusError:()=>OA,FetchSeriesError:()=>FA,FetchSessionKeysError:()=>HA,FetchSportsMarketTypesError:()=>KA,FetchSpreadError:()=>Fv,FetchSpreadsError:()=>Hv,FetchTagError:()=>ZA,FetchTotalEarningsForUserForDayError:()=>Z0,FetchTraderLeaderboardStandingError:()=>Tk,FetchTradingApprovalsStateError:()=>vv,FetchUserPnlError:()=>sA,FetchUserStatsError:()=>oA,FetchUserVolumeError:()=>iA,InsufficientLiquidityError:()=>So,LeaderboardWindow:()=>Gl,ListAccountTradesError:()=>H0,ListActivityError:()=>av,ListBiggestWinnersError:()=>Sk,ListBuilderLeaderboardError:()=>bk,ListBuilderTradesError:()=>Pv,ListComboActivityError:()=>lv,ListComboMarketsError:()=>Ik,ListComboPositionsError:()=>nA,ListCommentsByUserAddressError:()=>ik,ListCommentsError:()=>nk,ListCurrentRewardsError:()=>Gv,ListEventsError:()=>lk,ListMarketHoldersError:()=>Dk,ListMarketRewardsError:()=>Yv,ListMarketsError:()=>Rk,ListOpenOrdersError:()=>B0,ListPerpsBuilderEarningsError:()=>Tx,ListPerpsCandlesError:()=>Bx,ListPerpsFundingHistoryError:()=>Fx,ListPerpsTradesError:()=>Hx,ListPositionsError:()=>tA,ListPriceHistoryError:()=>Bk,ListSeriesError:()=>BA,ListSportsError:()=>WA,ListTagsError:()=>XA,ListTeamsError:()=>sT,ListTraderLeaderboardError:()=>xk,ListTradesError:()=>sv,ListUserEarningsAndMarketsConfigError:()=>tv,ListUserEarningsForDayError:()=>X0,MAX_UINT256:()=>lr,MergePositionsError:()=>jd,NotificationType:()=>t0,OpenPerpsSessionError:()=>zx,OpenRfqSessionError:()=>SA,OperationAbortedError:()=>Xw,OrderPostStatus:()=>n0,OrderResponseErrorCode:()=>r0,OrderSide:()=>Ue,OrderType:()=>cn,PaginationLimitError:()=>Ol,PerpsCancelRetryError:()=>Jw,PerpsDepositCallError:()=>z6,PerpsDepositStatus:()=>Gh,PerpsInstrumentCategory:()=>zh,PerpsInstrumentType:()=>jh,PerpsInternalTransferDirection:()=>Kh,PerpsKlineInterval:()=>Yh,PerpsKnownCancelOrderErrorCode:()=>Sd,PerpsKnownInternalTransferType:()=>qw,PerpsKnownWithdrawalStatus:()=>Fw,PerpsLiquidityRole:()=>Zh,PerpsMarginType:()=>nf,PerpsNotificationOrderType:()=>tf,PerpsNotificationType:()=>ef,PerpsOrderStatus:()=>rf,PerpsSide:()=>Wh,PerpsSortDirection:()=>Qh,PerpsTimeInForce:()=>ti,PlaceLimitOrderError:()=>gx,PlaceMarketOrderError:()=>mx,PlanCollateralReturnError:()=>Jv,PositionFilterType:()=>$l,PositionSortBy:()=>Hl,PositionStatus:()=>ai,PostOrderError:()=>Zk,PostOrdersError:()=>ex,PriceHistoryInterval:()=>Po,ProtocolVersion:()=>ta,RateLimitError:()=>$,RealtimeKnownErrorCode:()=>Ed,RedeemPositionsError:()=>bA,RequestComboQuoteError:()=>EA,RequestRejectedError:()=>O,ResolutionMarketType:()=>Jl,ResolutionReporter:()=>ec,ResolutionSource:()=>Zl,ResolutionStatus:()=>Xl,RevokePerpsBuilderFeeError:()=>Ix,RevokePerpsCredentialsError:()=>Wx,RevokeSessionKeyError:()=>jA,RfqCancelQuoteError:()=>AA,RfqCancelQuoteRejectedError:()=>lc,RfqConfirmationDecision:()=>cs,RfqConfirmationError:()=>TA,RfqConfirmationRejectedError:()=>cc,RfqDirection:()=>Nn,RfqExecutionStatus:()=>us,RfqKnownErrorCode:()=>Cr,RfqQuoteError:()=>xA,RfqQuoteRejectedError:()=>ac,RfqRejectionCode:()=>li,RfqRequestRejectedError:()=>ms,RfqRequestedSizeUnit:()=>Qr,RfqSide:()=>Eo,RfqStatus:()=>mn,RouterMergeCallError:()=>Q6,RouterRedeemCallError:()=>X6,RouterSplitCallError:()=>Y6,SearchError:()=>DA,SearchSort:()=>zd,SessionKeyKnownScope:()=>yo,SetupGaslessWalletError:()=>Tme,SetupTradingApprovalsError:()=>kv,SignatureType:()=>Rr,SignerType:()=>CN,SigningError:()=>ue,SortDirection:()=>Ml,SplitPositionError:()=>Vd,SubscribeError:()=>QA,TeamOrdering:()=>Fh,TimeoutError:()=>tt,TipSide:()=>Bl,TradeFilterType:()=>Fl,TraderLeaderboardSort:()=>Yl,TradingRestriction:()=>PC,TransactionFailedError:()=>en,TransferErc20Error:()=>aT,TransferPerpsCollateralError:()=>Yx,TransportError:()=>_,UnexpectedResponseError:()=>C,UpdatePerpsLeverageError:()=>Ex,UpdatePerpsMarginError:()=>Rx,UserInputError:()=>E,UserPnlFidelity:()=>zl,UserPnlInterval:()=>jl,WaitForComboFillError:()=>CA,WaitForOrderFillSettlementError:()=>ux,WaitForTransactionError:()=>Z6,WalletType:()=>Se,WebSocketKnownCloseCode:()=>SC,WithdrawFromPerpsError:()=>Kx,accountActions:()=>$O,allActions:()=>UV,analyticsActions:()=>VO,authorizeSessionSignerCall:()=>HN,buildHmacSignature:()=>MV,combinatorialPrepareConditionCall:()=>dv,createPublicClient:()=>GV,createSecureClient:()=>Sme,ctfMergePositionsCall:()=>zN,ctfRedeemPositionsCall:()=>WN,ctfSplitPositionCall:()=>jN,dataActions:()=>jO,decodeErc1155BalanceOfBatchResult:()=>Rf,decodeErc1155BalanceOfResult:()=>qN,decodeErc1155IsApprovedForAllResult:()=>MN,decodeErc20AllowanceResult:()=>UN,discoveryActions:()=>zO,encodeProxyCall:()=>KN,encodeSafeMultisendCall:()=>YN,erc1155ApprovalForAllCall:()=>bf,erc1155BalanceOfBatchCall:()=>Ef,erc1155BalanceOfCall:()=>FN,erc1155IsApprovedForAllCall:()=>BN,erc20AllowanceCall:()=>DN,erc20ApprovalCall:()=>yf,erc20TransferCall:()=>S0,expectTransactionHandle:()=>bn,forkEnvironmentConfig:()=>BV,makeErrorGuard:()=>B,perpsActions:()=>WO,perpsDepositCall:()=>VN,preproduction:()=>gpe,production:()=>QO,relayerApiKey:()=>cpe,remoteBuilderSigning:()=>lpe,revokeSessionSignerCall:()=>$N,rewardsActions:()=>GO,rfqActions:()=>OV,routerMergeCall:()=>uv,routerRedeemCall:()=>wf,routerSplitCall:()=>cv,sessionKeyActions:()=>LV,subscriptionsActions:()=>KO,tradingActions:()=>DV,walletActions:()=>YO});function lpe(e){return new upe(e)}function cpe(e){return new dpe(e)}function ppe(e){let t={chainId:e.chainId,name:"ClobAuthDomain",version:"1"};return{domain:t,message:{address:e.address,message:"This message attests that I control the given wallet",nonce:e.nonce??0,timestamp:`${e.timestamp}`},primaryType:"ClobAuth",types:{EIP712Domain:fo.extractEip712DomainTypes(t),ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function mpe(e){return{listPositions:$f.bind(null,e),listComboPositions:Vf.bind(null,e),fetchPortfolioValue:jf.bind(null,e),fetchTraderLeaderboardStanding:Df.bind(null,e),fetchUserStats:zf.bind(null,e),fetchUserPnl:Wf.bind(null,e),fetchUserVolume:Gf.bind(null,e),downloadAccountingSnapshot:Kf.bind(null,e),listActivity:Sf.bind(null,e),listComboActivity:Pf.bind(null,e)}}function hs(e,t={}){return t===null||typeof t!="object"||Array.isArray(t)?t:{...t,user:t.user===void 0?e.account.wallet:t.user}}function $O(e){let t=mpe(e);return e.isPublicClient()?t:{...t,listPositions:n=>$f(e,hs(e,n)),listComboPositions:n=>Vf(e,hs(e,n)),fetchPortfolioValue:n=>jf(e,hs(e,n)),fetchTraderLeaderboardStanding:n=>Df(e,hs(e,n)),fetchUserStats:n=>zf(e,hs(e,n)),fetchUserPnl:n=>Wf(e,hs(e,n)),fetchUserVolume:n=>Gf(e,hs(e,n)),downloadAccountingSnapshot:n=>Kf(e,hs(e,n)),listActivity:n=>Sf(e,hs(e,n)),listComboActivity:n=>Pf(e,hs(e,n)),listAccountTrades:Tf.bind(null,e),fetchNotifications:V0.bind(null,e),dropNotifications:z0.bind(null,e),fetchClosedOnlyMode:U0.bind(null,e)}}function VO(e){return{listBuilderTrades:Ev.bind(null,e),listBuilderLeaderboard:wk.bind(null,e),fetchBuilderVolume:kk.bind(null,e),listTraderLeaderboard:Ak.bind(null,e),listBiggestWinners:Pk.bind(null,e)}}function jO(e){return{fetchEventLiveVolume:yk.bind(null,e),fetchResolutions:fk.bind(null,e),fetchMidpoint:Iv.bind(null,e),fetchMidpoints:Cv.bind(null,e),fetchPrice:Ov.bind(null,e),fetchPrices:Dv.bind(null,e),fetchOrderBook:Hd.bind(null,e),fetchOrderBooks:Mv.bind(null,e),fetchSpread:qv.bind(null,e),fetchSpreads:$v.bind(null,e),fetchLastTradePrice:jv.bind(null,e),fetchLastTradePrices:Wv.bind(null,e),listPriceHistory:Mk.bind(null,e),estimateMarketPrice:Xk.bind(null,e),fetchOpenInterest:qk.bind(null,e),listMarketHolders:Uk.bind(null,e),listTrades:iv.bind(null,e)}}function zO(e){return{listEvents:ck.bind(null,e),fetchEvent:dk.bind(null,e),fetchEventTags:mk.bind(null,e),listMarkets:Uf.bind(null,e),listComboMarkets:_k.bind(null,e),fetchMarket:Nk.bind(null,e),fetchMarketTags:Lk.bind(null,e),listSeries:MA.bind(null,e),fetchSeries:qA.bind(null,e),listMarketClarifications:Ek.bind(null,e),listTags:JA.bind(null,e),fetchTag:eT.bind(null,e),fetchRelatedTags:nT.bind(null,e),fetchRelatedTagResources:oT.bind(null,e),search:UA.bind(null,e),listSports:GA.bind(null,e),fetchSportsMarketTypes:YA.bind(null,e),listTeams:iT.bind(null,e),fetchPublicProfile:kA.bind(null,e),listComments:rk.bind(null,e),fetchCommentsById:sk.bind(null,e),listCommentsByUserAddress:ak.bind(null,e)}}function WO(e){let t={fetchPerpsBuilderStatus:wx.bind(null,e),fetchPerpsBook:n=>Ux(e,n),fetchPerpsFees:()=>jx(e),fetchPerpsInstruments:n=>Cx(e,n),fetchPerpsTicker:n=>Ox(e,n),fetchPerpsTickers:n=>Hf(e,n),listPerpsCandles:n=>Mx(e,n),listPerpsFundingHistory:n=>qx(e,n),listPerpsTrades:n=>$x(e,n)};return e.isSecureClient()?{...t,depositToPerps:n=>Jx(e,n),openPerpsSession:n=>Qx(e,n),revokePerpsCredentials:n=>Xx(e,n),transferPerpsCollateral:eA.bind(null,e),withdrawFromPerps:n=>Zx(e,n)}:t}function hpe(e){return{listCurrentRewards:Kv.bind(null,e),listMarketRewards:Qv.bind(null,e)}}function GO(e){let t=hpe(e);return e.isPublicClient()?t:{...t,fetchOrderScoring:K0.bind(null,e),fetchOrdersScoring:Q0.bind(null,e),listUserEarningsForDay:J0.bind(null,e),fetchTotalEarningsForUserForDay:ev.bind(null,e),listUserEarningsAndMarketsConfig:nv.bind(null,e),fetchRewardPercentages:ov.bind(null,e)}}function OV(e){return{openRfqSession(){return PA(e)},requestComboQuote(t){return RA(e,t)},acceptComboQuote(t){return _A(e,t)},waitForComboFill(t){return NA(e,t)}}}function LV(e){return{authorizeSessionKey:VA.bind(null,e),fetchSessionKeys:Wd.bind(null,e),revokeSessionKey:zA.bind(null,e)}}function KO(e){return e.isSecureClient()?{subscribe(t){return Qf(e,t)}}:{subscribe(t){return Qf(e,t)}}}function DV(e){return{createMarketOrder:Mf.bind(null,e),placeMarketOrder:hx.bind(null,e),createLimitOrder:Ff.bind(null,e),placeLimitOrder:yx.bind(null,e),postOrder:$d(e),postOrders:tx(e),waitForOrderFillSettlement:dx.bind(null,e),cancelOrder:$k.bind(null,e),cancelOrders:jk.bind(null,e),cancelAll:Wk.bind(null,e),cancelMarketOrders:Kk.bind(null,e),listOpenOrders:M0.bind(null,e),fetchOrder:q0.bind(null,e)}}function fpe(e){return{fetchTradingApprovalsState:Lf.bind(null,e)}}function YO(e){let t=fpe(e);return e.isPublicClient()?t:{...t,fetchTradingApprovalsState:()=>Lf(e,{user:e.account.wallet}),setupTradingApprovals:xv.bind(null,e),approveErc20:Nf.bind(null,e),approveErc1155ForAll:Of.bind(null,e),transferErc20:lT.bind(null,e),splitPosition:dA.bind(null,e),mergePositions:fA.bind(null,e),redeemPositions:wA.bind(null,e),planCollateralReturn:Zv.bind(null,e),executeCollateralReturnPlan:tk.bind(null,e)}}function UV(e){return e.isSecureClient()?{...$O(e),...VO(e),...jO(e),...zO(e),...WO(e),...GO(e),...OV(e),...LV(e),...KO(e),...DV(e),...YO(e)}:{...$O(e),...VO(e),...jO(e),...zO(e),...WO(e),...GO(e),...KO(e),...YO(e)}}function BV(e,t=QO){return{...t,...e,walletDerivation:{...t.walletDerivation,...e.walletDerivation},contracts:{...t.contracts,...e.contracts},clob:{...Gd(t.clob,e.clob),market:Xf(t.clob.market,e.clob?.market),user:Xf(t.clob.user,e.clob?.user)},relayer:Gd(t.relayer,e.relayer),gamma:Gd(t.gamma,e.gamma),data:Gd(t.data,e.data),combos:{...AV(t.combos,e.combos),builderGateway:Gd(t.combos.builderGateway,e.combos?.builderGateway),collateralReturn:Gd(t.combos.collateralReturn,e.combos?.collateralReturn)},perps:AV(t.perps,e.perps),realtime:Xf(t.realtime,e.realtime),rtds:Xf(t.rtds,e.rtds),sports:Xf(t.sports,e.sports)}}function Gd(e,t){return{...e,...t,headers:XO(e.headers,t?.headers)}}function Xf(e,t){return{...e,...t,headers:XO(e.headers,t?.headers)}}function AV(e,t){return{...e,...t,headers:XO(e.headers,t?.headers)}}function XO(e,t){if(!(e===void 0&&t===void 0))return{...e,...t}}async function MV(e,t,n,r,o){let s=`${t}${n}${r}`;o!==void 0&&(s+=o);let i=await globalThis.crypto.subtle.importKey("raw",ype(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(s));return wpe(bpe(a))}function ype(e){let t=e.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)r[o]=n.charCodeAt(o);return r.buffer}function bpe(e){let t=new Uint8Array(e),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function wpe(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}function Zf(e,t){let n;return{close:()=>(n===void 0&&(n=Promise.resolve(e.return()).then(()=>t())),n),[Symbol.asyncIterator](){return e[Symbol.asyncIterator]()}}}function TV(e,t,n){let r=dT(n.assetsIds,t.assetsIds),o=dT(t.assetsIds,n.assetsIds);r.length>0&&e(PV(r,n.customFeatureEnabled));let s=n.assetsIds[0];r.length===0&&t.customFeatureEnabled!==n.customFeatureEnabled&&s!==void 0&&e(PV([s],n.customFeatureEnabled)),o.length>0&&e(Ape(o))}function SV(e,t,n){if(n.includeAllMarkets){!t.includeAllMarkets&&t.markets.length>0&&e(RV(t.markets));return}if(t.includeAllMarkets){n.markets.length>0&&e(EV(n.markets));return}let r=dT(n.markets,t.markets),o=dT(t.markets,n.markets);r.length>0&&e(EV(r)),o.length>0&&e(RV(o))}function vpe(e){let t=new Set,n=!1;for(let{subscription:r}of e){for(let o of r.assetIds??r.tokenIds)t.add(o);n||=r.customFeatureEnabled===!0}return{assetsIds:Array.from(t),customFeatureEnabled:n}}function kpe(e){let t=!1,n=new Set;for(let{subscription:r}of e){if(FV(r)){t=!0;continue}for(let o of r.markets??[])n.add(o)}return{includeAllMarkets:t,markets:t?[]:Array.from(n)}}function xpe(e){return{assets_ids:e.assetsIds,custom_feature_enabled:e.customFeatureEnabled,type:"market"}}function PV(e,t){return{assets_ids:e,custom_feature_enabled:t,operation:"subscribe"}}function Ape(e){return{assets_ids:e,operation:"unsubscribe"}}function Tpe(e,t){let n={auth:{apiKey:t.key,passphrase:t.passphrase,secret:t.secret},type:"user"};return e.includeAllMarkets||(n.markets=e.markets),n}function EV(e){return{markets:e,operation:"subscribe"}}function RV(e){return{markets:e,operation:"unsubscribe"}}function Spe(e){let t=e.assetIds??e.tokenIds;return n=>{switch(n.type){case"price_change":return n.payload.priceChanges.some(r=>t.includes(r.assetId));case"new_market":return e.customFeatureEnabled===!0;case"market_resolved":return e.customFeatureEnabled===!0&&(n.payload.assetIds??[]).some(r=>t.includes(r));case"best_bid_ask":return e.customFeatureEnabled===!0&&t.includes(n.payload.assetId);default:return t.includes(n.payload.assetId)}}}function Ppe(e){if(FV(e))return()=>!0;let t=new Set((e.markets??[]).map(n=>n.toLowerCase()));return n=>t.has(n.payload.market.toLowerCase())}function FV(e){return(e.markets?.length??0)===0}function dT(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}function Ipe(e){let t=new Set,n=new Set,r=new Set,o=!1,s=!1;for(let{subscription:i}of e)switch(i.topic){case"perps.tickers":i.instrumentId===void 0?o=!0:n.add(i.instrumentId);break;case"perps.statistics":i.instrumentId===void 0?s=!0:r.add(i.instrumentId);break;default:t.add(_pe(i))}if(o)t.add("tickers::all");else for(let i of n)t.add(`tickers::${i}`);if(s)t.add("statistics::all");else for(let i of r)t.add(`statistics::${i}`);return t}function IV(e,t){return Array.from(t).filter(n=>!e.has(n))}function _V(e,t){return Array.from(e).filter(n=>!t.has(n))}function _pe(e){switch(e.topic){case"perps.trades":return`trades::${e.instrumentId}`;case"perps.bbo":return`bbo::${e.instrumentId}`;case"perps.book":return`book::${e.instrumentId}`;case"perps.candles":return`klines::${e.instrumentId}::${e.interval}`;case"perps.tickers":return e.instrumentId===void 0?"tickers::all":`tickers::${e.instrumentId}`;case"perps.statistics":return e.instrumentId===void 0?"statistics::all":`statistics::${e.instrumentId}`;default:ge(!1,`Unknown Perps topic: ${String(e)}`)}}function Cpe(e){switch(e.topic){case"perps.trades":return t=>t.topic==="perps.trades"&&t.channel===`trades::${e.instrumentId}`;case"perps.bbo":case"perps.book":return t=>t.topic===e.topic&&t.payload.instrumentId===e.instrumentId;case"perps.candles":return t=>t.topic==="perps.candles"&&t.payload.instrumentId===e.instrumentId&&t.payload.interval===e.interval;case"perps.tickers":case"perps.statistics":return t=>t.topic===e.topic&&(e.instrumentId===void 0||t.payload.instrumentId===e.instrumentId);default:ge(!1,`Unknown Perps topic: ${String(e)}`)}}function Npe(e){if(e.topic==="prices.equity"){let t=e.symbol.toLowerCase();return[{key:JSON.stringify([e.topic,t]),topic:e.topic,symbol:t}]}return e.symbols.map(t=>e.topic==="prices.crypto.twap"?{key:JSON.stringify([e.topic,t,60]),topic:e.topic,symbol:t,windowSeconds:60}:{key:JSON.stringify([e.topic,t]),topic:e.topic,symbol:t})}function Ope(e,t){return Math.random()*(e===4003?1e4:Math.min(1e3*2**t,3e4))}function Dpe(e){return new Promise((t,n)=>{let r=gn(()=>{n(new _("Realtime subscription was not accepted within 30 seconds."))},3e4);e.then(()=>{clearTimeout(r),t()},o=>{clearTimeout(r),n(o)})})}function Upe(e,t){if(t.type==="subscribe")return t;let n=e?.type==="subscribe"?e.payload.data:[],{symbol:r,timestamp:o,value:s}=t.payload;if((n.at(-1)?.timestamp??0)>o)return e;let i=[...n.filter(a=>a.timestamp>o-12e4&&a.timestamp<o),{timestamp:o,value:s}];return t.topic==="prices.crypto.twap"?{...t,type:"subscribe",payload:{symbol:r,data:i,windowSeconds:t.payload.windowSeconds}}:{...t,type:"subscribe",payload:{symbol:r,data:i}}}function Mpe(e){switch(e.topic){case"prices.crypto":return{channel:Rd.Crypto,filter:{symbol:e.symbol}};case"prices.crypto.twap":return{channel:Rd.Twap,filter:{symbol:e.symbol,window_seconds:e.windowSeconds}};case"prices.equity":return{channel:Rd.Equity,filter:{symbol:e.symbol}}}}function Hpe(e,t){return{...t,quote:n=>e.quote(t,n)}}function $pe(e,t){let n=t.rfqId,r=t.quoteId;return{...t,confirm:()=>e.respondToConfirmation(n,r,cs.Confirm),decline:()=>e.respondToConfirmation(n,r,cs.Decline)}}function Vpe(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function jpe(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function zpe(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function Wpe(e,t){let n=oc(e);return{auth:{apiKey:t.key,passphrase:t.passphrase,secret:t.secret},identity:{maker_address:n.maker,signature_type:n.signatureType,signer_address:n.signer},type:"auth"}}function Gpe(e,t){return{price_e6:t.price.toString(),rfq_id:e.rfqId,signed_order:t.signedOrder,size_e6:t.size.toString(),type:"RFQ_QUOTE"}}function Kpe(e,t,n){let r=oc(e);return{maker_address:r.maker,quote_id:n,rfq_id:t,signer_address:r.signer,type:"RFQ_QUOTE_CANCEL"}}function Ype(e,t,n){return{decision:n,quote_id:t,rfq_id:e,type:"RFQ_CONFIRMATION_RESPONSE"}}function Xpe(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}async function Jpe(e){let t=oc(e.account),n=gO({chainId:e.chainId,exchange:e.exchange}),r={builder:CV,maker:t.maker,makerAmount:c5(e.orderSide,e.orderPrice,e.size),metadata:CV,salt:Zpe().toString(),side:ix(e.orderSide),signatureType:t.signatureType,signer:t.signer,takerAmount:u5(e.orderSide,e.orderPrice,e.size),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:e.tokenId},o;try{o=await e.signer.signTypedData(ox({domain:n,order:r}))}catch(s){throw ue.fromError(s,"Could not sign the RFQ quote order.")}return{...r,signature:sx({domain:n,order:r,signature:o})}}function Zpe(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)}function tme(e){return F(e,eme)}async function nme(e){let t=e.response.price,n=e.response.size===void 0?ime(e.request.requestedSize,t):e.response.size,r=await Jpe({account:e.account,chainId:e.chainId,exchange:e.exchange,orderPrice:ome(e.request,e.response.source,t),orderSide:sme(e.response.source),signer:e.signer,size:n,tokenId:rme(e.request,e.response.source)});return{price:t,signedOrder:r,size:n}}function rme(e,t){return e.direction===Nn.Buy?t==="collateral"?e.noPositionId:e.yesPositionId:t==="collateral"?e.yesPositionId:e.noPositionId}function ome(e,t,n){return e.direction===Nn.Buy&&t==="collateral"||e.direction===Nn.Sell&&t==="inventory"?1000000n-n:n}function sme(e){return e==="collateral"?Ue.BUY:Ue.SELL}function ime(e,t){let n=$V(e.value);return e.unit===Qr.Shares?n:n*1000000n/t}function $V(e){let t=/^(\d+)(?:\.(\d*))?$/.exec(e);if(t===null)throw new E("Value must be a valid decimal.");let[,n="",r=""]=t;if(r.length>6)throw new E("Value must have at most 6 decimal places.");let o=BigInt(n)*1000000n+BigInt(r.padEnd(6,"0"));if(o<=0n)throw new E("Value must be greater than 0.");return o}function uT(e){return`ACK_RFQ_QUOTE:${e}`}function qO(e,t){return`ACK_RFQ_QUOTE_CANCEL:${e}:${t}`}function HO(e,t){return`ACK_RFQ_CONFIRMATION_RESPONSE:${e}:${t}`}function dme(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}function pme(e,t){return Array.from(t).flatMap(([n,r])=>e.has(n)?[]:[r])}function mme(e,t){return Array.from(e).flatMap(([n,r])=>t.has(n)?[]:[r])}function hme(e){let t=new Map;for(let{subscription:n}of e)for(let r of yme(n))t.has(r.key)||t.set(r.key,r);return t}function fme(e){return{action:"subscribe",subscriptions:e.map(({topic:t,type:n})=>({topic:t,type:n}))}}function gme(e){return{action:"unsubscribe",subscriptions:e.map(({topic:t,type:n})=>({topic:t,type:n}))}}function yme(e){switch(e.topic){case"comments":return(e.types??["comment_created"]).map(t=>Jf("comments",t));case"prices.crypto.binance":return[Jf("crypto_prices","update")];case"prices.crypto.chainlink":return[Jf("crypto_prices_chainlink","update")];case"prices.crypto.chainlink.twap":return[Jf(bme(e.windowSeconds),"update")];case"prices.equity.pyth":return[Jf("equity_prices","update")];default:ge(!1,`Unknown RTDS topic: ${String(e)}`)}}function bme(e){switch(e){case 30:return"crypto_prices_twap_thirty";case 60:return"crypto_prices_twap_sixty";default:ge(!1,`Unknown TWAP window: ${String(e)}`)}}function Jf(e,t){return{key:`${e}:${t}`,topic:e,type:t}}function wme(e){switch(e.topic){case"comments":return t=>!(t.topic!=="comments"||e.types!==void 0&&e.types.length>0&&!e.types.includes(t.type)||(e.parentEntityId!==void 0||e.parentEntityType!==void 0)&&(!(t.type==="comment_created"||t.type==="comment_removed")||e.parentEntityId!==void 0&&t.payload.parentEntityID!==e.parentEntityId||e.parentEntityType!==void 0&&t.payload.parentEntityType!==e.parentEntityType));case"prices.crypto.binance":return t=>t.topic==="prices.crypto.binance"&&(e.symbols===void 0||e.symbols.length===0||e.symbols.includes(t.payload.symbol));case"prices.crypto.chainlink":return t=>t.topic==="prices.crypto.chainlink"&&(e.symbols===void 0||e.symbols.length===0||e.symbols.includes(t.payload.symbol));case"prices.crypto.chainlink.twap":return t=>t.topic==="prices.crypto.chainlink.twap"&&t.payload.windowSeconds===e.windowSeconds&&(e.symbols===void 0||e.symbols.length===0||e.symbols.includes(t.payload.symbol));case"prices.equity.pyth":return t=>t.topic==="prices.equity.pyth"&&t.payload.symbol.toLowerCase()===e.symbol.toLowerCase()&&(e.types===void 0||e.types.length===0||e.types.includes(t.type));default:ge(!1,`Unknown RTDS topic: ${String(e)}`)}}function GV(e={}){return new WV({environment:e.environment??QO,apiKey:e.apiKey,onRateLimitUpdate:e.onRateLimitUpdate}).extend(UV)}async function Sme(e){let t=GV({environment:e.environment,apiKey:e.apiKey,onRateLimitUpdate:e.onRateLimitUpdate}),n=await Pme(t,e),r=await t.beginAuthentication({wallet:n,credentials:e.credentials,nonce:e.nonce},e.signer).then(e8(e.signer));if(r.account.walletType===Se.EOA||await _f(r,{wallet:r.account.wallet,type:r.account.walletType}))return r;if(r.account.walletType===Se.DEPOSIT_WALLET)return await Eme(r),r;throw new E(`Wallet ${r.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function Pme(e,t){if(t.wallet!==void 0)return t.wallet;let n=Be(await t.signer.getAddress()),r=O0(n,e.environment.walletDerivation);return await _f(e,{wallet:r,type:Se.DEPOSIT_WALLET})?r:Af(n,e.environment.walletDerivation)}async function Eme(e){let t=Af(e.account.signer,e.environment.walletDerivation);if(!Wt(e.account.wallet,t))throw new E(`Wallet ${e.account.wallet} does not match the expected Deposit Wallet ${t} for this signer, nor a deployed wallet address.`);await(await pv(e)).wait()}var Lr,ape,upe,dpe,QO,gpe,eg,qV,Epe,Rpe,HV,Lpe,Bpe,Fpe,qpe,Qpe,CV,NV,eme,ame,lme,cme,ume,VV,jV,zV,vme,kme,WV,xme,Ame,Tme,YV=L(()=>{"use strict";cT();cT();Zw();Zw();cf();cf();OC();h0();o0();o0();rN();Lr=require("zod");Tl();hw();Qw();lN();g0();ape=Lr.z.object({POLY_BUILDER_API_KEY:Lr.z.string().min(1),POLY_BUILDER_TIMESTAMP:Lr.z.string().min(1),POLY_BUILDER_PASSPHRASE:Lr.z.string().min(1),POLY_BUILDER_SIGNATURE:Lr.z.string().min(1)});upe=class{#e;constructor(e){this.#e=e}get isBuilderKey(){return!0}get supportGasless(){return!0}async authorize(e){try{return await this.#r(e)}catch(t){throw ue.fromError(t,"Could not authorize the builder-authenticated request")}}async#t(){let e=this.#e.headers,t=typeof e=="function"?await e():e,n=new Headers(t);return n.set("content-type","application/json"),n}async#r(e){let t=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#t(),method:"POST",mode:"cors"});if(!t.ok)throw new Error(`Remote signer rejected request with status ${t.status}`);return ape.parse(await t.json())}},dpe=class{#e;constructor(e){this.#e=e}get isBuilderKey(){return!1}get supportGasless(){return!0}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};QO={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:Be("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:Be("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:Be("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:Be("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:Be("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:Be("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},contracts:{collateralToken:Be("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:Be("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:Be("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:Be("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:Be("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:Be("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:Be("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:Be("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:Be("0x12121212006e4CD160D18e3f00711DA5c3372600"),binaryModule:Be("0x1000008dD9001B968442c1000017eaE6E0dA00Ba"),negRiskModule:Be("0x200000900045e3B6259600682756002200028933"),combinatorialModule:Be("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:Be("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:Be("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:Be("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:Be("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),perpsDepositContract:Be("0xDCa4af75705dbB50f62437045afF9921947917d2")},clob:{rest:"https://clob.polymarket.com",market:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/market"},user:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/user"}},relayer:{rest:"https://relayer-v2.polymarket.com"},gamma:{rest:"https://gamma-api.polymarket.com"},data:{rest:"https://data-api.polymarket.com"},combos:{rest:"https://combos-rfq-api.polymarket.com",ws:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq",builderGateway:{rest:"https://combos-rfq-gateway-builder.polymarket.com"},collateralReturn:{rest:"https://combos-rfq-collateral-return.polymarket.com"}},perps:{rest:"https://api.perpetuals.polymarket.com",ws:"wss://ws.perpetuals.polymarket.com/v1/ws"},realtime:{ws:"wss://ws-live-v2.polymarket.com/ws"},rtds:{ws:"wss://ws-live-data.polymarket.com"},sports:{ws:"wss://sports-api.polymarket.com/ws"},relayerMaxPolls:100,relayerPollFrequencyMs:2e3};gpe=BV({name:"preproduction",clob:{rest:"https://clob-preprod-int-v2.polymarket.com"},data:{rest:"https://data-api-preprod-int.polymarket.com"},gamma:{rest:"https://gamma-api-preprod-int.polymarket.com"},relayer:{rest:"https://relayer-v2-preprod-int.polymarket.com"}});eg=class{#e=new Set;#t;constructor(e){this.#t=e?.deriveServerState??(()=>{})}add(e,t={}){let n={queue:Bd({objectMode:!0})};t.matches!==void 0&&(n.matches=t.matches);let r={subscription:e,subscriber:n};return{change:this.#r(r),entry:r}}#r(e){let t=this.serverState();return this.#e.add(e),{before:t,after:this.serverState()}}remove(e){let t=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:t,after:this.serverState()}}dispatch(e){for(let{subscriber:t}of this.#e)(t.matches===void 0||t.matches(e))&&t.queue.push(e)}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:t}of this.#e)t.queue.end(e);this.#e.clear()}serverState(){return this.#t(this.#e)}};qV=class{#e;#t;#r;#s=new mi({heartbeat:new kO});#n=new ua;#o=new eg({deriveServerState:vpe});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#o.add(e,{matches:Spe(e)});return await this.#i(n,t),Zf(n.subscriber.queue,()=>this.#a(n))}async#i(e,t){let{before:n,after:r}=t;try{(await this.#l()).reusedOpenSocket&&TV(o=>this.#s.send(o),n,r)}catch(o){throw await this.#a(e),o}}async#a(e){let{before:t,after:n}=this.#o.remove(e);if(!this.#o.hasActiveSubscriptions()){await this.close();return}TV(r=>this.#s.send(r),t,n)}async close(){this.#r===void 0&&(this.#r=this.#u().finally(()=>{this.#r=void 0})),await this.#r}async#u(){this.#n.stop(),this.#o.endAll(),await this.#s.close()}#l(){return this.#s.connect({onConnectionLost:()=>this.#d(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#t})}#c(){this.#n.resetBackoff(),this.#y()}#p(e){let t=Array.isArray(e)?e:[e];for(let n of t){let r=RH.safeParse(n);r.success&&this.#o.dispatch(r.data)}}#d(){this.#o.hasActiveSubscriptions()&&this.#h()}#m(){}#y(){this.#s.send(xpe(this.#o.serverState()))}#h(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}},Epe=class{#e;#t;#r;#s;#n=new mi({heartbeat:new kO});#o=new ua;#i=new eg({deriveServerState:kpe});constructor(e){this.#e=e.credentials,this.#t=e.headers,this.#r=e.url}async subscribe(e){let{change:t,entry:n}=this.#i.add(e,{matches:Ppe(e)});return await this.#a(n,t),Zf(n.subscriber.queue,()=>this.#u(n))}async#a(e,t){let{before:n,after:r}=t;try{(await this.#c()).reusedOpenSocket&&SV(o=>this.#n.send(o),n,r)}catch(o){throw await this.#u(e),o}}async#u(e){let{before:t,after:n}=this.#i.remove(e);if(!this.#i.hasActiveSubscriptions()){await this.close();return}SV(r=>this.#n.send(r),t,n)}async close(){this.#s===void 0&&(this.#s=this.#l().finally(()=>{this.#s=void 0})),await this.#s}async#l(){this.#o.stop(),this.#i.endAll(),await this.#n.close()}#c(){return this.#n.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#d(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#t,url:this.#r})}#p(e){this.#o.resetBackoff(),this.#h(e)}#d(e){let t=Array.isArray(e)?e:[e];for(let n of t){let r=IH.safeParse(n);r.success&&this.#i.dispatch(r.data)}}#m(){this.#i.hasActiveSubscriptions()&&this.#f()}#y(){}#h(e){this.#n.send(Tpe(this.#i.serverState(),e))}#f(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()})}},Rpe=class{#e;#t;#r;#s;#n=new Set;#o=new Set;#i=new Set;#a=!1;constructor(e){this.#e=e.chainId,this.#t=e.headers,this.#r=e.restUrl,this.#s=e.wsUrl}connect(e,t,n,r){if(this.#a)return Promise.reject(new _("Perps session manager has been shut down."));let o=new M5({builderAttribution:t,approveBuilderFee:n,includeBuilderFills:r,chainId:this.#e,credentials:e,headers:this.#t,onClose:i=>this.#u(i),restUrl:this.#r,wsUrl:this.#s});this.#o.add(o);let s;return s=(async()=>{try{if(await o.connect(),this.#a)throw await o.close(),new _("Perps session manager has been shut down.");return this.#n.add(o),o}catch(i){throw await o.close(),i}finally{this.#i.delete(s),this.#o.delete(o)}})(),this.#i.add(s),s}async shutdown(){this.#a=!0;let e=Array.from(this.#n),t=Array.from(this.#o),n=Array.from(this.#i);this.#n.clear(),this.#o.clear(),this.#i.clear(),await Promise.allSettled([...e.map(r=>r.close()),...t.map(r=>r.close()),...n.map(r=>r.catch(()=>{}))]).then(()=>{})}#u(e){this.#n.delete(e),this.#o.delete(e)}},HV=class{#e;#t;#r;#s=1;#n=new mi({heartbeat:new xO});#o=new ua;#i=new eg({deriveServerState:Ipe});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#i.add(e,{matches:Cpe(e)});return await this.#a(n,t),Zf(n.subscriber.queue,()=>this.#u(n))}async#a(e,t){try{(await this.#c()).reusedOpenSocket&&(this.#h(IV(t.before,t.after)),this.#f(_V(t.before,t.after)))}catch(n){throw await this.#u(e),n}}async#u(e){let{before:t,after:n}=this.#i.remove(e);this.#h(IV(t,n)),this.#f(_V(t,n)),this.#i.hasActiveSubscriptions()||await this.close()}async close(){this.#r===void 0&&(this.#r=this.#l().finally(()=>{this.#r=void 0})),await this.#r}async#l(){this.#o.stop(),this.#i.endAll(),await this.#n.close()}#c(){return this.#n.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#d(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#t})}#p(){this.#o.resetBackoff(),this.#h(Array.from(this.#i.serverState()))}#d(e){let t=CH.safeParse(e);t.success&&this.#i.dispatch(t.data)}#m(){this.#i.hasActiveSubscriptions()&&this.#b()}#y(){}#h(e){e.length!==0&&this.#n.send(this.#g("sub",e))}#f(e){e.length!==0&&this.#n.send(this.#g("unsub",e))}#g(e,t){return{id:this.#s++,req:e,chs:t}}#b(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()})}};Lpe=class{#e;#t=new ua;#r=new Map;#s=[];#n;#o;#i=!1;#a=!1;#u=!1;#l=!1;#c;#p=0;#d=64;#m=Number.NEGATIVE_INFINITY;constructor(e){this.#e=e}get size(){return this.#r.size}has(e){return this.#r.has(e)}get closed(){return this.#a}get keyTarget(){return Date.now()-this.#m>=6e4?64:this.#d}add(e,t){clearTimeout(this.#o);let n=this.#r.get(e.key);if(n===void 0){let{promise:r,resolve:o,reject:s}=Promise.withResolvers();r.catch(()=>{}),n={subscription:e,listeners:new Set,ready:r,resolve:o,reject:s,subscribed:!1,accepted:!1},this.#r.set(e.key,n),this.#i&&this.#f("subscribe",[n])}return n.listeners.add(t),n.snapshot!==void 0&&t.event(n.snapshot),!this.#i&&!this.#l&&this.#c===void 0&&!this.#t.isScheduled&&this.#y(),Dpe(n.ready)}remove(e,t){let n=this.#r.get(e);n!==void 0&&(n.listeners.delete(t),!(n.listeners.size>0)&&(this.#r.delete(e),n.reject(new _("Realtime subscription closed.")),this.#i&&this.#f("unsubscribe",[n]),this.#r.size===0&&(this.#o=gn(()=>{this.close()},1e3))))}#y(){if(this.#a||this.#l)return Promise.resolve();if(this.#c!==void 0)return this.#c;let e=this.#h().catch(t=>{this.#S([...this.#r.values()].filter(n=>!n.accepted),_.fromError(t))}).finally(()=>{this.#c===e&&(this.#c=void 0),this.#i||this.#w(1006)});return this.#c=e,e}async#h(){let e=this.#p;if(await this.#e.open({event:t=>this.#x(t),dropped:()=>this.#A(),disconnected:t=>this.#T(t)}),!(this.#a||e!==this.#p))try{if(await this.#e.authorize(),this.#a||e!==this.#p)return;this.#i=!0,this.#f("subscribe",[...this.#r.values()])}catch(t){if(this.#a||e!==this.#p)return;t instanceof O&&t.code!==Ed.AuthUnavailable?this.#P(t):await this.#k(1006)}}#f(e,t){if(t.length===0)return;let n=this.#s.at(-1);n?.op===e?n.keys.push(...t):this.#s.push({op:e,keys:t}),this.#g()}#g(){this.#n!==void 0||this.#u||!this.#i||this.#a||(this.#n=gn(()=>{this.#n=void 0,this.#b()},10))}async#b(){if(!this.#i||this.#a)return;let e=this.#s.shift();if(e===void 0)return;let t=[...new Set(e.keys)].filter(r=>e.op==="unsubscribe"||this.#r.get(r.subscription.key)===r);if(t.length===0){this.#g();return}let n=this.#p;this.#u=!0;try{let r=await this.#e.change(e.op,t.map(({subscription:o})=>o));if(n!==this.#p||this.#a)return;if(e.op==="unsubscribe"&&r.length>0){let o=r[0];if(o!==void 0)throw o.error}if(e.op==="subscribe"){this.#t.resetBackoff();let o=new Set(r.map(s=>s.key));for(let s of t)o.has(s.subscription.key)||(s.subscribed=!0,s.accepted=!0,s.resolve());for(let{key:s,error:i}of r){let a=t.find(l=>l.subscription.key===s);a!==void 0&&this.#S([a],i,!1)}}}catch(r){if(n!==this.#p||this.#a)return;r instanceof O&&e.op==="subscribe"?this.#S(t,r):await this.#k(1006)}finally{this.#u=!1,this.#g()}}#x(e){for(let t of this.#r.values()){let n=t.subscription;if(n.topic!==e.topic)continue;let r=e.payload;if(r.symbol.toLowerCase()===n.symbol&&!(n.topic==="prices.crypto.twap"&&(!("windowSeconds"in r)||r.windowSeconds!==n.windowSeconds))){t.snapshot=Upe(t.snapshot,e);for(let o of t.listeners)o.event(e)}}}#A(){let e=Date.now();e-this.#m<5e3||(this.#d=Math.max(1,Math.floor(this.keyTarget/2)),this.#m=e)}#v(){this.#p++,this.#i=!1,this.#s=[],clearTimeout(this.#n),this.#n=void 0;for(let e of this.#r.values()){if(e.snapshot=void 0,!e.subscribed)continue;let{promise:t,resolve:n,reject:r}=Promise.withResolvers();t.catch(()=>{}),e.ready=t,e.resolve=n,e.reject=r,e.subscribed=!1}}#T(e){let t=new Yr("Realtime connection closed.",e);this.#v(),e.code===4001||e.code===4008?this.#P(t):this.#w(e.code)}async#k(e){this.#l=!0,this.#v();try{await this.#e.close()}finally{this.#l=!1,this.#w(e)}}#w(e){this.#t.schedule({delayPolicy:t=>Ope(e,t),shouldReconnect:()=>!this.#a&&this.#r.size>0,reconnect:()=>this.#y()})}#P(e){let t=[...this.#r.values()],n=new Set(t.flatMap(r=>[...r.listeners]));for(let r of t)r.reject(e);for(let r of n)r.end(e);this.close()}#S(e,t,n=!0){let r=e.filter(s=>this.#r.get(s.subscription.key)===s),o=new Set(r.flatMap(s=>[...s.listeners]));for(let s of r)this.#r.delete(s.subscription.key),s.reject(t);n&&this.#i&&this.#f("unsubscribe",r);for(let s of o)s.end(t);this.#r.size===0&&(this.#o=gn(()=>{this.close()},1e3))}async close(){if(this.#a)return;this.#a=!0,this.#t.stop(),clearTimeout(this.#o);let e=new _("Realtime connection closed.");this.#v();for(let t of this.#r.values())t.reject(e);this.#r.clear(),await this.#e.close()}};Bpe=class{#e;#t=new mi({heartbeat:new I5,connectTimeoutMs:1e4,closeTimeoutMs:1e3});#r=new Map;#s;#n=0;#o=0;#i=0;constructor(e){this.#e=e}async open(e){this.#s=e;let t=this.#i;await this.#t.connect({url:this.#e.url,headers:this.#e.headers,onOpen:()=>{},onError:()=>{},onConnectionLost:n=>{t===this.#i&&(this.#l(new Yr("Realtime connection closed.",n)),e.disconnected(n))},onMessage:n=>{t===this.#i&&this.#u(n)}})}async authorize(){let{key:e,secret:t,passphrase:n}=this.#e.credentials;await this.#a({op:"auth",auth:{apiKey:e,secret:t,passphrase:n}},Nl.Authed,[])}async change(e,t){let n=[],r=0;for(;r<t.length;){let o=[];for(;r+o.length<t.length;){let i=t[r+o.length];if(i===void 0)break;let a=Mpe(i),l={op:e,subscriptions:[...o,a],rid:String(this.#n+1)};if(o.length>0&&new TextEncoder().encode(JSON.stringify(l)).length>6e4)break;o.push(a)}let s=await this.#a({op:e,subscriptions:o},e==="subscribe"?Nl.Subscribed:Nl.Unsubscribed,o.map(({channel:i})=>i));for(let{index:i,error:a}of s){let l=t[r+i];l!==void 0&&n.push({key:l.key,error:a})}r+=o.length}return n}#a(e,t,n){let r=String(++this.#n);return new Promise((o,s)=>{let i={op:t,channels:[...n],rejections:[],resolve:o,reject:s};this.#r.set(r,i),i.sendTimer=gn(()=>{i.timer=gn(()=>{this.#r.delete(r),s(new _("Realtime acknowledgement timed out after 10 seconds."))},1e4),this.#o=Date.now();try{if(!this.#t.send({...e,rid:r}))throw new _("Realtime connection is not open.")}catch(a){clearTimeout(i.timer),this.#r.delete(r),s(_.fromError(a))}},Math.max(0,110-(Date.now()-this.#o)))})}#u(e){let t=DH.safeParse(e);if(t.success){let{op:o,rid:s,code:i,channel:a}=t.data,l=s===void 0?void 0:this.#r.get(s);if(l===void 0)return;if(o===Nl.Error&&i!==void 0){let c=new O(`Realtime subscription rejected: ${i}`,{status:200,code:i}),u=l.channels.flatMap((d,p)=>d===a?[p]:[]);if(a===void 0||u.length!==1)l.reject(c);else{let d=u[0];if(d===void 0||(l.channels[d]=void 0,l.rejections.push({index:d,error:c}),l.channels.some(p=>p!==void 0)))return;l.resolve(l.rejections)}}else if(o===l.op){if(l.channels.length>0){let c=l.channels.indexOf(a??"");if(c<0||(l.channels[c]=void 0,l.channels.some(u=>u!==void 0)))return}l.resolve(l.rejections)}else return;clearTimeout(l.timer),s!==void 0&&this.#r.delete(s);return}let n=UH.safeParse(e);if(!n.success)return;let r=FH(n.data);r!==void 0&&this.#s?.event(r),(n.data.dropped??0)>0&&this.#s?.dropped()}#l(e){for(let t of this.#r.values())clearTimeout(t.sendTimer),clearTimeout(t.timer),t.reject(e);this.#r.clear()}async close(){this.#i++,this.#s=void 0,this.#l(new _("Realtime connection closed.")),await this.#t.close()}};Fpe=class{#e;#t=new Set;#r=new Set;constructor(e){this.#e=e}async subscribe(e){let t=[...new Map(Npe(e).map(a=>[a.key,a])).values()],n=Bd({objectMode:!0}),r=[],o=!1,s,i=async()=>{if(!o){o=!0;for(let a of r)a();s===void 0?await n.return():n.end(s),this.#r.delete(i)}};this.#r.add(i);try{await Promise.all(t.map(a=>{let l=this.#s(a.key),c={event(u){if(o||"types"in e&&e.types!==void 0&&e.types.length>0&&!e.types.includes(u.type))return;let d="symbol"in u.payload?{...u.payload,symbol:"symbol"in a?a.symbol:u.payload.symbol}:u.payload;n.push({...u,payload:d})},end(u){s=u,n.end(u),i()}};return r.push(()=>l.remove(a.key,c)),l.add(a,c)}))}catch(a){throw await i(),a}return{close:i,async*[Symbol.asyncIterator](){try{yield*n}finally{await i()}}}}#s(e){for(let n of this.#t)if(n.closed)this.#t.delete(n);else if(n.has(e))return n;for(let n of this.#t)if(n.size<n.keyTarget)return n;let t=new Lpe(new Bpe(this.#e));return this.#t.add(t),t}async close(){await Promise.all([...this.#r].map(t=>t()));let e=[...this.#t];this.#t.clear(),await Promise.all(e.map(t=>t.close()))}},qpe=class{#e;constructor(e){this.#e=new Fpe(e)}async subscribe(e){return this.#e.subscribe(e)}async close(){await this.#e.close()}};Qpe=class{#e=new Map;#t;constructor(e){this.#t=e}waitFor(e,t){let n=Xpe(),r,o=gn(()=>{this.remove(e,r),n.reject(new tt(t))},this.#t);r=n.promise.finally(()=>clearTimeout(o));let s=this.#e.get(e)??[];return s.push({...n,promise:r}),this.#e.set(e,s),r}resolve(e,t){let n=this.#e.get(e),r=n?.shift();r!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),r.resolve(t))}reject(e,t){let n=this.#e.get(e),r=n?.shift();r!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),r.reject(t))}remove(e,t){let n=this.#e.get(e);if(n===void 0)return;let r=n.filter(o=>o.promise!==t);r.length===0?this.#e.delete(e):this.#e.set(e,r)}rejectAll(e){for(let t of this.#e.values())for(let n of t)n.reject(e);this.#e.clear()}};CV="0x0000000000000000000000000000000000000000000000000000000000000000";NV=H.transform(e=>$V(e)).refine(e=>e<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),eme=Lr.z.strictObject({price:NV.refine(e=>e<1000000n,{message:"Price must be less than 1."}),size:NV.optional(),source:Lr.z.enum(["collateral","inventory"]).default("collateral")});ame=3e4,lme=3e4,cme=class{#e;#t;#r;#s;#n;#o;#i;#a;#u;#l;#c=!1;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#o=e.signer,this.#i=e.url}async connect(){if(this.#c)throw new _("RFQ quoter manager has been shut down.");if(this.#a!==void 0){if(!this.#a.closed)return this.#a;this.#a=void 0}if(this.#l!==void 0)return this.#l;let e=new ume({account:this.#e,chainId:this.#t,credentials:this.#r,exchange:this.#s,headers:this.#n,onClose:()=>this.#p(e),signer:this.#o,url:this.#i});this.#u=e;let t;return t=(async()=>{try{if(await e.connect(),this.#c)throw await e.close(),new _("RFQ quoter manager has been shut down.");return this.#a=e,e}catch(n){throw await e.close(),n}finally{this.#l===t&&(this.#l=void 0),this.#u===e&&(this.#u=void 0)}})(),this.#l=t,t}async shutdown(){this.#c=!0;let e=this.#a,t=this.#u,n=this.#l;this.#a=void 0,this.#u=void 0,this.#l=void 0,await Promise.allSettled([e?.close(),t?.close(),n?.catch(()=>{})]).then(()=>{})}#p(e){this.#a===e&&(this.#a=void 0),this.#u===e&&(this.#u=void 0)}},ume=class{#e;#t;#r;#s;#n;#o;#i;#a;#u=new mi;#l=Bd({objectMode:!0});#c=new Qpe(lme);#p;#d;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#o=e.onClose,this.#i=e.signer,this.#a=e.url}get closed(){return this.#p!==void 0}async connect(){let e=dme();this.#d=e;let t=gn(()=>{e.reject(new _("RFQ quoter authentication timed out."))},ame);try{await this.#u.connect({headers:this.#n,onConnectionLost:n=>this.#v(n),onError:()=>{},onMessage:n=>this.#x(n),onOpen:()=>this.#b(),url:this.#a}),await e.promise}finally{clearTimeout(t),this.#d=void 0}}async#m(e){if(!this.#u.send(e))throw new _("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#y()),await this.#p}[Symbol.asyncIterator](){return this.#l[Symbol.asyncIterator]()}async#y(){let e=new _("RFQ quoter websocket closed.");this.#g(e),this.#l.end(),await this.#u.close(),this.#o()}async#h(e){this.#p===void 0&&(this.#p=this.#f(e)),await this.#p}async#f(e){this.#g(e),this.#l.end(e),await this.#u.close(),this.#o()}#g(e){this.#d?.reject(e),this.#c.rejectAll(e)}#b(){this.#u.send(Wpe(this.#e,this.#r))}#x(e){if(this.#p!==void 0)return;let t=h4.safeParse(e);if(!t.success)return;let n=t.data;switch(n.type){case"auth":this.#A(n);return;case"quote_request":this.#l.push(Hpe(this,n));return;case"quote_ack":this.#c.resolve(uT(n.rfqId),Vpe(n));return;case"quote_cancel_ack":this.#c.resolve(qO(n.rfqId,n.quoteId),jpe(n));return;case"confirmation_request":this.#l.push($pe(this,n));return;case"confirmation_ack":this.#c.resolve(HO(n.rfqId,n.quoteId),zpe(n));return;case"execution_update":this.#l.push(n);return;case"trade":this.#l.push(n);return;case"rfq_error":this.#T(n);return}}#A(e){if(e.success===!0){this.#d?.resolve(void 0);return}this.#d?.reject(new _(`RFQ quoter authentication failed: ${e.error}`))}#v(e){this.#h(new Yr("RFQ quoter connection lost.",e))}#T(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new _("Uncorrelated RFQ quoter error."));return}this.#c.reject(uT(e.rfqId),new ac(e.message,{code:e.code,errorId:e.errorId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_QUOTE_CANCEL"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new _("Uncorrelated RFQ quoter error."));return}this.#c.reject(qO(e.rfqId,e.quoteId),new lc(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_CONFIRMATION_RESPONSE"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new _("Uncorrelated RFQ quoter error."));return}this.#c.reject(HO(e.rfqId,e.quoteId),new cc(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}))}}async quote(e,t){let n=tme(t),r=await nme({account:this.#e,chainId:this.#t,exchange:this.#s,request:e,response:n,signer:this.#i}),o=this.#c.waitFor(uT(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#m(Gpe(e,r)),await o}catch(s){throw this.#c.remove(uT(e.rfqId),o),s}}async cancelQuote(e){let t=qO(e.rfqId,e.quoteId),n=this.#c.waitFor(t,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#m(Kpe(this.#e,e.rfqId,e.quoteId)),await n}catch(r){throw this.#c.remove(t,n),r}}async respondToConfirmation(e,t,n){let r=HO(e,t),o=this.#c.waitFor(r,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#m(Ype(e,t,n)),await o}catch(s){throw this.#c.remove(r,o),s}}};VV=class{#e;#t;#r;#s=new mi({heartbeat:new E5});#n=new ua;#o=new eg({deriveServerState:hme});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#o.add(e,{matches:wme(e)});return await this.#i(n,t),Zf(n.subscriber.queue,()=>this.#a(n))}async#i(e,t){try{if((await this.#l()).reusedOpenSocket){let{before:n,after:r}=t,o=pme(n,r);this.#h(o)}}catch(n){throw await this.#a(e),n}}async#a(e){let{before:t,after:n}=this.#o.remove(e),r=mme(t,n);this.#f(r),this.#o.hasActiveSubscriptions()||await this.close()}async close(){this.#r===void 0&&(this.#r=this.#u().finally(()=>{this.#r=void 0})),await this.#r}async#u(){this.#n.stop(),this.#o.endAll(),await this.#s.close()}#l(){return this.#s.connect({onConnectionLost:()=>this.#d(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#t})}#c(){this.#n.resetBackoff(),this.#y()}#p(e){let t=WH.safeParse(e);t.success&&this.#o.dispatch(t.data)}#d(){this.#o.hasActiveSubscriptions()&&this.#g()}#m(){}#y(){this.#h(Array.from(this.#o.serverState().values()))}#h(e){e.length!==0&&this.#s.send(fme(e))}#f(e){e.length!==0&&this.#s.send(gme(e))}#g(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}};jV=class{#e;#t;#r;#s=new mi({heartbeat:new R5});#n=new ua;#o=new eg;constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{entry:t}=this.#o.add(e);return await this.#i(t),Zf(t.subscriber.queue,()=>this.#a(t))}async#i(e){try{await this.#l()}catch(t){throw await this.#a(e),t}}async#a(e){this.#o.remove(e),this.#o.hasActiveSubscriptions()||await this.close()}async close(){this.#r===void 0&&(this.#r=this.#u().finally(()=>{this.#r=void 0})),await this.#r}async#u(){this.#n.stop(),this.#o.endAll(),await this.#s.close()}#l(){return this.#s.connect({onConnectionLost:()=>this.#d(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#t})}#c(){this.#n.resetBackoff()}#p(e){let t=GH.safeParse(e);t.success&&this.#o.dispatch(t.data)}#d(){this.#o.hasActiveSubscriptions()&&this.#y()}#m(){}#y(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}},zV=class{#e;#t;get context(){return this.#e}get decorators(){return this.#t}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get perps(){return this.context.perps}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??!1}get hasBuilderApiKey(){return this.context.apiKey?.isBuilderKey??!1}constructor(e){this.#e=e,this.#t=[]}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#t.push(e)}},vme=Lr.z.object({key:os,passphrase:Lr.z.string(),secret:Lr.z.string()}),kme=Lr.z.object({wallet:J,credentials:vme.optional(),nonce:Lr.z.number().int().nonnegative().optional()}).superRefine((e,t)=>{e.credentials!==void 0&&e.nonce!==void 0&&t.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]})}).transform(e=>e.credentials!==void 0?{wallet:e.wallet,credentials:e.credentials}:e.nonce!==void 0?{wallet:e.wallet,nonce:e.nonce}:{wallet:e.wallet}),WV=class extends zV{constructor(e){super({apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,data:new vn({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new vn({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new vn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:t=>this.resolveClobHeaders(t)}),relayer:new vn({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:t=>this.resolveRelayerHeaders(t)}),rfq:new vn({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new vn({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new _N({url:e.environment.rpc}),webSockets:{clobMarket:new qV({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new jV({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new VV({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new HV({headers:e.environment.perps.headers,url:e.environment.perps.ws})}})}isSecureClient(){return!1}isPublicClient(){return!0}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close()]).then(()=>{})}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,t){let n=F(e,kme);return Promise.resolve(async function*(){let r=Math.floor(Date.now()/1e3),o=n?.nonce??0,s=Be(yield QN()),i=Be(n.wallet),a=_6(this.environment,s,i);if(n.credentials!==void 0){let u=this.#e(n.credentials,a,t);try{if((await Tv(u)).includes(n.credentials.key))return u}catch(d){if(!(d instanceof O)||d.status!==401)throw d}}let l=yield{kind:"signAuthMessage",payload:ppe({address:s,chainId:this.environment.chainId,nonce:o,timestamp:r})},c=await Av(this,{address:s,nonce:o,signature:rs(l),timestamp:r});return this.#e(c,a,t)}.call(this))}#e(e,t,n){let r=new xme({account:t,apiKey:this.context.apiKey,credentials:e,environment:this.environment,onRateLimitUpdate:this.context.onRateLimitUpdate,signer:n});for(let o of this.decorators)r.extend(o);return r}},xme=class extends zV{#e=!1;get context(){return ge(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=!0}constructor(e){let t=new qpe({url:e.environment.realtime.ws,headers:e.environment.realtime.headers,credentials:e.credentials});super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,signer:e.signer,clob:new vn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:n=>this.resolveClobHeaders(n)}),relayer:new vn({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:n=>this.resolveRelayerHeaders(n)}),rpc:new _N({url:e.environment.rpc}),gamma:new vn({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new vn({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new vn({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new vn({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new vn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,resolveHeaders:async n=>({...await this.resolveClobHeaders(n),...await this.#r(n)}),root:e.environment.clob.rest}),combos:new vn({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:n=>this.resolveRelayerHeaders(n),root:e.environment.combos.collateralReturn.rest}),builderGateway:new vn({headers:e.environment.combos.builderGateway.headers,resolveHeaders:async n=>({...await this.#t(n),...await this.#r(n)}),root:e.environment.combos.builderGateway.rest}),webSockets:{clobMarket:new qV({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new Epe({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new cme({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.contracts.exchangeV3,headers:e.environment.combos.headers,signer:e.signer,url:e.environment.combos.ws}),sports:new jV({headers:e.environment.sports.headers,url:e.environment.sports.ws}),realtime:t,rtds:new VV({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new HV({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new Rpe({chainId:e.environment.chainId,headers:e.environment.perps.headers,restUrl:e.environment.perps.rest,wsUrl:e.environment.perps.ws})}})}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}get secureClob(){return this.context.secureClob}get combos(){return this.context.combos}get builderGateway(){return this.context.builderGateway}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.realtime.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close(),this.webSockets.clobUser.close()]).then(()=>{})}isSecureClient(){return!0}isPublicClient(){return!1}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),t=this.webSockets.perpsSession.shutdown(),n=this.webSockets.rfqQuoter.shutdown(),{apiKey:r,environment:o,onRateLimitUpdate:s}=this.context;try{await Sv(this)}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,t,n]).then(()=>{})}let i=new WV({apiKey:r,environment:o,onRateLimitUpdate:s});for(let a of this.decorators)i.extend(a);return i}async#t(e){return e.method!=="GET"&&this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):{}}async#r(e){try{let t=Math.floor(Date.now()/1e3);return{POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await MV(this.credentials.secret,t,e.method,e.path,e.body),POLY_TIMESTAMP:`${t}`}}catch(t){throw ue.fromError(t,"Could not sign the L2-authenticated request")}}};Ame=B(bt,$,O,ue,tt,en,_,C,E),Tme=B(E)});var QV={};fr(QV,{AcceptComboQuoteError:()=>IA,ApproveErc1155ForAllError:()=>wv,ApproveErc20Error:()=>bv,ApprovePerpsBuilderFeeError:()=>vx,ArmPerpsAutoCancelError:()=>Px,AuthorizeSessionKeyError:()=>$A,BiggestWinnerKind:()=>Ql,BuilderVolumeInterval:()=>Kl,CancelAllError:()=>zk,CancelMarketOrdersError:()=>Gk,CancelOrderError:()=>Hk,CancelOrdersError:()=>Vk,CollateralReturnKnownOperationKind:()=>Dd,ComboAcceptFailureReason:()=>Ro,ComboActivityType:()=>Wl,ComboPositionSortBy:()=>Vl,ComboPositionStatus:()=>ii,ComboQuoteUnavailableReason:()=>ci,CreateApiKeyError:()=>g8,CreateBuilderApiKeyError:()=>k8,CreateLimitOrderError:()=>fx,CreateMarketOrderError:()=>px,CreateOrDeriveApiKeyError:()=>b8,DeleteApiKeyError:()=>v8,DeployDepositWalletError:()=>r8,DepositToPerpsError:()=>Gx,DeriveApiKeyError:()=>y8,DownloadAccountingSnapshotError:()=>aA,DropNotificationsError:()=>j0,EstimateMarketPriceError:()=>Qk,ExecuteCollateralReturnPlanError:()=>ek,FetchApiKeysError:()=>w8,FetchBalanceAllowanceError:()=>D6,FetchBuilderApiKeysError:()=>A8,FetchBuilderFeeRatesError:()=>L8,FetchBuilderVolumeError:()=>vk,FetchClosedOnlyModeError:()=>D0,FetchCommentsByIdError:()=>ok,FetchEventError:()=>uk,FetchEventLiveVolumeError:()=>gk,FetchEventTagsError:()=>pk,FetchExecuteParamsError:()=>t8,FetchLastTradePriceError:()=>Vv,FetchLastTradePricesError:()=>zv,FetchMarketError:()=>Ck,FetchMarketInfoError:()=>O8,FetchMarketTagsError:()=>Ok,FetchMidpointError:()=>Rv,FetchMidpointsError:()=>_v,FetchNegRiskError:()=>_8,FetchNotificationsError:()=>$0,FetchOpenInterestError:()=>Fk,FetchOrderBookError:()=>Uv,FetchOrderBooksError:()=>Bv,FetchOrderError:()=>F0,FetchOrderScoringError:()=>G0,FetchOrdersScoringError:()=>Y0,FetchPerpsBookError:()=>Dx,FetchPerpsBuilderApprovalsError:()=>Ax,FetchPerpsBuilderEarningsSummaryError:()=>Sx,FetchPerpsBuilderStatusError:()=>bx,FetchPerpsFeesError:()=>Vx,FetchPerpsInstrumentsError:()=>_x,FetchPerpsTickerError:()=>Nx,FetchPerpsTickersError:()=>Lx,FetchPortfolioValueError:()=>rA,FetchPriceError:()=>Nv,FetchPricesError:()=>Lv,FetchPublicProfileError:()=>vA,FetchRelatedTagResourcesError:()=>rT,FetchRelatedTagsError:()=>tT,FetchResolutionsError:()=>hk,FetchRewardPercentagesError:()=>rv,FetchRfqStatusError:()=>OA,FetchSeriesError:()=>FA,FetchSessionKeysError:()=>HA,FetchSportsMarketTypesError:()=>KA,FetchSpreadError:()=>Fv,FetchSpreadsError:()=>Hv,FetchTagError:()=>ZA,FetchTickSizeError:()=>R8,FetchTotalEarningsForUserForDayError:()=>Z0,FetchTraderLeaderboardStandingError:()=>Tk,FetchTradingApprovalsStateError:()=>vv,FetchUserPnlError:()=>sA,FetchUserStatsError:()=>oA,FetchUserVolumeError:()=>iA,GaslessTransactionHandle:()=>Cf,GaslessTransactionMetadataSchema:()=>ur,IsWalletDeployedError:()=>n8,LeaderboardWindow:()=>Gl,ListAccountTradesError:()=>H0,ListActivityError:()=>av,ListBiggestWinnersError:()=>Sk,ListBuilderLeaderboardError:()=>bk,ListBuilderTradesError:()=>Pv,ListComboActivityError:()=>lv,ListComboMarketsError:()=>Ik,ListComboPositionsError:()=>nA,ListCommentsByUserAddressError:()=>ik,ListCommentsError:()=>nk,ListCurrentRewardsError:()=>Gv,ListEventsError:()=>lk,ListMarketClarificationsError:()=>q8,ListMarketHoldersError:()=>Dk,ListMarketRewardsError:()=>Yv,ListMarketsError:()=>Rk,ListOpenOrdersError:()=>B0,ListPerpsBuilderEarningsError:()=>Tx,ListPerpsCandlesError:()=>Bx,ListPerpsFundingHistoryError:()=>Fx,ListPerpsTradesError:()=>Hx,ListPositionsError:()=>tA,ListPriceHistoryError:()=>Bk,ListSeriesError:()=>BA,ListSportsError:()=>WA,ListTagsError:()=>XA,ListTeamsError:()=>sT,ListTraderLeaderboardError:()=>xk,ListTradesError:()=>sv,ListUserEarningsAndMarketsConfigError:()=>tv,ListUserEarningsForDayError:()=>X0,MergeComboPositionError:()=>aV,MergeMarketPositionError:()=>sV,MergePositionsError:()=>jd,OpenPerpsSessionError:()=>zx,OpenRfqSessionError:()=>SA,PlaceLimitOrderError:()=>gx,PlaceMarketOrderError:()=>mx,PlanCollateralReturnError:()=>Jv,PositionFilterType:()=>$l,PositionSortBy:()=>Hl,PositionStatus:()=>ai,PostOrderError:()=>Zk,PostOrdersError:()=>ex,PrepareCollateralReturnExecutionError:()=>U8,PrepareErc1155ApprovalForAllError:()=>d8,PrepareErc20ApprovalError:()=>u8,PrepareErc20TransferError:()=>xV,PrepareGaslessTransactionError:()=>o8,PrepareLimitOrderError:()=>bO,PrepareLimitOrderPostingError:()=>v5,PrepareMarketOrderError:()=>yO,PrepareMarketOrderPostingError:()=>b5,PrepareMergeComboPositionError:()=>oV,PrepareMergeMarketPositionError:()=>nV,PrepareMergePositionsError:()=>pA,PreparePerpsDepositError:()=>V5,PrepareRedeemComboPositionError:()=>mV,PrepareRedeemMarketPositionsError:()=>dV,PrepareRedeemPositionsError:()=>gA,PrepareSplitComboPositionError:()=>Q5,PrepareSplitMarketPositionError:()=>K5,PrepareSplitPositionError:()=>lA,PrepareTradingApprovalsError:()=>p8,PriceHistoryInterval:()=>Po,RedeemPositionsError:()=>bA,RequestComboQuoteError:()=>EA,ResolutionMarketType:()=>Jl,ResolutionReporter:()=>ec,ResolutionSource:()=>Zl,ResolutionStatus:()=>Xl,ResolveConditionByTokenError:()=>N8,RevokeBuilderApiKeyError:()=>S8,RevokePerpsBuilderFeeError:()=>Ix,RevokePerpsCredentialsError:()=>Wx,RevokeSessionKeyError:()=>jA,RfqCancelQuoteError:()=>AA,RfqCancelQuoteRejectedError:()=>lc,RfqConfirmationDecision:()=>cs,RfqConfirmationError:()=>TA,RfqConfirmationRejectedError:()=>cc,RfqDirection:()=>Nn,RfqExecutionStatus:()=>us,RfqKnownErrorCode:()=>Cr,RfqQuoteError:()=>xA,RfqQuoteRejectedError:()=>ac,RfqRejectionCode:()=>li,RfqRequestRejectedError:()=>ms,RfqRequestedSizeUnit:()=>Qr,RfqSide:()=>Eo,RfqStatus:()=>mn,SearchError:()=>DA,SearchSort:()=>zd,SessionKeyKnownScope:()=>yo,SetupTradingApprovalsError:()=>kv,SortDirection:()=>Ml,SplitComboPositionError:()=>Z5,SplitMarketPositionError:()=>X5,SplitPositionError:()=>Vd,SubscribeError:()=>QA,TipSide:()=>Bl,TradeFilterType:()=>Fl,TraderLeaderboardSort:()=>Yl,TransferErc20Error:()=>aT,TransferPerpsCollateralError:()=>Yx,UpdateBalanceAllowanceError:()=>U6,UpdatePerpsLeverageError:()=>Ex,UpdatePerpsMarginError:()=>Rx,UserPnlFidelity:()=>zl,UserPnlInterval:()=>jl,WaitForComboFillError:()=>CA,WaitForGaslessTransactionError:()=>c8,WaitForOrderFillSettlementError:()=>ux,WithdrawFromPerpsError:()=>Kx,acceptComboQuote:()=>_A,approveErc1155ForAll:()=>Of,approveErc20:()=>Nf,authorizeSessionKey:()=>VA,buildDepositWalletExecuteRequest:()=>qd,buildProxyWalletExecuteRequest:()=>mv,buildSafeWalletExecuteRequest:()=>gv,cancelAll:()=>Wk,cancelMarketOrders:()=>Kk,cancelOrder:()=>$k,cancelOrders:()=>jk,createApiKey:()=>tO,createBuilderApiKey:()=>x8,createLimitOrder:()=>Ff,createMarketOrder:()=>Mf,createOrDeriveApiKey:()=>Av,deleteApiKey:()=>Sv,deployDepositWallet:()=>pv,depositToPerps:()=>Jx,deriveApiKey:()=>nO,downloadAccountingSnapshot:()=>Kf,dropNotifications:()=>z0,estimateMarketPrice:()=>Xk,executeCollateralReturnPlan:()=>tk,extractOnChainNonceFromSubmitError:()=>hv,fetchApiKeys:()=>Tv,fetchBalanceAllowance:()=>W0,fetchBuilderApiKeys:()=>T8,fetchBuilderFeeRates:()=>sO,fetchBuilderVolume:()=>kk,fetchClosedOnlyMode:()=>U0,fetchCommentsById:()=>sk,fetchEvent:()=>dk,fetchEventLiveVolume:()=>yk,fetchEventTags:()=>mk,fetchExecuteParams:()=>If,fetchLastTradePrice:()=>jv,fetchLastTradePrices:()=>Wv,fetchMarket:()=>Nk,fetchMarketInfo:()=>oO,fetchMarketTags:()=>Lk,fetchMidpoint:()=>Iv,fetchMidpoints:()=>Cv,fetchNegRisk:()=>C8,fetchNotifications:()=>V0,fetchOpenInterest:()=>qk,fetchOrder:()=>q0,fetchOrderBook:()=>Hd,fetchOrderBooks:()=>Mv,fetchOrderScoring:()=>K0,fetchOrdersScoring:()=>Q0,fetchPerpsBook:()=>Ux,fetchPerpsBuilderStatus:()=>wx,fetchPerpsFees:()=>jx,fetchPerpsInstruments:()=>Cx,fetchPerpsTicker:()=>Ox,fetchPerpsTickers:()=>Hf,fetchPortfolioValue:()=>jf,fetchPrice:()=>Ov,fetchPrices:()=>Dv,fetchPublicProfile:()=>kA,fetchRelatedTagResources:()=>oT,fetchRelatedTags:()=>nT,fetchResolutions:()=>fk,fetchRewardPercentages:()=>ov,fetchRfqStatus:()=>LA,fetchSeries:()=>qA,fetchSessionKeys:()=>Wd,fetchSportsMarketTypes:()=>YA,fetchSpread:()=>qv,fetchSpreads:()=>$v,fetchTag:()=>eT,fetchTickSize:()=>I8,fetchTotalEarningsForUserForDay:()=>ev,fetchTraderLeaderboardStanding:()=>Df,fetchTradingApprovalsState:()=>Lf,fetchTransaction:()=>XN,fetchUserPnl:()=>Wf,fetchUserStats:()=>zf,fetchUserVolume:()=>Gf,isRetryableGaslessSubmitError:()=>yv,isWalletDeployed:()=>_f,listAccountTrades:()=>Tf,listActivity:()=>Sf,listBiggestWinners:()=>Pk,listBuilderLeaderboard:()=>wk,listBuilderTrades:()=>Ev,listComboActivity:()=>Pf,listComboMarkets:()=>_k,listComboPositions:()=>Vf,listComments:()=>rk,listCommentsByUserAddress:()=>ak,listCurrentRewards:()=>Kv,listEvents:()=>ck,listMarketClarifications:()=>Ek,listMarketHolders:()=>Uk,listMarketRewards:()=>Qv,listMarkets:()=>Uf,listOpenOrders:()=>M0,listPerpsCandles:()=>Mx,listPerpsFundingHistory:()=>qx,listPerpsTrades:()=>$x,listPositions:()=>$f,listPriceHistory:()=>Mk,listSeries:()=>MA,listSports:()=>GA,listTags:()=>JA,listTeams:()=>iT,listTraderLeaderboard:()=>Ak,listTrades:()=>iv,listUserEarningsAndMarketsConfig:()=>nv,listUserEarningsForDay:()=>J0,mergeComboPosition:()=>lV,mergeMarketPosition:()=>iV,mergePositions:()=>fA,openPerpsSession:()=>Qx,openRfqSession:()=>PA,placeLimitOrder:()=>yx,placeMarketOrder:()=>hx,planCollateralReturn:()=>Zv,postOrder:()=>$d,postOrders:()=>tx,prepareCollateralReturnExecution:()=>iO,prepareErc1155ApprovalForAll:()=>ZN,prepareErc20Approval:()=>JN,prepareErc20Transfer:()=>FO,prepareGaslessTransaction:()=>Or,prepareLimitOrder:()=>cx,prepareLimitOrderPosting:()=>k5,prepareMarketOrder:()=>lx,prepareMarketOrderPosting:()=>w5,prepareMergeComboPosition:()=>hA,prepareMergeMarketPosition:()=>mA,prepareMergePositions:()=>NO,preparePerpsDeposit:()=>_O,prepareRedeemComboPosition:()=>hV,prepareRedeemMarketPositions:()=>OO,prepareRedeemPosition:()=>yA,prepareRedeemPositions:()=>LO,prepareSplitComboPosition:()=>uA,prepareSplitMarketPosition:()=>cA,prepareSplitPosition:()=>CO,prepareTradingApprovals:()=>eO,redeemPositions:()=>wA,requestComboQuote:()=>RA,resignDepositWalletExecuteRequest:()=>fv,resolveConditionByToken:()=>rO,resolveEstimatedMarketPrice:()=>dO,resolveMarketPriceFromOrderBook:()=>Jk,revokeBuilderApiKey:()=>P8,revokePerpsCredentials:()=>Xx,revokeSessionKey:()=>zA,search:()=>UA,setupTradingApprovals:()=>xv,signOrder:()=>ax,splitComboPosition:()=>eV,splitMarketPosition:()=>J5,splitPosition:()=>dA,subscribe:()=>Qf,transferErc20:()=>lT,transferPerpsCollateral:()=>eA,updateBalanceAllowance:()=>ON,waitForComboFill:()=>NA,waitForOrderFillSettlement:()=>dx,withdrawFromPerps:()=>Zx});var XV=L(()=>{"use strict";cT()});var Hge={};fr(Hge,{AI_AGENT_TOOL_NAMES:()=>tS,AbortError:()=>Li,AgentCore:()=>cS,ApproveTokenTool:()=>Gp,BRIDGE_NON_EVM_CHAIN_FAMILY:()=>Qa,BRIDGE_STATUS_POLL_MS:()=>pY,BRIDGE_SUPPORT_URL:()=>mY,BUILDER_CODE:()=>EP,BaseNftAiTool:()=>bs,BaseSwapProvider:()=>Ta,BaseTool:()=>K,BaseWalletActionTool:()=>eo,BuyTokenTool:()=>Kp,CachedResource:()=>xs,ChatHistory:()=>Xp,CoinpoolConfigApi:()=>sg,DEFAULT_CHAIN:()=>er,DEFAULT_PROVIDER:()=>gi,DEFAULT_RPC_BY_CHAIN:()=>Mr,DEFILLAMA_EXTRA_SIGNALS:()=>Oo,DEFILLAMA_POOL_CHAIN_HEXES:()=>Bp,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION:()=>hr,DELAYED_ORDER:()=>_y,DEPOSIT_REFERENCE_USD:()=>tL,DEPOSIT_STABLE_SYMBOLS:()=>Mm,DebridgeProvider:()=>Tp,DefiLlamaEstimatePoolYieldTool:()=>Vp,DefiLlamaPoolByAddressTool:()=>$p,DefiLlamaPoolCandidateResolver:()=>jp,DefiLlamaPoolDetailTool:()=>Hp,DefiLlamaPoolSearchTool:()=>qp,DefiLlamaPoolService:()=>Jn,DefiLlamaTopPoolsTool:()=>Fp,ERC1967_INIT_CODE:()=>Ds,EstimatePoolYieldTool:()=>Ip,GAMES_TAG_ID:()=>LP,GeminiProvider:()=>jt,GeminiSearchAiTool:()=>hp,HEX_TO_PANTOGRAPH:()=>Y1,HIDE_FROM_NEW_TAG_ID:()=>DP,KeyringSettingApi:()=>lg,KnowledgeBase:()=>Zp,LendingMarketDetailTool:()=>_u,LendingMarketsTool:()=>Iu,LendingReadService:()=>Eu,LendingService:()=>io,LendingSupplyService:()=>Ru,MARKET_ORDER:()=>qm,MARKET_STREAM:()=>Hm,MULTICALL3_ADDRESS:()=>vt,ManageLiquidityRedirectTool:()=>bc,MoralisService:()=>De,NATIVE_GAS_LIMIT:()=>wz,NATIVE_TOKEN_PLACEHOLDER:()=>IP,NFC_AGENT_TOOL_NAMES:()=>eS,NFC_AMAZON_DEFAULT_DOMAIN:()=>fL,NFC_AMAZON_DOMAINS:()=>hL,NFTContractInfoTool:()=>cp,NFTMetadataTool:()=>up,NFT_AGENT_TOOL_NAMES:()=>ZT,NfcBuyTool:()=>mp,NfcInfoTool:()=>pp,NoFormTool:()=>gg,ONBOARDING_STEP:()=>on,ONBOARDING_TRACKING:()=>Iy,ORDER_INPUT_ERROR:()=>Us,OpenAddLiquidityFormTool:()=>fc,OpenSupplyFormTool:()=>Nu,PERPS_DEPOSIT_CONTRACT:()=>CP,POLYGON_CHAIN_ID:()=>Bm,POLYGON_HEX_CHAIN_ID:()=>Vi,POLYMARKET_API:()=>Hi,POLYMARKET_LIVE_DATA_WS:()=>_P,POLYMARKET_WEB_URL:()=>$i,POOL_UNISWAP_AGENT_TOOL_NAMES:()=>rS,POSITION_DUST_SHARES:()=>BP,PREDICTION_ACTIVITY_TYPES:()=>UP,PREDICTION_AGENT_TOOL_NAMES:()=>XT,PREDICTION_CATEGORIES:()=>ji,PREDICTION_SORTS:()=>Fm,PUSD_ADDRESS:()=>Os,PUSD_DECIMALS:()=>Ls,PantographService:()=>Ft,PolymarketApiError:()=>Ys,PolymarketOnboardingError:()=>hi,PolymarketRedeemError:()=>fa,PolymarketService:()=>Ye,PolymarketTradeError:()=>ha,PolymarketWithdrawError:()=>gs,PoolByAddressTool:()=>Rp,PoolDetailTool:()=>Pp,PoolFallbackAiTool:()=>fp,PoolPriceRangesTool:()=>yc,PoolSearchTool:()=>Ep,PoolService:()=>Et,PoolSwapRouter:()=>vp,PredictionActivityTool:()=>np,PredictionDepositTool:()=>op,PredictionMarketDetailTool:()=>ep,PredictionMarketsTool:()=>Jd,PredictionPortfolioTool:()=>tp,PredictionSetupTool:()=>rp,PredictionTradeTool:()=>sp,PredictionWithdrawTool:()=>ip,PreviewAddLiquidityTool:()=>gc,PublicClient:()=>Ha,REDEEM:()=>Xa,RELAYER_DEPLOY_POLL:()=>Ry,RELAYER_SUBMIT_PATH:()=>Ey,RelayProvider:()=>bp,Router:()=>em,SUPPLIABLE_TYPES:()=>wP,SUPPORTED_CHAINS:()=>eu,SUPPORTED_CHAINS_LABEL:()=>nu,SWAP_PROVIDER_CONFIG:()=>Ap,SendNativeTool:()=>zp,SendNftTool:()=>Qp,SendTokenTool:()=>Wp,Subagent:()=>ct,SubgraphAddPoolTool:()=>Up,SubgraphCoinPoolPairsTool:()=>Dp,SubgraphPoolByAddressTool:()=>Np,SubgraphPoolByPositionIdTool:()=>Op,SubgraphPoolSearchTool:()=>_p,SubgraphPositionDetailTool:()=>Lp,SubgraphTrendingPoolsTool:()=>Cp,Summarizer:()=>Jp,SwapProviderFactory:()=>ag,SwapRouter:()=>wp,SwapRouterRegistry:()=>ig,SwapTokenTool:()=>Yp,Synthesizer:()=>tm,TOKEN_AGENT_TOOL_NAMES:()=>JT,TRADE_ERROR:()=>gt,TRADING_APPROVALS_METADATA:()=>NP,TRANSFER_TOPIC:()=>oz,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Q1,TokenAnalyticsTool:()=>du,TokenHoldersTool:()=>uu,TokenInfoTool:()=>cu,TokenScoreTool:()=>pu,ToolRegistry:()=>Zc,TopGainersTool:()=>hu,TopPoolsTool:()=>Sp,TransactionByHashTool:()=>Pu,TrendingTokensTool:()=>mu,UNISWAP_CHAIN_SLUG:()=>ug,UNRESOLVED_ASSET:()=>Ka,UP_OR_DOWN_TAG_ID:()=>OP,UpstashKnowledgeBase:()=>Ia,UserSwapRouter:()=>kp,WALLET_ACTION_AGENT_TOOL_NAMES:()=>oS,WALLET_AGENT_TOOL_NAMES:()=>QT,WALLET_DERIVATION:()=>jr,WITHDRAW:()=>xn,WalletApprovalsTool:()=>Au,WalletDefiPositionsTool:()=>Tu,WalletDefiProtocolPositionsTool:()=>Su,WalletHistoryTool:()=>bu,WalletLendingPositionsTool:()=>Cu,WalletNFTsTool:()=>lp,WalletNftTransfersTool:()=>vu,WalletPnlSummaryTool:()=>ku,WalletPnlTool:()=>xu,WalletTokenBalancesTool:()=>yu,WalletTokenTransfersTool:()=>wu,WebsiteTrustKeyringAgent:()=>uS,ZERO_ADDRESS:()=>Pt,adjustBuyAmountForFees:()=>GP,allInBuyNotional:()=>XD,amazonDomainForLanguage:()=>gL,apiClient:()=>se,applyMarketEvent:()=>nL,applyYieldConversions:()=>my,bestPrice:()=>eU,buildApprovalCalls:()=>ZO,buildApprovals:()=>qT,buildBuilderSignature:()=>DI,buildChallenge:()=>JS,buildRangePresets:()=>vL,buildUniswapPoolUrl:()=>Ur,builderApiKey:()=>UI,buyNotional:()=>QD,buyNotionalAfterFee:()=>JD,call:()=>Mo,canDeriveV3PoolAddress:()=>SL,ceil2:()=>YD,chains:()=>Ua,checkNativeGasAffordable:()=>mg,checksumAddress:()=>Sc,clampTick:()=>ks,classifyTradeError:()=>oL,classifyWithdrawError:()=>iL,clearPublicClientCache:()=>Yg,coinpoolConfigApi:()=>Pa,compareDecimal:()=>Oi,completeX402:()=>ZS,configureSupportedChains:()=>ey,configureSwapProvider:()=>MT,convertSusdsShares:()=>Ga,createAiAgent:()=>Ag,createDefaultSubagents:()=>sS,createNfcAgent:()=>xg,createNftAgent:()=>kg,createPolymarketSigner:()=>ma,createPoolUniswapAgent:()=>Tg,createPredictionAgent:()=>wg,createPublicClient:()=>Ni,createTokenAgent:()=>vg,createTransport:()=>_i,createWalletActionAgent:()=>Sg,createWalletAgent:()=>bg,createX402SignatureProvider:()=>tP,decodeAbiParameters:()=>Dn,decodeErrorResult:()=>_c,decodeFunctionData:()=>ES,decodeFunctionResult:()=>Do,defiLlamaPoolInfoScope:()=>pr,defiLlamaPoolSupportsLabel:()=>mr,deployDepositWallet:()=>vw,depositPriceImpact:()=>nj,deriveBeaconDepositWallet:()=>NI,deriveDepositWallet:()=>LI,deriveSafeWallet:()=>OI,deriveUupsDepositWallet:()=>CI,deriveV3PoolAddress:()=>PL,displayFromChallenge:()=>M1,effectivePriceUSD:()=>Cm,encodeAbiParameters:()=>Ec,encodeApprove:()=>FT,encodeErrorResult:()=>xS,encodeFunctionData:()=>Le,encodeSignedHeader:()=>eP,erc1155Abi:()=>$g,erc20Abi:()=>Ve,erc20Abi_bytes32:()=>Fc,erc721Abi:()=>qc,estimateGas:()=>Bc,estimateNativeGasReserveWei:()=>dg,estimateTransactionFeeWei:()=>RL,ethCallAt:()=>cD,ethCallByChain:()=>uK,eventHeadline:()=>Uy,eventUrl:()=>jP,evmDepositAssets:()=>gT,exactAmountString:()=>$a,extractOutRaw:()=>ez,extractQuoteError:()=>tz,fallback:()=>Ci,feePerShare:()=>zi,feeWeiToNative:()=>IL,fetchOnboardingSnapshot:()=>fs,fetchTopMarketplaces:()=>yL,fetchTradingApprovalsStatus:()=>hT,fetchUnderlyingPricesUSD:()=>Lm,findWalletDepositOptions:()=>fT,floor2:()=>Za,floorToDecimals:()=>gr,formatDefiLlamaPool:()=>Ln,getAbiItem:()=>Si,getAddress:()=>yS,getBalance:()=>Oc,getBlock:()=>Mc,getBlockNumber:()=>Cc,getCashBalance:()=>cd,getCashBalanceBaseUnits:()=>Sh,getChain:()=>kn,getChainContractAddress:()=>dm,getChainId:()=>Nc,getChainMeta:()=>Co,getCode:()=>Pi,getDefaultRpcUrl:()=>$S,getGasPrice:()=>Uc,getNativeTokenInfo:()=>mc,getPolymarketBuilderCode:()=>Ou,getPublicClient:()=>Rt,getRevertReason:()=>am,getRpcOverrides:()=>fm,getStorageAt:()=>Lc,getTokenPriceUSD:()=>uy,getTransactionCount:()=>Dc,http:()=>so,humanToWei:()=>Is,ingestKnowledgeBase:()=>Mz,isAbortError:()=>ja,isAddress:()=>fe,isAddressEqual:()=>bS,isEvmAddress:()=>zr,isMarketOpen:()=>jm,isPaymentRequired:()=>eG,isShareBasedProtocol:()=>au,isShareBasedYieldToken:()=>eD,isSupplyChain:()=>by,keyringSettingApi:()=>Sa,listCandidateChains:()=>bP,listSupplyChains:()=>yy,mapEvent:()=>Dy,mapMarket:()=>VP,marketFee:()=>Vm,marketProtocol:()=>$m,moneylineMarket:()=>Ja,mulDivFloor:()=>Va,multicall:()=>Qc,multicall3Abi:()=>oo,multicallRaw:()=>Ri,nativeGasShortfall:()=>kz,nfcAmazonSearchUrl:()=>CT,normaliseCountry:()=>NT,normalizeDecimal:()=>Xc,normalizeLevels:()=>el,normalizePriceRangeToPool:()=>yp,normalizeText:()=>St,onboardingStep:()=>ZV,openSecureClient:()=>Yd,parseAbi:()=>CS,parseAbiItem:()=>qg,parseAbiParameters:()=>cm,parsePolymarketUrl:()=>zm,parsePredictionHint:()=>Wm,pickLogo:()=>yi,placePredictionOrder:()=>ij,planYieldTokenConversions:()=>fP,predictionHint:()=>By,prepareMarketOrder:()=>ZD,priceToTick:()=>pc,protocolLabelFor:()=>yr,psm3For:()=>py,pusdFromBaseUnits:()=>sL,pusdToBaseUnits:()=>vT,quoteBuyAsPolymarket:()=>WP,quoteBuyUsd:()=>Du,quoteDeposit:()=>ng,quoteMarketOrder:()=>YP,quoteSellShares:()=>KP,quoteWithdrawal:()=>lj,readContract:()=>Fo,readPaymentError:()=>U1,readPaymentRequired:()=>Xg,readProtocolFeeWei:()=>HT,readReceipt:()=>B1,readSpendableBalance:()=>fg,readTokenUsdPrice:()=>hg,redeemPredictionPositions:()=>uj,registerMaybeNoForm:()=>YT,remoteBuilderSigning:()=>FF,requestWithX402:()=>ZW,resolveAccountWallet:()=>yw,resolveCategory:()=>My,resolveGasLimit:()=>vz,resolveNfcShopLinks:()=>dp,resolveRawYieldAsset:()=>z1,resolveRawYieldIdentity:()=>za,resolveRawYieldProtocol:()=>j1,resolveRpcUrl:()=>Ho,resolveRpcUrls:()=>qa,resolveTokenPriceUSD:()=>Nm,roundTickToSpacing:()=>vs,rpcCall:()=>lD,runPolymarketOnboarding:()=>ej,setPolymarketBuilderCode:()=>RP,setRpcOverrides:()=>Fa,slippagePrice:()=>Fy,spendableNative:()=>pg,swapProviderFactory:()=>xp,swapRouterRegistry:()=>BT,tickToPrice:()=>_o,ticketFee:()=>zP,toBuilderAuthorization:()=>Zo,toEventSelector:()=>wS,toFunctionSelector:()=>Es,toPantographChain:()=>bG,toPlainDecimal:()=>ym,unitPriceUSD:()=>lu,upDownWindow:()=>Oy,valueYieldTokens:()=>hy,walletDepositAssets:()=>eL,watchCryptoPrice:()=>WD,watchOrderBooks:()=>oj,weiToHuman:()=>Jc,withdrawDestinations:()=>wT,withdrawFromPolymarket:()=>cj});module.exports=zz(Hge);var qL=ML(require("axios"));var FL="0.3.24";var Gz=`keyring-agent-core/${FL} (Keyring Chatbot Agent; +https://keyring.app)`,dS=null;function HL(e){dS=e}var Kz=["payment-signature","x-payment"];function Yz(e){return e?Object.keys(e).some(t=>Kz.includes(t.toLowerCase())):!1}var $L;function rm(e){$L=e}var Qz=3e4,Xz=typeof process<"u"&&process.versions?.node!=null,pS=class{instance;constructor(t={}){this.instance=qL.default.create({baseURL:t.baseURL,timeout:t.timeout??Qz,validateStatus:()=>!0,headers:{Accept:"application/json",...Xz?{"Accept-Encoding":"gzip, deflate, br","User-Agent":t.userAgent??Gz}:{},...t.headers}})}async request(t,n,r,o={}){let s=o.signal??$L,i=await this.instance.request({...o,signal:s,method:t,url:n,data:r}),a={};for(let[c,u]of Object.entries(i.headers??{}))u!=null&&(a[c.toLowerCase()]=String(u));let l={ok:i.status>=200&&i.status<300,status:i.status,statusText:i.statusText,data:i.data,headers:a};if(l.status===402&&dS&&!Yz(o.headers)){let c=await dS(l,{url:n,method:String(t),body:r,headers:o.headers});if(c)return this.request(t,n,r,{...o,headers:{...o.headers,...c}})}return l}get(t,n){return this.request("GET",t,void 0,n)}post(t,n,r){return this.request("POST",t,n,r)}put(t,n,r){return this.request("PUT",t,n,r)}patch(t,n,r){return this.request("PATCH",t,n,r)}delete(t,n){return this.request("DELETE",t,void 0,n)}},se=new pS;function he(e){let{data:t,status:n,statusText:r}=e,o=r?`HTTP ${n} ${r}`:`HTTP ${n}`;if(typeof t=="string")return t.trim()||o;if(t&&typeof t=="object"){let s=t,i=l=>l&&typeof l=="object"?l.message:void 0,a=[s.message,s.errorMessage,s.error,s.error_description,s.detail,i(s.error),i(s.data)];for(let l of a)if(typeof l=="string"&&l.trim())return l.trim()}return o}function Jz(e){return e instanceof $e?e.details||e.shortMessage:e instanceof Error?e.message:typeof e=="string"?e:""}var $e=class extends Error{name="BaseError";shortMessage;details;metaMessages;constructor(t,n={}){let r=n.details??Jz(n.cause),o=n.metaMessages??[],s=[t||"An error occurred.",...o.length>0?["",...o]:[],...r?["",`Details: ${r}`]:[]].join(`
|
|
9
9
|
`);super(s,n.cause!==void 0?{cause:n.cause}:void 0),this.shortMessage=t,this.details=r,this.metaMessages=o,n.name&&(this.name=n.name)}walk(t){return VL(this,t)}};function VL(e,t){if(t?.(e))return e;let n=e&&typeof e=="object"?e.cause:void 0;return n!=null?VL(n,t):t?null:e}var wi=class extends $e{name="AbiParameterTypeError";constructor(t){super(`Type "${t}" is not a valid ABI type.`,{metaMessages:["Supported: address, bool, string, bytes, bytesN, (u)intN, tuple, and arrays of those."]})}},Rg=class extends $e{name="AbiEncodingLengthMismatchError";constructor({expectedLength:t,givenLength:n}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${t}`,`Given length (values): ${n}`]})}},Ig=class extends $e{name="AbiEncodingArrayLengthMismatchError";constructor({expectedLength:t,givenLength:n,type:r}){super(`ABI encoding array length mismatch for type ${r}.`,{metaMessages:[`Expected length: ${t}`,`Given length: ${n}`]})}},no=class extends $e{name="InvalidAbiValueError";constructor({type:t,value:n,reason:r}){super(`Invalid value for ABI type "${t}".`,{metaMessages:[`Value: ${jL(n)}`,`Reason: ${r}`]})}},_g=class extends $e{name="IntegerOutOfRangeError";constructor({type:t,value:n,min:r,max:o}){super(`Number "${n}" is not in safe ${t} range.`,{metaMessages:[`Range: ${r} \u2026 ${o}`]})}},xc=class extends $e{name="InvalidAddressError";constructor(t){super(`Address "${jL(t)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function jL(e){if(typeof e=="bigint")return e.toString();if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var Cg=class extends $e{name="AbiEncodingBytesSizeMismatchError";constructor({expectedSize:t,value:n}){super(`Size of bytes "${n}" does not match expected size of bytes${t}.`)}},vi=class extends $e{name="AbiDecodingZeroDataError";constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{metaMessages:["The contract returned no data. Usually this means:","- the address is not a contract on this chain,","- the function does not exist on it, or","- the call was made before the contract was deployed."]})}},Ng=class extends $e{name="AbiDecodingDataSizeTooSmallError";data;params;size;constructor({data:t,params:n,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${n.map(o=>o.type).join(", ")})`,`Data: ${t} (${r} bytes)`]}),this.data=t,this.params=n,this.size=r}},Ac=class extends $e{name="AbiDecodingOutOfBoundsError";constructor({position:t,length:n}){super(`Position ${t} is out of bounds (${n} bytes).`,{metaMessages:["The return data is truncated or not ABI-encoded."]})}},Og=class extends $e{name="AbiItemNotFoundError";constructor({name:t,type:n="function"}){super(`${n[0].toUpperCase()}${n.slice(1)} "${t}" not found on ABI.`,{metaMessages:["Make sure you are using the correct ABI and that the item exists on it."]})}},ki=class extends $e{name="InvalidAbiSignatureError";constructor(t,n){super(`Invalid ABI signature: "${t}".`,{metaMessages:n?[n]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']})}};var Zz=/^0x[0-9a-fA-F]*$/;function Ca(e,{strict:t=!0}={}){return typeof e!="string"?!1:t?Zz.test(e):e.startsWith("0x")}function Lo(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}function om(e){return typeof e=="string"?Math.ceil(Lo(e).length/2):e.length}function Na(e,t,n){let r=Lo(e),o=(t??0)*2,s=n===void 0?r.length:n*2;return`0x${r.slice(o,s)}`}function Lg(e){return`0x${e.map(Lo).join("")}`}function Oa(e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function xi(e){let t=Lo(e),n=t.length%2?`0${t}`:t,r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(n.slice(o*2,o*2+2),16);return r}function Ps(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return`0x${t}`}function mS(e){return new TextEncoder().encode(e)}function hS(e){return new TextDecoder().decode(e)}function Zn(e,t={}){let{size:n,signed:r}=t,o=BigInt(e);if(o<0n){if(!n)throw new Error("numberToHex: negative values require a `size`");o+=1n<<BigInt(n*8)}else if(r&&n){let i=(1n<<BigInt(n*8-1))-1n;if(o>i)throw new Error(`numberToHex: ${e} overflows int${n*8}`)}let s=o.toString(16);if(!n)return`0x${s}`;if(s.length>n*2)throw new Error(`numberToHex: ${e} overflows ${n} bytes`);return`0x${s.padStart(n*2,"0")}`}function fS(e,t=32){if(e.length>t)throw new Error(`padLeft: ${e.length} bytes exceeds ${t}`);let n=new Uint8Array(t);return n.set(e,t-e.length),n}function gS(e,t=32){if(e.length>t)throw new Error(`padRight: ${e.length} bytes exceeds ${t}`);let n=new Uint8Array(t);return n.set(e),n}function La(e){let t=1n<<256n,n=(e%t+t)%t;return xi(n.toString(16).padStart(64,"0"))}function Tc(e,{signed:t=!1}={}){let n=BigInt(Ps(e));if(!t)return n;let r=BigInt(e.length*8);return n>=1n<<r-1n?n-(1n<<r):n}function ro(e,{signed:t=!1}={}){return Lo(e)?Tc(xi(e),{signed:t}):0n}function Dg(e,t={}){return Number(ro(e,t))}var zL=require("js-sha3");var eW=/^0x[0-9a-fA-F]{40}$/;function fe(e){return typeof e=="string"&&eW.test(e)}function Sc(e){let t=Lo(e).toLowerCase(),n=(0,zL.keccak_256)(t),r="";for(let o=0;o<t.length;o++)r+=parseInt(n[o],16)>=8?t[o].toUpperCase():t[o];return`0x${r}`}function yS(e){if(!fe(e))throw new Error(`Address "${e}" is invalid.`);return Sc(e)}function bS(e,t){return fe(e)&&fe(t)&&e.toLowerCase()===t.toLowerCase()}var Ug=require("js-sha3");function Bg(e){return`0x${(0,Ug.keccak_256)(e)}`}function WL(e){return`0x${(0,Ug.keccak_256)(new TextEncoder().encode(e))}`}function Ai(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function Ti(e){return e.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function sm(e){let t=Ti(e.type);return t==="tuple"||t.startsWith("tuple[")?`(${(e.components??[]).map(sm).join(",")})${t.slice(5)}`:t}function Pc(e){return`${e.name??""}(${(e.inputs??[]).map(sm).join(",")})`}function Es(e){let t=typeof e=="string"?e:Pc(e);return`0x${(0,Ug.keccak_256)(new TextEncoder().encode(t)).slice(0,8)}`}function wS(e){let t=typeof e=="string"?e:Pc(e);return WL(t)}function GL(e,t){let n=Ti(t.type),r=Ai(n);if(r){let[o,s]=r;return!Array.isArray(e)||o!==null&&e.length!==o?!1:e.every(i=>GL(i,{...t,type:s}))}if(n==="tuple"){let o=t.components??[];return Array.isArray(e)?e.length===o.length:typeof e=="object"&&e!==null}return n==="address"?typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e):n==="bool"?typeof e=="boolean":n==="string"?typeof e=="string":n.startsWith("bytes")?typeof e=="string"||e instanceof Uint8Array:n.startsWith("uint")||n.startsWith("int")?typeof e=="number"||typeof e=="bigint"||typeof e=="string":!0}function Si({abi:e,name:t,args:n,type:r}){let o=r??"function",s=e.filter(a=>(a.type??"function")===o);if(t.startsWith("0x")&&t.length===10)return s.find(a=>Es(a)===t.toLowerCase());if(t.includes("("))return s.find(a=>Pc(a)===t);let i=s.filter(a=>a.name===t);return i.length<=1||!n?i[0]:i.find(a=>{let l=a.inputs??[];return l.length===n.length&&l.every((c,u)=>GL(n[u],c))})??i[0]}function Da(e){let t=Si(e);if(!t)throw new Og({name:e.name,type:e.type??"function"});return t}function KL(e){let t=new Uint8Array(Math.ceil(e.length/32)*32);return t.set(e),{dynamic:!0,encoded:Oa([La(BigInt(e.length)),t])}}function YL(e,t){let n=e.slice(t.length),r=n===""?256:Number(n);if(!Number.isInteger(r)||r<8||r>256||r%8!==0)throw new wi(e);return r}function QL(e,t){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new no({type:t,value:e,reason:"expected an integer, got a fractional number"});return BigInt(e)}if(typeof e=="string"&&e.trim()!=="")try{return BigInt(e.trim())}catch{throw new no({type:t,value:e,reason:"string is not a valid integer"})}throw new no({type:t,value:e,reason:"expected a bigint, number or numeric string"})}function XL(e,{bits:t,signed:n,type:r}){let o=n?(1n<<BigInt(t-1))-1n:(1n<<BigInt(t))-1n,s=n?-(1n<<BigInt(t-1)):0n;if(e<s||e>o)throw new _g({type:r,value:e,min:s,max:o})}function JL(e,t){if(e instanceof Uint8Array)return e;if(typeof e=="string"){if(!Ca(e))throw new no({type:t,value:e,reason:"expected 0x-prefixed hex"});return xi(e)}throw new no({type:t,value:e,reason:"expected a hex string or Uint8Array"})}function vS(e,t){let n=Ai(e.type);if(n){let[o,s]=n;if(!Array.isArray(t))throw new no({type:e.type,value:t,reason:"expected an array"});return tW({...e,type:s},t,o,e.type)}if(e.type==="tuple")return nW(e,t);let r=Ti(e.type);if(r==="address"){if(!fe(t))throw new xc(t);return{dynamic:!1,encoded:fS(xi(Lo(t).toLowerCase()))}}if(r==="bool"){if(typeof t!="boolean")throw new no({type:r,value:t,reason:"expected a boolean"});let o=new Uint8Array(32);return o[31]=t?1:0,{dynamic:!1,encoded:o}}if(/^uint\d*$/.test(r)){let o=QL(t,r);return XL(o,{bits:YL(r,"uint"),signed:!1,type:r}),{dynamic:!1,encoded:La(o)}}if(/^int\d*$/.test(r)){let o=QL(t,r);return XL(o,{bits:YL(r,"int"),signed:!0,type:r}),o<0n&&(o+=1n<<256n),{dynamic:!1,encoded:La(o)}}if(/^bytes\d+$/.test(r)){let o=Number(r.slice(5));if(o<1||o>32)throw new wi(e.type);let s=JL(t,r);if(s.length!==o)throw new Cg({expectedSize:o,value:String(t)});return{dynamic:!1,encoded:gS(s)}}if(r==="bytes")return KL(JL(t,r));if(r==="string"){if(typeof t!="string"&&!(t instanceof Uint8Array))throw new no({type:r,value:t,reason:"expected a string"});return KL(typeof t=="string"?mS(t):t)}throw new wi(e.type)}function kS(e){let t=0;for(let{dynamic:s,encoded:i}of e)t+=s?32:i.length;let n=[],r=[],o=0;for(let{dynamic:s,encoded:i}of e)s?(n.push(La(BigInt(t+o))),r.push(i),o+=i.length):n.push(i);return Oa([...n,...r])}function tW(e,t,n,r){let o=n===null;if(!o&&t.length!==n)throw new Ig({expectedLength:n,givenLength:t.length,type:r});let s=!1,i=[];for(let a of t){let l=vS(e,a);l.dynamic&&(s=!0),i.push(l)}if(o||s){let a=kS(i);if(!o)return{dynamic:!0,encoded:a};let l=La(BigInt(i.length));return{dynamic:!0,encoded:i.length>0?Oa([l,a]):l}}return{dynamic:!1,encoded:Oa(i.map(a=>a.encoded))}}function nW(e,t){let n=e.components??[],r=!1,o=[];for(let s=0;s<n.length;s++){let i=n[s],a=vS(i,Array.isArray(t)?t[s]:t[i.name??""]);a.dynamic&&(r=!0),o.push(a)}return{dynamic:r,encoded:r?kS(o):Oa(o.map(s=>s.encoded))}}function Ec(e,t){if(e.length!==t.length)throw new Rg({expectedLength:e.length,givenLength:t.length});return e.length===0?"0x":Ps(kS(e.map((n,r)=>vS(n,t[r]))))}function Le({abi:e,functionName:t,args:n=[]}){let r=Da({abi:e,name:t,args:n,type:"function"}),o=Es(r),s=r.inputs??[];return s.length===0?o:Lg([o,Ec(s,n)])}function xS({abi:e,errorName:t,args:n=[]}){let r=Da({abi:e,name:t,args:n,type:"error"}),o=r.inputs??[],s=Es(r);return o.length===0?s:Lg([s,Ec(o,n)])}function rW(e){let t=e.replace(/^u?int/,"");return t?Number(t):256}function im(e,t){if(t<0||t+32>e.length)throw new Ac({position:t,length:e.length});return e.subarray(t,t+32)}function SS(e,t){let n=Tc(im(e,t));if(n>BigInt(e.length))throw new Ac({position:Number(n),length:e.length});return Number(n)}function AS(e){let t=Ai(e.type);if(t){let[r,o]=t;return r===null||AS({...e,type:o})}if(e.type==="tuple")return(e.components??[]).some(AS);let n=Ti(e.type);return n==="bytes"||n==="string"}function TS(e){let t=Ai(e.type);if(t){let[n,r]=t;return n===null?32:n*TS({...e,type:r})}return e.type==="tuple"?(e.components??[]).reduce((n,r)=>n+TS(r),0):32}function PS(e,t,n){let r=[],o=t;for(let s of n)AS(s)?(r.push(ZL(e,t+SS(e,o),s)),o+=32):(r.push(ZL(e,o,s)),o+=TS(s));return r}function oW(e,t,n,r){let o=r===null?SS(e,t):r,s=r===null?t+32:t;return PS(e,s,new Array(o).fill(n))}function sW(e,t,n){let r=n.components??[],o=PS(e,t,r);if(r.length===0||r.some(a=>!a.name))return o;let i={};return r.forEach((a,l)=>{i[a.name]=o[l]}),i}function ZL(e,t,n){let r=Ai(n.type);if(r){let[s,i]=r;return oW(e,t,{...n,type:i},s)}if(n.type==="tuple")return sW(e,t,n);let o=Ti(n.type);if(o==="address")return Sc(Ps(im(e,t).subarray(12)));if(o==="bool")return Tc(im(e,t))!==0n;if(/^u?int\d*$/.test(o)){let s=o.startsWith("int"),i=Tc(im(e,t),{signed:s});return rW(o)>48?i:Number(i)}if(/^bytes\d+$/.test(o)){let s=Number(o.slice(5));return Ps(im(e,t).subarray(0,s))}if(o==="bytes"||o==="string"){let s=SS(e,t),i=t+32;if(i+s>e.length)throw new Ac({position:i+s,length:e.length});let a=e.subarray(i,i+s);return o==="bytes"?Ps(a):hS(a)}throw new wi(n.type)}function Dn(e,t){let n=typeof t=="string"?xi(t):t;if(n.length===0){if(e.length>0)throw new vi;return[]}if(n.length<32)throw new Ng({data:typeof t=="string"?t:Ps(t),params:e,size:n.length});return PS(n,0,e)}function ht(e){if(!e)return null;try{let[t]=Dn([{type:"uint256"}],e);return t}catch{return null}}function Ge(e){if(!e)return null;try{let[t]=Dn([{type:"address"}],e),n=t;return/^0x0{40}$/i.test(n)?null:n}catch{return null}}function Rc(e){if(!e)return null;try{let[t]=Dn([{type:"string"}],e),n=e1(t);if(n)return n}catch{}try{let[t]=Dn([{type:"bytes32"}],e);return Fg(t)}catch{return null}}function Ic(e){return Mg(ht(e))}function Mg(e){let t=typeof e=="bigint"?Number(e):typeof e=="number"?e:NaN;return Number.isFinite(t)&&t>=0&&t<=36?t:null}function Fg(e){return typeof e!="string"||!e.startsWith("0x")?null:e1(Buffer.from(e.slice(2),"hex").toString("utf8"))||null}function e1(e){return e.replace(/[^\x20-\x7e]/g,"").trim()}function Do({abi:e,functionName:t,args:n,data:r}){let s=Da({abi:e,name:t,args:n,type:"function"}).outputs??[],i=Dn(s,r);if(i.length!==0)return i.length===1?i[0]:i}function ES({abi:e,data:t}){let n=Na(t,0,4),r=Da({abi:e,name:n,type:"function"}),o=r.inputs??[];return{functionName:r.name,args:o.length===0||om(t)<=4?[]:Dn(o,Na(t,4))}}var t1={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},n1={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},r1={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array.",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."};function _c({abi:e=[],data:t}){let n=Na(t,0,4);if(om(t)<4)throw new Error(`Cannot decode error result: "${t}" is too short.`);let r=[...e,t1,n1],o=Si({abi:r,name:n,type:"error"})??r.find(i=>(i.type??"")==="error"&&Es(i)===n);if(!o)throw new Error(`Unknown error selector "${n}".`);let s=o.inputs??[];return{abiItem:o,errorName:o.name,args:s.length>0?Dn(s,Na(t,4)):void 0}}function am({abi:e,data:t}){if(!(!t||t==="0x"))try{let{errorName:n,args:r}=_c({abi:e,data:t});if(n==="Error")return String(r?.[0]??"");if(n==="Panic"){let o=Number(r?.[0]??0);return r1[o]??`Panic code ${o}.`}return!r||r.length===0?n:`${n}(${r.map(o=>String(o)).join(", ")})`}catch{return}}var iW=new Set(["pure","view","nonpayable","payable"]),aW=new Set(["external","public","internal","private","calldata","memory","storage"]);function IS(e,t){let n=0;for(let r=t;r<e.length;r++)if(e[r]==="(")n++;else if(e[r]===")"&&(n--,n===0))return r;throw new ki(e,"Unbalanced parentheses.")}function s1(e){let t=[],n=0,r="";for(let o of e){if(o==="("&&n++,o===")"&&n--,o===","&&n===0){t.push(r),r="";continue}r+=o}return r.trim()&&t.push(r),t.map(o=>o.trim()).filter(Boolean)}function lW(e){let t=e.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:t?.[1]??"",rest:(t?.[2]??"").trim()}}function o1(e,t){let n=!1,r;for(let o of e)o==="indexed"?n=!0:aW.has(o)||(r=o);return{...t,...r?{name:r}:{},...n?{indexed:!0}:{}}}function _S(e){let t=e.trim();if(t.startsWith("(")){let o=IS(t,0),s=s1(t.slice(1,o)).map(_S),{suffix:i,rest:a}=lW(t.slice(o+1).trim());return o1(a.split(/\s+/).filter(Boolean),{type:`tuple${i}`,components:s})}let[n,...r]=t.split(/\s+/).filter(Boolean);if(!n)throw new ki(e,"Missing parameter type.");return o1(r,{type:n})}function cm(e){return s1(e).map(_S)}function lm(e,t,n){let r=e.indexOf("(",t);if(r===-1)throw new ki(n,"Missing parameter list.");let o=IS(e,r);return{name:e.slice(t,r).trim(),params:cm(e.slice(r+1,o)),rest:e.slice(o+1).trim()}}function RS(e,t){return e.split(/[\s()]+/).find(r=>iW.has(r))??t}function qg(e){let t=e.trim();if(t.startsWith("function ")){let{name:n,params:r,rest:o}=lm(t,9,e),s=o.indexOf("returns"),i=s===-1?o:o.slice(0,s),a=[];if(s!==-1){let l=o.indexOf("(",s);if(l===-1)throw new ki(e,"`returns` without a parameter list.");a=cm(o.slice(l+1,IS(o,l)))}return{type:"function",name:n,inputs:r,outputs:a,stateMutability:RS(i,"nonpayable")}}if(t.startsWith("event ")){let{name:n,params:r}=lm(t,6,e);return{type:"event",name:n,inputs:r}}if(t.startsWith("error ")){let{name:n,params:r}=lm(t,6,e);return{type:"error",name:n,inputs:r}}if(t.startsWith("constructor")){let{params:n,rest:r}=lm(t,11,e);return{type:"constructor",inputs:n,stateMutability:RS(r,"nonpayable")}}if(t.startsWith("fallback")){let{rest:n}=lm(t,8,e);return{type:"fallback",stateMutability:RS(n,"nonpayable")}}if(t.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new ki(e,"Expected function, event, error, constructor, fallback or receive.")}function CS(e){return e.map(qg)}function Uo({blockNumber:e,blockTag:t="latest"}={}){return e!==void 0?Zn(e):t}function um(e){let{account:t,to:n,data:r,value:o,gas:s,gasPrice:i,maxFeePerGas:a,maxPriorityFeePerGas:l,nonce:c}=e,u={};return t&&(u.from=t),n&&(u.to=n),r&&(u.data=r),o!==void 0&&(u.value=Zn(o)),s!==void 0&&(u.gas=Zn(s)),i!==void 0&&(u.gasPrice=Zn(i)),a!==void 0&&(u.maxFeePerGas=Zn(a)),l!==void 0&&(u.maxPriorityFeePerGas=Zn(l)),c!==void 0&&(u.nonce=Zn(c)),u}function NS(e){let t={};for(let[n,r]of Object.entries(e)){let o={};r.balance!==void 0&&(o.balance=Zn(r.balance)),r.nonce!==void 0&&(o.nonce=Zn(r.nonce)),r.code!==void 0&&(o.code=r.code),r.state&&(o.state=r.state),r.stateDiff&&(o.stateDiff=r.stateDiff),t[n]=o}return t}async function Cc(e){return ro(await e.request({method:"eth_blockNumber"}))}async function Nc(e){return Dg(await e.request({method:"eth_chainId"}))}async function Oc(e,{address:t,...n}){return ro(await e.request({method:"eth_getBalance",params:[t,Uo(n)]}))}async function Pi(e,{address:t,...n}){let r=await e.request({method:"eth_getCode",params:[t,Uo(n)]});return!r||r==="0x"?void 0:r}async function Lc(e,{address:t,slot:n,...r}){return await e.request({method:"eth_getStorageAt",params:[t,n,Uo(r)]})??void 0}async function Dc(e,{address:t,...n}){return Dg(await e.request({method:"eth_getTransactionCount",params:[t,Uo(n)]}))}async function Uc(e){return ro(await e.request({method:"eth_gasPrice"}))}async function Hg(e){return ro(await e.request({method:"eth_maxPriorityFeePerGas"}))}async function Bc(e,{blockNumber:t,blockTag:n,...r}){return ro(await e.request({method:"eth_estimateGas",params:[um(r),Uo({blockNumber:t,blockTag:n})]}))}async function Mc(e,{includeTransactions:t=!1,...n}={}){let r=await e.request({method:"eth_getBlockByNumber",params:[Uo(n),t]});return r?{...r,blockNumber:r.number?ro(r.number):void 0,blockTimestamp:r.timestamp?ro(r.timestamp):void 0,baseFee:r.baseFeePerGas?ro(r.baseFeePerGas):void 0}:null}var vt="0xcA11bde05977b3631167028862bE2a173976CA11",i1={id:1,hexId:"0x1",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io"}},contracts:{multicall3:{address:vt,blockCreated:14353601}}},a1={id:10,hexId:"0xa",name:"Optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io","https://optimism-rpc.publicnode.com","https://optimism.drpc.org"]}},blockExplorers:{default:{name:"Optimistic Etherscan",url:"https://optimistic.etherscan.io"}},contracts:{multicall3:{address:vt,blockCreated:4286263}}},l1={id:56,hexId:"0x38",name:"BSC",nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18},rpcUrls:{default:{http:["https://bsc-dataseed.binance.org","https://bsc-rpc.publicnode.com","https://bsc.drpc.org"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com"}},contracts:{multicall3:{address:vt}}},c1={id:137,hexId:"0x89",name:"Polygon",nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com"}},contracts:{multicall3:{address:vt,blockCreated:25770160}}},u1={id:8453,hexId:"0x2105",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org","https://base-rpc.publicnode.com","https://base.drpc.org"]}},blockExplorers:{default:{name:"BaseScan",url:"https://basescan.org"}},contracts:{multicall3:{address:vt,blockCreated:5022}}},d1={id:42161,hexId:"0xa4b1",name:"Arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc","https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io"}},contracts:{multicall3:{address:vt,blockCreated:7654707}}},p1={id:43114,hexId:"0xa86a",name:"Avalanche",nativeCurrency:{name:"Avalanche",symbol:"AVAX",decimals:18},rpcUrls:{default:{http:["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io"}},contracts:{multicall3:{address:vt}}},m1={id:59144,hexId:"0xe708",name:"Linea",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build","https://linea-rpc.publicnode.com","https://linea.drpc.org"]}},blockExplorers:{default:{name:"LineaScan",url:"https://lineascan.build"}},contracts:{multicall3:{address:vt}}},h1={id:100,hexId:"0x64",name:"Gnosis",nativeCurrency:{name:"xDAI",symbol:"XDAI",decimals:18},rpcUrls:{default:{http:["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"]}},blockExplorers:{default:{name:"Gnosisscan",url:"https://gnosisscan.io"}},contracts:{multicall3:{address:vt}}},f1={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:vt}}},g1={id:5e3,hexId:"0x1388",name:"Mantle",nativeCurrency:{name:"Mantle",symbol:"MNT",decimals:18},rpcUrls:{default:{http:["https://rpc.mantle.xyz","https://mantle-rpc.publicnode.com"]}},blockExplorers:{default:{name:"Mantle Explorer",url:"https://explorer.mantle.xyz"}},contracts:{multicall3:{address:vt}}},y1={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:vt}}},Ua=[i1,a1,l1,c1,u1,d1,p1,m1,h1,f1,g1,y1];var b1=new Map,OS=new Map;function cW(e,t){return`${e??"unknown"}|${t.toLowerCase()}`}async function w1(e,t=vt){let n=cW(e.chain?.id??e.chain?.hexId,t),r=b1.get(n);if(r!==void 0)return r;let o=OS.get(n);if(o)return o;let s=(async()=>{try{let a=await Pi(e,{address:t})!==void 0;return b1.set(n,a),a}catch{return!0}finally{OS.delete(n)}})();return OS.set(n,s),s}async function Ba(e,t,n=!1){return n||typeof e.batch?.multicall=="object"&&e.batch.multicall.assumeMulticall3?!0:w1(e,t)}var oo=[{type:"function",name:"aggregate3",stateMutability:"payable",inputs:[{name:"calls",type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],outputs:[{name:"returnData",type:"tuple[]",components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}]}]},{type:"function",name:"getEthBalance",stateMutability:"view",inputs:[{name:"addr",type:"address"}],outputs:[{name:"balance",type:"uint256"}]},{type:"function",name:"getBlockNumber",stateMutability:"view",inputs:[],outputs:[{name:"blockNumber",type:"uint256"}]},{type:"function",name:"getCurrentBlockTimestamp",stateMutability:"view",inputs:[],outputs:[{name:"timestamp",type:"uint256"}]}];var Ve=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint8"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{name:"from",type:"address",indexed:!0},{name:"to",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]},{type:"event",name:"Approval",inputs:[{name:"owner",type:"address",indexed:!0},{name:"spender",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]}],Fc=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];var qc=[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"address"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]}];var $g=[{type:"function",name:"uri",stateMutability:"view",inputs:[{name:"id",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"},{name:"id",type:"uint256"}],outputs:[{name:"",type:"uint256"}]}];var Bo=[{type:"function",name:"asset",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"totalAssets",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"convertToAssets",stateMutability:"view",inputs:[{name:"shares",type:"uint256"}],outputs:[{name:"assets",type:"uint256"}]},{type:"function",name:"convertToShares",stateMutability:"view",inputs:[{name:"assets",type:"uint256"}],outputs:[{name:"shares",type:"uint256"}]}];var Hc=class extends $e{name="ChainNotFoundError";constructor(t){super(`Chain "${t}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]})}},Ma=class extends $e{name="ClientChainNotConfiguredError";constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]})}},Ei=class extends $e{name="ChainDoesNotSupportContractError";constructor({chain:t,contract:n,blockNumber:r}){super(r!==void 0?`Chain "${t}" does not support contract "${n}" at block ${r}.`:`Chain "${t}" does not support contract "${n}".`,{metaMessages:["Pass the contract address explicitly to use it on this chain."]})}};async function LS(e,t,n){let r=new Array(e.length);if(e.length===0)return r;let o=0,s=Math.max(1,Math.min(t>0?t:e.length,e.length));async function i(){for(;;){let a=o++;if(a>=e.length)return;try{r[a]={status:"fulfilled",value:await n(e[a],a)}}catch(l){r[a]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:s},i)),r}function dm({blockNumber:e,chain:t,contract:n}){let r=t.contracts?.[n];if(!r)throw new Ei({chain:t.name,contract:n});if(e!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(e))throw new Ei({blockNumber:e,chain:t.name,contract:n});return r.address}var $c=class extends $e{name="RawContractError";data;constructor({data:t,shortMessage:n="The contract call reverted."}){super(n),this.data=t}},DS=class extends $e{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:t,data:n,functionName:r}){let o=n?am({abi:t,data:n}):void 0,s,i;if(n&&n!=="0x")try{let a=_c({abi:t,data:n});s=a.errorName,i=a.args}catch{}super(o?`The contract function "${r??"call"}" reverted with the following reason:
|
|
10
10
|
${o}`:`The contract function "${r??"call"}" reverted.`,{metaMessages:n&&n!=="0x"?[`Revert data: ${n}`]:[]}),this.reason=o,this.errorName=s,this.errorArgs=i,this.data=n}},US=class extends $e{name="ContractFunctionZeroDataError";constructor({functionName:t}){super(`The contract function "${t??"call"}" returned no data ("0x").`,{metaMessages:["This usually means:","- the address is not a contract on this chain,","- the ABI does not match the deployed contract, or","- the block predates the contract deployment."]})}},BS=class extends $e{name="ContractFunctionExecutionError";abi;address;args;functionName;constructor(t,{abi:n,address:r,args:o,functionName:s,sender:i}){let a=n&&s?Si({abi:n,name:s,args:o}):void 0,l=a?Pc(a):s,c=o&&o.length>0?` args: (${o.map(d=>uW(d)).join(", ")})`:void 0,u=a?.inputs?.length?`(${a.inputs.map(sm).join(", ")})`:"()";super(t instanceof $e?t.shortMessage:`An error occurred calling "${s??"contract"}".`,{cause:t,metaMessages:[...r?[`Contract: ${r}`]:[],...l?[`Function: ${l}${a?"":u}`]:[],...c?[c]:[],...i?[`Sender: ${i}`]:[]]}),this.abi=n,this.address=r,this.args=o,this.functionName=s}},pm=class extends $e{name="CallExecutionError";constructor(t,{to:n,data:r}){super(t instanceof $e?t.shortMessage:"The call failed.",{cause:t,metaMessages:[...n?[`To: ${n}`]:[],...r?[`Data: ${r}`]:[]]})}};function uW(e){if(typeof e=="bigint")return e.toString();if(typeof e=="string")return e;try{return JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n)}catch{return String(e)}}function Vg(e){if(!e||typeof e!="object")return;let t=e,n=t.data;if(typeof n=="string"&&n.startsWith("0x"))return n;if(n&&typeof n=="object"){let r=n.data;if(typeof r=="string"&&r.startsWith("0x"))return r}return t.cause?Vg(t.cause):void 0}function Vc(e,{abi:t,address:n,args:r,functionName:o,sender:s}){let i=Vg(e),a=e instanceof vi?new US({functionName:o}):i!==void 0?new DS({abi:t,data:i,functionName:o}):e;return new BS(a,{abi:t,address:n,args:r,functionName:o,sender:s})}var MS=new Map;function mm({fn:e,id:t,shouldSplitBatch:n,wait:r=0}){let o=()=>MS.get(t)??void 0,s=a=>MS.set(t,a),i=async a=>{o()===a&&MS.delete(t);try{let l=await e(a.map(c=>c.item));a.forEach((c,u)=>c.resolve(l[u]))}catch(l){a.forEach(c=>c.reject(l))}};return{schedule(a){return new Promise((l,c)=>{let u={item:a,resolve:l,reject:c},d=o();if(d)if(n?.([...d.map(m=>m.item),a]))i(d);else{d.push(u);return}let p=[u];s(p),setTimeout(()=>{i(p)},r)})}}}function dW(e){return!!(e.data&&e.to&&!e.account&&!e.value&&!e.gas&&!e.gasPrice&&!e.maxFeePerGas&&!e.maxPriorityFeePerGas&&e.nonce===void 0&&!e.stateOverride)}async function pW(e,t){let{batchSize:n=1024,wait:r=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{blockNumber:o,blockTag:s="latest",data:i,to:a}=t;if(!e.chain)throw new Ma;let l=dm({blockNumber:o,chain:e.chain,contract:"multicall3"});if(!await Ba(e,l,!1))throw new Ei({chain:e.chain.name,contract:"multicall3"});let c=o!==void 0?Zn(o):s,{schedule:u}=mm({id:`${e.uid}.call.${c}`,wait:r,shouldSplitBatch:m=>m.reduce((g,f)=>g+(f.data.length-2)/2,0)>n,fn:async m=>{let g=Le({abi:oo,functionName:"aggregate3",args:[m.map(y=>({allowFailure:!0,callData:y.data,target:y.to}))]}),f=await e.request({method:"eth_call",params:[{to:l,data:g},c]});return Do({abi:oo,functionName:"aggregate3",data:f})}}),{returnData:d,success:p}=await u({data:i,to:a});if(!p)throw new $c({data:d});return d}async function Mo(e,t){let{blockNumber:n,blockTag:r,stateOverride:o,skipBatch:s,...i}=t;if(e.batch?.multicall&&!s&&dW(t))try{let l=await pW(e,{blockNumber:n,blockTag:r,data:i.data,to:i.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof Ma||l instanceof Ei))throw new pm(l,{to:i.to,data:i.data})}let a=[um(i),Uo({blockNumber:n,blockTag:r})];o&&a.push(NS(o));try{let l=await e.request({method:"eth_call",params:a});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new pm(l,{to:i.to,data:i.data})}}var FS=8;function v1(e,t){if(t!==void 0&&t>0)return t;let n=typeof e.batch?.multicall=="object"?e.batch.multicall.fallbackConcurrency:void 0;return n!==void 0&&n>0?n:FS}function hm(e,t,n){if(t)return t;if(!e.chain)throw new Ma;let r=e.chain.contracts?.multicall3;return r?n!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(n)?vt:r.address:vt}async function jc(e,t,n={}){let{concurrency:r,account:o,blockNumber:s,blockTag:i,stateOverride:a}=n;return(await LS(t,v1(e,r),async c=>{let{data:u}=await Mo(e,{to:c.target,data:c.callData,account:o,blockNumber:s,blockTag:i,stateOverride:a,skipBatch:!0});return u??"0x"})).map(c=>c.status==="fulfilled"?{success:!0,returnData:c.value}:{success:!1,returnData:"0x",error:c.reason})}async function Fo(e,t){let{abi:n,address:r,functionName:o,args:s,...i}=t;try{let a=Le({abi:n,functionName:o,args:s}),{data:l}=await Mo(e,{...i,to:r,data:a});return Do({abi:n,functionName:o,args:s,data:l??"0x"})}catch(a){throw Vc(a,{abi:n,address:r,args:s,functionName:o,sender:i.account})}}var mW=1024,hW=50;async function Ri(e,t){let{calls:n,account:r,blockNumber:o,blockTag:s,batchSize:i=mW,maxCalls:a=hW,multicallAddress:l,stateOverride:c,fallbackConcurrency:u}=t,d=n.map(()=>({success:!1,returnData:"0x"}));if(n.length===0)return d;let p=hm(e,l,o),m=[];if(n.forEach((w,v)=>{fe(w.target)&&Ca(w.callData)&&m.push({index:v,call:w})}),m.length===0)return d;if(!await Ba(e,p,l!==void 0))return(await jc(e,m.map(v=>v.call),{account:r,blockNumber:o,blockTag:s,stateOverride:c,concurrency:u})).forEach((v,x)=>{d[m[x].index]={success:v.success,returnData:v.returnData}}),d;let g=[],f;return m.forEach(({call:w,index:v})=>{let x=(w.callData.length-2)/2,k=i>0&&f!==void 0&&f.size+x>i,S=a>0&&f!==void 0&&f.calls.length>=a;(!f||(k||S)&&f.calls.length>0)&&(f={calls:[],indexes:[],size:0},g.push(f)),f.calls.push(w),f.indexes.push(v),f.size+=x}),(await Promise.allSettled(g.map(w=>Fo(e,{abi:oo,address:p,functionName:"aggregate3",args:[w.calls.map(v=>({target:v.target,allowFailure:!0,callData:v.callData}))],account:r,blockNumber:o,blockTag:s,stateOverride:c})))).forEach((w,v)=>{w.status==="fulfilled"&&g[v].indexes.forEach((x,k)=>{let S=w.value[k];S&&(d[x]={success:!!S.success,returnData:S.returnData??"0x"})})}),d}var k1="https://wallet-api.pantograph.app/keyring/chains_v6",fW=6,gW=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,x1={},zc=null;function yW(e){let t=Array.isArray(e.rpcs)?e.rpcs:[],n=typeof e.linkProvider=="string"?[e.linkProvider]:[],r=[];for(let o of[...n,...t]){if(typeof o!="string")continue;let s=o.trim();if(!(!s.startsWith("https://")||gW.test(s))&&(r.includes(s)||r.push(s),r.length>=fW))break}return r}function A1(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!r||typeof r!="object")continue;let o=r,s=qo(n)??(typeof o.chainId=="number"?qo(o.chainId):void 0);if(!s)continue;let i=yW(o);i.length>0&&(t[s]=i)}return t}function T1(e){x1=e}function qS(e){let t=qo(e);return t?x1[t]??[]:[]}function HS(){zc||jg()}function jg(e={}){let{url:t=k1,force:n=!1,debug:r=!1}=e;return zc&&!n||(zc=(async()=>{try{let o=await se.get(t);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=A1(o.data),i=Object.keys(s).length;if(i===0)throw new Error("catalogue contained no usable RPC endpoints");return T1(s),r&&console.log(`[chains] loaded RPC endpoints for ${i} chains from ${t}`),!0}catch(o){if(r){let s=o instanceof Error?o.message:String(o);console.warn(`[chains] remote RPC catalogue unavailable (${s}); using built-in endpoints`)}return zc=null,!1}})()),zc}var bW=new Map(Ua.map(e=>[e.hexId.toLowerCase(),e])),wW=new Map(Ua.map(e=>[e.id,e]));function qo(e){if(typeof e=="number")return Number.isFinite(e)&&e>=0?`0x${e.toString(16)}`:void 0;let t=e.trim().toLowerCase();if(t)return t.startsWith("0x")?/^0x[0-9a-f]+$/.test(t)?t:void 0:/^\d+$/.test(t)?`0x${Number(t).toString(16)}`:void 0}function kn(e){if(typeof e=="number")return wW.get(e);let t=qo(e);return t?bW.get(t):void 0}function Rs(e){return kn(e)?.nativeCurrency}var Mr=Object.fromEntries(Ua.map(e=>[e.hexId,e.rpcUrls.default.http[0]]));function $S(e){return kn(e)?.rpcUrls.default.http[0]}var VS={};function Fa(e){let t={};if(e)for(let[n,r]of Object.entries(e)){if(typeof r!="string"||!r.trim())continue;let o=qo(n)??n.toLowerCase();t[o]=r.trim()}VS=t}function fm(){return{...VS}}function qa(e){HS();let t=qo(e),n=t?VS[t]:void 0,r=qS(e),o=kn(e)?.rpcUrls.default.http??[];return[...new Set([...n?[n]:[],...r,...o])]}function Ho(e){return qa(e)[0]}function jS(e){let t=kn(e);if(!t)return;let n=qa(e),r=t.rpcUrls.default.http;return n.length===0||n.length===r.length&&n.every((o,s)=>o===r[s])?t:{...t,rpcUrls:{default:{http:n}}}}var Ii=class extends $e{name="HttpRequestError";status;url;body;headers;constructor({body:t,details:n,headers:r,status:o,url:s}){super("HTTP request failed.",{details:n,metaMessages:[`URL: ${s}`,...o?[`Status: ${o}`]:[],...t?[`Request body: ${JSON.stringify(t)}`]:[]]}),this.status=o,this.url=s,this.body=t,this.headers=r}},Wc=class extends $e{name="TimeoutError";constructor({body:t,url:n,timeout:r}){super("The request took too long to respond.",{details:`The request timed out after ${r}ms.`,metaMessages:[`URL: ${n}`,...t?[`Request body: ${JSON.stringify(t)}`]:[]]})}},Gc=class extends $e{name="NetworkError";constructor({cause:t,url:n}){super("Could not reach the RPC endpoint.",{cause:t,metaMessages:[`URL: ${n}`]})}},zg=class extends $e{name="UrlRequiredError";constructor(){super("No RPC URL was provided.",{metaMessages:['Pass one to the transport \u2014 http("https://\u2026") \u2014 or give the client a chain that has a default RPC URL.']})}},gm=class extends $e{name="FallbackTransportError";constructor({cause:t,count:n}){super(`All ${n} fallback transports failed.`,{cause:t})}};var Kc=class extends $e{name="RpcRequestError";code;data;constructor({body:t,error:n,url:r,shortMessage:o}){super(o??"RPC request failed.",{details:n.message,metaMessages:[...r?[`URL: ${r}`]:[],...t?[`Request body: ${JSON.stringify(t)}`]:[],`Error code: ${n.code}`]}),this.code=n.code,this.data=n.data}};function Fr(e,t,n){return class extends Kc{static code=t;name=e;constructor(r){super({...r,shortMessage:n})}}}var vW=Fr("ParseRpcError",-32700,"The node could not parse the JSON request."),kW=Fr("InvalidRequestRpcError",-32600,"The JSON request is not valid."),xW=Fr("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),AW=Fr("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),TW=Fr("InternalRpcError",-32603,"The node reported an internal error."),SW=Fr("InvalidInputRpcError",-32e3,"The RPC input is not valid."),PW=Fr("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),EW=Fr("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),RW=Fr("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),IW=Fr("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),zS=Fr("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),_W=Fr("UserRejectedRequestError",4001,"The user rejected the request."),CW=new Map([[-32700,vW],[-32600,kW],[-32601,xW],[-32602,AW],[-32603,TW],[-32e3,SW],[-32001,PW],[-32002,EW],[-32003,RW],[-32004,IW],[-32005,zS],[4001,_W]]);function S1(e){let t=CW.get(e.error.code);return t?new t(e):new Kc(e)}function P1(e){return new Promise(t=>setTimeout(t,e))}async function WS(e,{retryCount:t=2,delay:n=150,shouldRetry:r=()=>!0}={}){let o=0;for(;;)try{return await e()}catch(s){if(o++,o>t||!r({count:o,error:s}))throw s;let i=typeof n=="function"?n({count:o,error:s}):n*2**(o-1);i>0&&await P1(i)}}function GS(e){let t=e?.["retry-after"];if(!t)return;let n=Number(t);if(Number.isFinite(n))return n*1e3;let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var NW=new Set([408,413,429,500,502,503,504]),OW=new Set([401,402,403]);function Wg(e){return e instanceof Wc||e instanceof Gc?!0:e instanceof Ii?e.status?NW.has(e.status)||e.status>=500:!0:e instanceof zS?!0:e instanceof Kc?e.code===-32603:!1}function Gg(e){return e instanceof Ii&&e.status&&OW.has(e.status)?!0:Wg(e)}function Kg(e,{retryCount:t=3,retryDelay:n=150}={}){return function(o,s={}){return WS(()=>e(o),{retryCount:s.retryCount??t,shouldRetry:({error:i})=>Wg(i),delay:({count:i,error:a})=>{let l=a instanceof Ii?GS(a.headers):void 0;return l!==void 0?l:(s.retryDelay??n)*2**(i-1)}})}}function _i({key:e,name:t,type:n,request:r,retryCount:o=3,retryDelay:s=150,timeout:i=1e4},a){return{config:{key:e,name:t,type:n,request:r,retryCount:o,retryDelay:s,timeout:i},request:Kg(r,{retryCount:o,retryDelay:s}),value:a}}function Ci(e,t={}){let{key:n="fallback",name:r="Fallback",retryCount:o=0,retryDelay:s,onTransportError:i}=t;return(a={})=>{let l=e.map(u=>u(a));if(l.length===0)throw new gm({count:0});return _i({key:n,name:r,type:"fallback",request:async u=>{let d;for(let p=0;p<l.length;p++)try{return await l[p].request(u)}catch(m){if(d=m,i?.({error:m,index:p,method:u.method}),!Gg(m))throw m}throw new gm({cause:d,count:l.length})},retryCount:o,retryDelay:s,timeout:a.timeout},{transports:l})}}var E1=0;function R1(){return E1+=1,E1}function LW(e){let t=e?.code;if(t==="ECONNABORTED"||t==="ETIMEDOUT")return!0;let n=e?.message??"";return/timeout/i.test(n)}var Yc=class{url;timeout;fetchOptions;constructor(t,{timeout:n=1e4,fetchOptions:r={}}={}){this.url=t,this.timeout=n,this.fetchOptions=r}async post(t){let n;try{n=await se.post(this.url,t,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(r){throw LW(r)?new Wc({body:t,url:this.url,timeout:this.timeout}):new Gc({cause:r,url:this.url})}if(!n.ok)throw new Ii({body:t,details:he(n),headers:n.headers,status:n.status,url:this.url});return n.data}async request(t){let n={jsonrpc:"2.0",id:R1(),...t};return await this.post(n)??{id:n.id}}async requestBatch(t){let n=t.map(s=>({jsonrpc:"2.0",id:R1(),...s})),r=await this.post(n);if(!Array.isArray(r))return n.map(s=>({id:s.id,error:r?.error??{code:-32603,message:"Malformed batch response."}}));let o=new Map(r.map(s=>[s.id,s]));return n.map((s,i)=>o.get(s.id)??r[i]??{id:s.id,error:{code:-32603,message:"Missing response for batched request."}})}};function I1(e,t,n){if(e.error)throw S1({body:t,error:e.error,url:n});return e.result}function so(e,t={}){let{batch:n,fetchOptions:r,key:o="http",name:s="HTTP JSON-RPC",retryCount:i,retryDelay:a,timeout:l}=t;return({chain:c,retryCount:u,retryDelay:d,timeout:p}={})=>{let{batchSize:m=1e3,wait:g=0}=typeof n=="object"?n:{},f=l??p??1e4,y=e??c?.rpcUrls.default.http[0];if(!y)throw new zg;let w=new Yc(y,{timeout:f,fetchOptions:r});return _i({key:o,name:s,type:"http",retryCount:i??u,retryDelay:a??d,timeout:f,async request({method:v,params:x}){let k={method:v,params:x};if(n){let{schedule:S}=mm({id:`${y}:${m}:${g}`,wait:g,shouldSplitBatch:D=>D.length>m,fn:D=>w.requestBatch(D)});return I1(await S(k),k,y)}return I1(await w.request(k),k,y)}},{url:y})}}var DW=1024;async function Qc(e,t){let{contracts:n,allowFailure:r=!0,account:o,blockNumber:s,blockTag:i,multicallAddress:a,stateOverride:l,fallbackConcurrency:c}=t,u=t.batchSize??(typeof e.batch?.multicall=="object"&&e.batch.multicall.batchSize||DW),d=new Array(n.length);if(n.length===0)return r?d:[];let p=hm(e,a,s),m=[],g;n.forEach((w,v)=>{let{abi:x,address:k,functionName:S,args:D}=w,q;try{if(!fe(k))throw new xc(k);q=Le({abi:x,functionName:S,args:D})}catch(Y){let ee=Vc(Y,{abi:x,address:k,args:D,functionName:S,sender:o});if(!r)throw ee;d[v]={status:"failure",error:ee};return}let V=(q.length-2)/2;(!g||u>0&&g.size+V>u&&g.calls.length>0)&&(g={calls:[],indexes:[],size:0},m.push(g)),g.calls.push({target:k,allowFailure:!0,callData:q}),g.indexes.push(v),g.size+=V}),(await Ba(e,p,a!==void 0)?await Promise.allSettled(m.map(w=>Fo(e,{abi:oo,address:p,functionName:"aggregate3",args:[w.calls],account:o,blockNumber:s,blockTag:i,stateOverride:l}))):await(async()=>{let w=m.flatMap(x=>x.calls.map((k,S)=>({target:k.target,callData:k.callData,index:x.indexes[S]}))),v=await jc(e,w,{account:o,blockNumber:s,blockTag:i,stateOverride:l,concurrency:c});return m.length=0,v.map((x,k)=>(m.push({calls:[],indexes:[w[k].index],size:0}),x.success?{status:"fulfilled",value:[{success:!0,returnData:x.returnData}]}:{status:"rejected",reason:x.error}))})()).forEach((w,v)=>{let x=m[v];if(w.status==="rejected"){for(let k of x.indexes){let S=n[k],D=Vc(w.reason,{abi:S.abi,address:S.address,args:S.args,functionName:S.functionName,sender:o});if(!r)throw D;d[k]={status:"failure",error:D}}return}x.indexes.forEach((k,S)=>{let D=n[k],q=w.value[S];try{if(!q)throw new Error("Multicall returned fewer results than calls.");if(!q.success)throw new $c({data:q.returnData});if(!q.returnData||q.returnData==="0x")throw new vi;let V=Do({abi:D.abi,functionName:D.functionName,args:D.args,data:q.returnData});d[k]={status:"success",result:V}}catch(V){let Y=Vc(V,{abi:D.abi,address:D.address,args:D.args,functionName:D.functionName,sender:o});if(!r)throw Y;d[k]={status:"failure",error:Y}}})});for(let w=0;w<n.length;w++){if(d[w])continue;let v=new Error("Multicall returned no result for this call.");if(!r)throw v;d[w]={status:"failure",error:v}}return r?d:d.map(w=>w.result)}var UW=0,Ha=class{key;name;uid;chain;transport;batch;request;constructor(t={}){let{batch:n,key:r="public",name:o="Public Client",retryCount:s,retryDelay:i,timeout:a}=t;this.chain=MW(t.chain),this.key=r,this.name=o,this.batch=n,this.uid=`${r}-${++UW}-${Math.random().toString(36).slice(2,8)}`;let c=(t.transport??BW(t.rpcUrl,this.chain))({chain:this.chain,retryCount:s,retryDelay:i,timeout:a});this.transport={...c.config,...c.value},this.request=c.request}call(t){return Mo(this,t)}readContract(t){return Fo(this,t)}multicall(t){return Qc(this,t)}multicallRaw(t){return Ri(this,t)}getBlockNumber(){return Cc(this)}getChainId(){return Nc(this)}getBalance(t){return Oc(this,t)}getCode(t){return Pi(this,t)}getStorageAt(t){return Lc(this,t)}getTransactionCount(t){return Dc(this,t)}getGasPrice(){return Uc(this)}estimateMaxPriorityFeePerGas(){return Hg(this)}estimateGas(t){return Bc(this,t)}getBlock(t){return Mc(this,t)}rpc(t,n){return this.request({method:t,params:n})}extend(t){let n=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return Object.assign(n,t(n))}};function BW(e,t){if(e)return so(e);let n=t?.rpcUrls.default.http??[];return n.length>1?Ci(n.map(r=>so(r,{retryCount:1}))):so(n[0])}function MW(e){if(e===void 0)return;if(typeof e=="object")return e;let t=jS(e);if(!t)throw new Hc(e);return t}function Ni(e={}){return new Ha(e)}var KS=new Map;function FW(e,t){return{id:parseInt(e,16),hexId:e,name:`Chain ${parseInt(e,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:t}},contracts:{multicall3:{address:vt}}}}function Rt(e,t={}){let{batch:n=!0,pinRpcUrl:r=!1,fallbackConcurrency:o,assumeMulticall3:s}=t,i=qo(e),a=t.rpcUrl?.trim(),l=i?qa(i):[],c=a?r?[a]:[...new Set([a,...l])]:l;if(c.length===0)throw new Hc(e);let u=`${i??e}|${c.join(",")}|${n?1:0}|${o??""}|${s?1:0}`,d=KS.get(u);if(d)return d;let p=Ni({chain:i&&!kn(i)?FW(i,c):i,transport:c.length===1?so(c[0]):Ci(c.map(m=>so(m,{retryCount:1}))),batch:n?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return KS.set(u,p),p}function Yg(){KS.clear()}function QS(e,t){try{return Rt(e,{rpcUrl:t?.trim()||void 0})}catch{return null}}async function Qt(e,t,n){let r=new Array(t.length).fill(null),o=t.length>0?QS(e,n):null;if(!o)return r;let s=[];if(t.forEach((i,a)=>{!fe(i.target)||!Ca(i.callData)||s.push({index:a,target:i.target,callData:i.callData})}),s.length===0)return r;try{(await Ri(o,{calls:s})).forEach((a,l)=>{a.success&&(r[s[l].index]=a.returnData)})}catch{}return r}function Qg(e){return e?.status==="success"?e.result:void 0}async function YS(e,t){try{return await e.multicall({contracts:t})}catch{return[]}}async function $o(e,t,n){let r=t.map(()=>({symbol:null,decimals:null})),o=t.length>0?QS(e,n):null;if(!o)return r;let s=[];if(t.forEach((l,c)=>{fe(l)&&s.push({index:c,address:l})}),s.length===0)return r;let i=await YS(o,s.flatMap(l=>[{address:l.address,abi:Ve,functionName:"symbol"},{address:l.address,abi:Ve,functionName:"decimals"}]));s.forEach((l,c)=>{let u=Qg(i[c*2]);typeof u=="string"&&u.trim()&&(r[l.index].symbol=u.trim()),r[l.index].decimals=Mg(Qg(i[c*2+1]))});let a=s.filter(l=>r[l.index].symbol===null);if(a.length>0){let l=await YS(o,a.map(c=>({address:c.address,abi:Fc,functionName:"symbol"})));a.forEach((c,u)=>{r[c.index].symbol=Fg(Qg(l[u]))})}return r}async function _1(e,t,n){let r=new Array(t.length).fill(null),o=t.length>0?QS(e,n):null;if(!o)return r;let s=[];return t.forEach((a,l)=>{if(fe(a.contract))try{s.push({index:l,address:a.contract,tokenId:BigInt(a.tokenId)})}catch{}}),s.length===0||(await YS(o,s.map(a=>({address:a.address,abi:qc,functionName:"tokenURI",args:[a.tokenId]})))).forEach((a,l)=>{let c=Qg(a);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(r[s[l].index]=u)}),r}function ym(e){return Xc(String(e))??"0"}function Xc(e){let t=e.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!t)return null;let n=t[1]==="-"?"-":"",r=t[2]??"",o=t[3]??"";if(r===""&&o==="")return null;let s=t[4]?parseInt(t[4],10):0,i=r+o,a=r.length+s,l;return a<=0?l=`0.${"0".repeat(-a)}${i}`:a>=i.length?l=i+"0".repeat(a-i.length):l=`${i.slice(0,a)}.${i.slice(a)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":n+l}function XS(e){let t=Xc(e);if(t===null||t.startsWith("-"))return null;let[n,r=""]=t.split(".");return{mant:BigInt(n+r),frac:r.length}}function Jc(e,t){let n=e<0n,r=(n?-e:e).toString(),o;if(t===0)o=r;else{let s=r.padStart(t+1,"0"),i=s.length-t;o=`${s.slice(0,i)}.${s.slice(i)}`.replace(/0+$/,"").replace(/\.$/,"")}return n?`-${o}`:o}function Is(e,t){let n=Xc(e);if(n===null||n.startsWith("-"))return null;let[r,o=""]=n.split("."),s=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(s||"0");return i>0n?i:null}catch{return null}}function $a(e){if(typeof e=="number")return Number.isFinite(e)&&e>0?ym(e):null;if(typeof e!="string")return null;let t=e.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!t)return null;let n=Xc(t[0]);return n&&n!=="0"&&!n.startsWith("-")?n:null}function gr(e,t){let n=Xc(e);if(n===null||t<0)return e;let r=n.startsWith("-"),[o,s=""]=(r?n.slice(1):n).split(".");if(s.length<=t)return n;let i=t===0?o:`${o}.${s.slice(0,t)}`,a=i.includes(".")?i.replace(/0+$/,"").replace(/\.$/,""):i;return r?`-${a}`:a}function Va(e,t,n,r){let o=XS(e);if(!o||n<=0n||r<0)return e;let s=o.mant*t*10n**BigInt(r)/(n*10n**BigInt(o.frac));return Jc(s,r)}function Oi(e,t){let n=XS(e),r=XS(t);if(!n||!r){let a=Number(e),l=Number(t);return a<l?-1:a>l?1:0}let o=Math.max(n.frac,r.frac),s=n.mant*10n**BigInt(o-n.frac),i=r.mant*10n**BigInt(o-r.frac);return s<i?-1:s>i?1:0}var qW={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},HW="payment-required",$W="PAYMENT-SIGNATURE",VW="X-PAYMENT",jW="payment-response",zW="x-payment-response",WW=600,GW=300,KW={ethereum:1,sepolia:11155111,abstract:2741,"abstract-testnet":11124,base:8453,"base-sepolia":84532,avalanche:43114,"avalanche-fuji":43113,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338,story:1514,educhain:41923,"skale-base-sepolia":324705682,megaeth:4326,monad:143,stable:988,"stable-testnet":2201};function C1(e){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCharCode(r)).join("");return globalThis.btoa(n)}return Buffer.from(e,"utf8").toString("base64")}function O1(e){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let t=globalThis.atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return new TextDecoder("utf-8").decode(n)}return Buffer.from(e,"base64").toString("utf8")}function YW(){let e=new Uint8Array(32),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(e);else for(let n=0;n<32;n++)e[n]=Math.floor(Math.random()*256);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function L1(e){let t=String(e);if(t.includes(":")){let[r,o]=t.split(":"),s=parseInt(o,10);if(r!=="eip155"||Number.isNaN(s))throw new Error(`Unsupported x402 network: ${e} (only EVM "eip155:*" is supported)`);return s}let n=KW[t.toLowerCase()];if(n===void 0)throw new Error(`Unsupported x402 network: ${e}`);return n}function D1(e){if(!e.query||Object.keys(e.query).length===0)return e.url;let t=Object.entries(e.query).map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(r)}`).join("&");return e.url.includes("?")?`${e.url}&${t}`:`${e.url}?${t}`}function Xg(e){let t=e.headers[HW];if(t){let o=N1(QW(t));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let n=e.data,r=n&&typeof n=="object"?n:N1(n);return r&&Array.isArray(r.accepts)?{version:1,payload:r}:null}function N1(e){if(typeof e!="string")return null;try{let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function QW(e){try{return O1(e)}catch{return null}}function XW(e){let t=e.amount??e.maxAmountRequired;return typeof e.scheme!="string"||typeof e.network!="string"||t==null||typeof e.asset!="string"||typeof e.payTo!="string"?null:{scheme:e.scheme,network:e.network,amount:String(t),asset:e.asset,payTo:e.payTo,...typeof e.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:e.maxTimeoutSeconds}:{},...e.extra&&typeof e.extra=="object"?{extra:e.extra}:{},...typeof e.resource=="string"?{resource:e.resource}:{},...typeof e.description=="string"?{description:e.description}:{},...typeof e.mimeType=="string"?{mimeType:e.mimeType}:{},...e.outputSchema!=null?{outputSchema:e.outputSchema}:{}}}function JW(e){let t=null;for(let n of e){let r=XW(n);if(r){if(r.scheme!=="exact"){t=`unsupported scheme "${r.scheme}"`;continue}try{return L1(r.network),r}catch(o){t=o instanceof Error?o.message:String(o)}}}throw new Error(t?`No payable x402 requirement offered (${t}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function JS(e,t,n,r){let o=Xg(e);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:i}=o,a=JW(i.accepts??[]);if(!n)throw new Error("No connected wallet address to build the payment from");let l=L1(a.network),c=Math.floor(Date.now()/1e3),u={from:n,to:a.payTo,value:String(a.amount),validAfter:String(Math.max(0,c-WW)),validBefore:String(c+(a.maxTimeoutSeconds??GW)),nonce:YW()},d={domain:{name:a.extra?.name,version:a.extra?.version,chainId:l,verifyingContract:a.asset},types:qW,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:D1(t),method:t.method??"GET",body:t.body,headers:t.headers},x402Version:s,requirements:a,authorization:u,typedData:d,chainId:l,...i.resource!=null?{resource:i.resource}:{},...i.extensions!=null?{extensions:i.extensions}:{},...r?{userQuery:r}:{}}}async function ZW(e,t,n,r){let o=D1(t),s=await e.request(t.method??"GET",o,t.body,{headers:t.headers});if(s.status===402)return{status:"payment_required",challenge:JS(s,t,n,r)};if(!s.ok)throw new Error(he(s));return{status:"ok",data:s.data}}async function ZS(e,t,n){let{url:r,method:o,body:s,headers:i}=t.request,a=await e.request(o,r,s,{headers:{...i??{},...eP(t,n)}});if(a.ok)return a.data;throw new Error(tG(a)??he(a))}function eG(e){return Xg(e)!==null}function U1(e){let t=B1(e);return t?.errorReason?t.errorReason:Xg(e)?.payload.error??null}function tG(e){let t=U1(e);return t?`x402 payment rejected: ${t}`:null}var nG={1:"Ethereum",10:"Optimism",137:"Polygon",143:"Monad",988:"Stable",1328:"Sei Testnet",1329:"Sei",1514:"Story",2201:"Stable Testnet",2741:"Abstract",3338:"Peaq",4326:"MegaETH",4689:"IoTeX",8453:"Base",11124:"Abstract Testnet",41923:"EDU Chain",42161:"Arbitrum",43113:"Avalanche Fuji",43114:"Avalanche",80002:"Polygon Amoy",84532:"Base Sepolia",324705682:"SKALE Base Sepolia",11155111:"Sepolia"};function eP(e,t){let{requirements:n,authorization:r}=e,o={signature:t,authorization:r};if(e.x402Version===1){let i={x402Version:1,scheme:n.scheme,network:n.network,payload:o};return{[VW]:C1(JSON.stringify(i))}}let s={x402Version:2,...e.resource!=null?{resource:e.resource}:{},accepted:rG(n),payload:o,...e.extensions!=null?{extensions:e.extensions}:{}};return{[$W]:C1(JSON.stringify(s))}}function rG(e){let{resource:t,description:n,mimeType:r,outputSchema:o,...s}=e;return s}function B1(e){let t=e.headers[jW]??e.headers[zW];if(!t)return null;try{return JSON.parse(O1(t))}catch{return null}}function oG(e,t){return e==null?t:nG[e]??`Chain ${e}`}async function M1(e){let t=e.requirements,r=e.resource?.description||t.description,o=e.chainId??null,s=null,i=null;if(o!=null){let[l]=await $o("0x"+o.toString(16),[t.asset]);s=l?.symbol??null,i=l?.decimals??null}let a=String(t.amount);if(i!==null)try{a=Jc(BigInt(t.amount),i)}catch{}return{amount:a,asset:s||t.extra?.name||"USDC",amountRaw:String(t.amount),decimals:i,assetAddress:t.asset,network:o!=null?`eip155:${o}`:t.network,networkRaw:t.network,chainId:o,networkLabel:oG(o,t.network),payTo:t.payTo,...r?{description:r}:{},resourceUrl:e.request.url}}function tP(e){return async(t,n)=>{let r=e.getPayer(),o=e.getSigner();if(!r||!o)return null;let s;try{s=JS(t,{url:n.url,method:n.method,body:n.body,headers:n.headers},r)}catch{return null}let i;try{i=await o({typedData:s.typedData,display:await M1(s)})}catch{i=null}return i?eP(s,i):null}}var Li=class extends Error{constructor(t="Aborted"){super(t),this.name="AbortError"}};function ja(e){if(!e||typeof e!="object")return!1;let t=e;return t.name==="AbortError"||t.name==="CanceledError"||t.code==="ERR_CANCELED"}function bm(e){if(e?.aborted)throw new Li}function nP(e,t){if(!t)return{signal:e.signal,cleanup:()=>{}};if(t.aborted)return e.abort(),{signal:e.signal,cleanup:()=>{}};let n=()=>e.abort();return t.addEventListener("abort",n),{signal:e.signal,cleanup:()=>t.removeEventListener("abort",n)}}var F1={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},sG="https://nft.keyring.app/api/gemini-stable",iG="https://generativelanguage.googleapis.com",aG=new Set([408,429,500,502,503,504]),q1=3e4,Jg=e=>new Promise(t=>setTimeout(t,e));function Zg(e,t,n){if(n!=null&&n>0)return Math.min(n,q1);let r=Math.min(t*2**(e-1),q1);return r/2+Math.random()*(r/2)}function lG(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let n=Date.parse(e);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}var jt=class{model;maxTokens;temperature;thinkingBudget;baseUrl;apiKey;requestSignal;constructor(t){this.model=t.model??"gemini-2.5-flash",this.maxTokens=t.maxTokens??4096,this.temperature=t.temperature??.7,this.thinkingBudget=t.thinkingBudget===void 0?0:t.thinkingBudget,this.apiKey=t.apiKey?.trim()??"",this.baseUrl=(t.baseUrl??(this.apiKey?iG:sG)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(t){this.requestSignal=t}async chat(t,n,r){let{systemInstruction:o,contents:s}=this.toContents(t),{maxRetries:i=5,retryDelayMs:a=1e3}=r??{},l=r?.signal??this.requestSignal;bm(l);let c=s.length>0?s:[{role:"user",parts:[{text:"(continue)"}]}];if(r?._debug){console.log("[GeminiProvider] turn sequence:");for(let f of c){let y=f.parts.map(w=>w.functionCall?`fc:${w.functionCall.name}`:w.functionResponse?`fr:${w.functionResponse.name}`:`text:${(w.text??"").slice(0,40)}`).join(", ");console.log(` ${f.role}: [${y}]`)}}let u=r?.thinkingBudget===void 0?this.thinkingBudget:r.thinkingBudget,d={maxOutputTokens:r?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let p={contents:c,generationConfig:d};o&&(p.systemInstruction=o),n?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(n)}],r?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):r?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,g="Unknown error";for(let f=1;f<=i;f++){bm(l);let y;try{y=await se.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(q){if(ja(q))throw q;if(g=q instanceof Error?q.message:String(q),f>=i)break;await Jg(Zg(f,a));continue}if(!y.ok){let q=typeof y.data=="string"?y.data:JSON.stringify(y.data)||y.statusText;if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${y.status}: ${q}`,!aG.has(y.status))throw new Error(g);if(f>=i)break;let V=lG(y.headers["retry-after"]??null);await Jg(Zg(f,a,V));continue}if(y.data==null||typeof y.data!="object"){if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,f>=i)break;await Jg(Zg(f,a));continue}let w=y.data,v=w.candidates?.[0];if(!v)return{text:"",toolCalls:[]};let x="",k=[],S=v.content?.parts;if(!Array.isArray(S)||S.length===0){let q=v.finishReason;if(!(q==="SAFETY"||q==="RECITATION")&&f<i){g=`Gemini returned an empty turn (finishReason=${q??"none"})`,await Jg(Zg(f,a));continue}return{text:"",toolCalls:[]}}for(let q of S)q.text&&(x+=q.text),q.functionCall&&k.push({toolName:q.functionCall.name,args:q.functionCall.args??{},callId:q.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let D=w.usageMetadata?{promptTokens:w.usageMetadata.promptTokenCount??0,completionTokens:w.usageMetadata.candidatesTokenCount??0,totalTokens:w.usageMetadata.totalTokenCount??0,thoughtsTokens:w.usageMetadata.thoughtsTokenCount??0,cachedTokens:w.usageMetadata.cachedContentTokenCount??0}:void 0;return{text:x,toolCalls:k,usage:D,finishReason:v.finishReason}}throw new Error(g)}toContents(t){let n=[],r=[];for(let a of t){if(a.role==="system"){n.push(a.content);continue}if(a.role==="tool"){r.push({role:"function",parts:[{functionResponse:{name:a.toolName??"unknown",response:{result:a.content},...a.toolCallId?{id:a.toolCallId}:{}}}]});continue}if(a.role==="assistant"&&a.toolCalls?.length){r.push({role:"model",parts:a.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}r.push({role:a.role==="assistant"?"model":"user",parts:[{text:a.content}]})}let o=[];for(let a of r){let l=o[o.length-1],c=a.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===a.role&&!c&&!u?l.parts.push(...a.parts):o.push({...a,parts:[...a.parts]})}let s=[];for(let a=0;a<o.length;a++){let l=o[a],c=s[s.length-1];l.role==="function"&&!c?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(o[a+1]?.role==="function")||s.push(l)}for(;s.length>0&&s[0].role!=="user";)s.shift();return{systemInstruction:n.length?{role:"user",parts:[{text:n.join(`
|
|
11
11
|
`)}]}:null,contents:s}}toFunctionDeclarations(t){return t.map(n=>{let r={},o=[];for(let s of n.parameters){let i={type:F1[s.type]??"STRING",description:s.description};s.type==="array"&&(i.items={type:F1[s.items?.type??"string"]??"STRING"}),r[s.name]=i,s.required&&o.push(s.name)}return{name:n.name,description:n.description,parameters:{type:"OBJECT",properties:r,required:o}}})}};var Zc=class{tools=new Map;register(t){if(this.tools.has(t.name))throw new Error(`Tool "${t.name}" is already registered`);this.tools.set(t.name,t)}unregister(t){return this.tools.delete(t)}get(t){return this.tools.get(t)}has(t){return this.tools.has(t)}getDefinitions(){return Array.from(this.tools.values()).map(t=>({name:t.name,description:t.description,parameters:t.parameters,category:t.category,kind:t.kind}))}getDefinitionsByCategory(t){return this.getDefinitions().filter(n=>n.category===t)}async execute(t,n,r){let o=this.tools.get(t);if(!o)return{toolName:t,callId:`err_${Date.now()}`,success:!1,error:`Tool "${t}" not found in registry`,duration:0};let s=Date.now();try{return{...await o.execute(n,r),duration:Date.now()-s}}catch(i){return{toolName:t,callId:`err_${Date.now()}`,success:!1,error:i instanceof Error?i.message:String(i),duration:Date.now()-s}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var eu=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],cG=new Set(eu),Di=[...eu],rP=new Set(Di),er="0x1",nu="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function uG(e){return e.map(t=>tu[t]??t).join(", ")}function ey(e){let t=new Set;if(e)for(let r of e){let o=ty(r);o&&t.add(o)}let n=eu.filter(r=>!t.has(r));Di=n.length>0?[...n]:[...eu],rP=new Set(Di),er=Di.includes("0x1")?"0x1":Di[0],nu=uG(Di)}var dG={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function Ce(e){let t=ty(e);return t&&rP.has(t)?t:null}function ty(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase().replace(/\s+/g," ");if(!t)return null;let n=dG[t];if(n)return n;let r=null;return/^0x[0-9a-f]+$/.test(t)?r=t:/^[0-9]+$/.test(t)&&(r="0x"+Number(t).toString(16)),r&&cG.has(r)?r:null}function tr(e){return Ce(e)!==null}function nr(){return[...Di]}var Ui=class extends Error{constructor(n){super(`Chain "${n}" is not supported. Supported chains: ${nu}.`);this.requested=n;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},_s=e=>typeof e=="string"&&e.trim()!=="";function at(e,t){if(_s(e)){let n=Ce(e);if(n)return n;throw new Ui(e.trim())}if(_s(t?.chain)){let n=Ce(t.chain);if(n)return n;throw new Ui(t.chain.trim())}return null}function ny(e,t){return Ce(e)??Ce(t?.chain)??void 0}var tu={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function j(e){let t=ty(e);return t&&tu[t]?tu[t]:typeof e=="string"&&e.trim()?e.trim():"the requested chain"}var pG={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function H1(e,t){let n=ty(e),r=n?pG[n]:void 0;return!r||typeof t!="string"||!/^0x[0-9a-fA-F]{64}$/.test(t.trim())?null:`${r}/tx/${t.trim()}`}var mG={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function $1(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t?mG[t]??null:null}var hG={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function ry(e){let t=Ce(e);return t?hG[t]??null:null}function oy(e,t){if(!_s(e)||!_s(t))return null;let n=Ce(e),r=Ce(t);return!n||!r||n===r?null:{from:n,to:r,fromLabel:tu[n]??n,toLabel:tu[r]??r}}function ru(e){return`Hex chain ID of the ${e} \u2014 same ids as \`chain\` (e.g. "0xa" Optimism, "0x2105" Base). ONLY set this when the user names a chain FOR THIS SIDE SPECIFICALLY, i.e. they named a chain per token \u2014 "swap ETH on Optimism to ETH on Base", "buy USDC on Base using ETH on Arbitrum". When the user names ONE chain for the whole request (or none), leave this EMPTY and use \`chain\` instead. Never copy the same chain into both sides.`}function sy(e,t){return{error:"cross_chain_not_supported",_instructions:`The user asked to ${e} from ${t.fromLabel} to ${t.toLabel} \u2014 that is a CROSS-CHAIN (bridge) request, which is NOT supported: a ${e} happens entirely on ONE network. Tell them, in their language, that ${e}ping between two different networks isn't supported yet, and that they can ${e} between tokens that are both on ${t.fromLabel}, or both on ${t.toLabel} (switching their wallet's network first). Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var qr=`Hex chain ID \u2014 e.g. "0xa" Optimism, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0x38" BSC, "0x1" Ethereum, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Set this WHENEVER the user names a network anywhere in their request \u2014 "swap USDC on Optimism", "buy PEPE on Base", "\u0111\u1ED5i USDC tr\xEAn Optimism", "mua PEPE tr\xEAn Base" \u2014 by mapping that name to its hex id from the list above. Do this EVEN IF it differs from the wallet's currently connected chain: that is a normal request, and the wallet is asked to switch networks when the transaction is signed. NEVER substitute the connected chain for a network the user named, and never leave this empty just because the two differ. OMIT it only when the user names no network at all \u2014 the connected wallet chain is then used automatically.`;function V1(e,t){let n=typeof e=="string"?e.trim():"",r=t&&t.length?t.filter(s=>rP.has(s)):[];return(r.length?r:Di).map(s=>{let i=tu[s]??s;return{label:i,prompt:n?`${n} (${i})`:i}})}function ou(e,t){return{actionButtons:V1(t),_instructions:`The user wants to ${e} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var Mt=class extends Error{code="needs_chain_selection";buttons;constructor(t,n){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=V1(t,n)}},wm=class extends Error{code="no_wallet_connected";constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one."),this.name="NoWalletConnectedError"}};function ft(e,t){if(_s(e))return e.trim();if(_s(t?.walletAddress))return t.walletAddress.trim();throw new wm}function rn(e,t,n){if(_s(e)){let r=Ce(e);if(r)return r;throw new Ui(e.trim())}if(_s(t?.chain)){let r=Ce(t.chain);if(r)return r;throw new Ui(t.chain.trim())}if(_s(t?.walletAddress))throw new Mt(typeof t?.query=="string"?t.query:void 0,n);return er}var K=class{category;async execute(t,n){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(t,n),i=fG(s);return{toolName:this.name,callId:r,success:!0,data:i.data,duration:Date.now()-o,...i.actionButtons?{actionButtons:i.actionButtons}:{},...i.ui?{ui:i.ui}:{}}}catch(s){return s instanceof Mt?{toolName:this.name,callId:r,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-o,actionButtons:s.buttons}:s instanceof wm?{toolName:this.name,callId:r,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-o}:{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}};function fG(e){if(!e||typeof e!="object")return{data:e};let t=e,n=t.actionButtons,r=Array.isArray(n)&&n.length>0?n:void 0,o=t.ui,s=o&&typeof o=="object"&&typeof o.component=="string"?o:void 0;if(!r&&!s)return{data:e};let{actionButtons:i,ui:a,...l}=t;return{data:l,...r?{actionButtons:r}:{},...s?{ui:s}:{}}}function j1(e){if(!e)return;let t=e.yieldProtocolV2;if(t!=null)return t;let n=e.yieldProtocol;return n??(t===null||n===null?null:void 0)}function z1(e){let t=e?.newConfig?.yieldInfo;if(t?.assetToken){let n=t.assetDecimals==null||t.assetDecimals===""?NaN:Number(t.assetDecimals);return{address:String(t.assetToken).toLowerCase(),...Number.isFinite(n)?{decimals:n}:{},fixedPrice:t.assetFixedPrice??null}}return e?.yieldAsset}function za(e){let t=j1(e),n=z1(e);return t===void 0&&n===void 0?null:{yieldProtocol:t,yieldAsset:n}}var gG="https://wallet-api.pantograph.app",yG="0x0000000000000000000000000000000000000000",Y1={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Q1={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function bG(e){return Y1[e.toLowerCase()]||e}function W1(e){let t=[];for(let[n,r]of Object.entries(e))if(r!=null)if(Array.isArray(r))for(let o of r)t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(o))}`);else t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`);return t.join("&")}function oP(e){let t=e,n=t.decimals,r=typeof n=="number"?n:typeof n=="string"?parseInt(n,10):NaN,o=t.price,s=o!=null?parseFloat(String(o)):NaN,i=typeof t.symbolOnchain=="string"?t.symbolOnchain.trim():"";return{...t,token_address:t.token_address??t.address??"",decimals:Number.isFinite(r)?r:0,...i?{symbol:i}:{},...Number.isFinite(s)?{usd_price:s}:{}}}function G1(e){if(Array.isArray(e))return e;let t=e;return Array.isArray(t?.items)?t.items:Array.isArray(t?.data)?t.data:[]}function Un(e){if(e==null)return null;let t=typeof e=="number"?e:parseFloat(String(e));return Number.isFinite(t)?t:null}var iy=new WeakSet;function K1(e,t){let n=typeof e.symbolOnchain=="string"?e.symbolOnchain.trim():"",r=e.decimals,o=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,s=Un(e.price_change_percentage_24h)??Un(e.priceChange24h)??Un(e.usd_price_24hr_percent_change)??Un(e.price_change_24h)??Un(e.priceChange),i={chainId:t,tokenAddress:e.address??e.token_address??"",name:e.name??null,symbol:n||e.symbol||null,decimals:o!=null&&Number.isFinite(o)?o:null,logo:e.logoURI??e.icon_image??e.logo??null,usdPrice:Un(e.price)??Un(e.usd_price),marketCap:Un(e.market_cap)??Un(e.marketCap),totalVolume:{"24h":Un(e.total_volume)??Un(e.volume24h)},pricePercentChange:{"24h":s}};return n&&iy.add(i),i}var wG=100;function vG(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var Ft=class{baseUrl;constructor(t){this.baseUrl=(t?.baseUrl??gG).replace(/\/+$/,"")}tokensUrl(t,n){let r=parseInt(t,16);return`${this.baseUrl}/keyrings/tokens/all/${r}?addresses=${encodeURIComponent(n)}`}async fetchTokensAll(t,n){let r=vG(n,wG);return(await Promise.all(r.map(async s=>{try{let i=`${this.baseUrl}/keyrings/tokens/all/${t}?addresses=${encodeURIComponent(s.join(","))}`,a=await se.get(i);return a.ok?G1(a.data):[]}catch{return[]}}))).flat()}async enrichTokenPrices(t,n){let r=new Map;if(t.length===0)return r;try{let o=t.map(a=>a.token_address),s=await this.fetchTokensAll(parseInt(n,16),o),i=new Map;for(let a of s)if(a.address){let l=a.address.toLowerCase(),c=typeof a.symbolOnchain=="string"?a.symbolOnchain.trim():"";i.set(l,{price:a.price!=null?parseFloat(String(a.price)):NaN,icon_image:a.icon_image,...c?{symbolOnchain:c}:{}});let u=za(a);u&&r.set(l,u)}for(let a=0;a<t.length;a++){let l=i.get(t[a].token_address.toLowerCase());l&&(l.icon_image&&(t[a].logo=l.icon_image,t[a].thumbnail=l.icon_image),l.symbolOnchain&&(t[a].symbol=l.symbolOnchain),isNaN(l.price)||(t[a].usd_price=l.price,t[a].usd_value=parseFloat(t[a].balance_formatted||"0")*l.price))}}catch{}return r}async getYieldPricingTokens(t,n){let r=(n??[]).map(s=>String(s??"").trim()).filter(Boolean);if(r.length===0)return[];let o=typeof t=="number"?t:String(t).startsWith("0x")?parseInt(String(t),16):parseInt(String(t),10);if(!Number.isFinite(o))return[];try{return await this.fetchTokensAll(o,r)}catch{return[]}}async getTokenMetadata(t,n){try{let r=this.tokensUrl(n,t),o=await se.get(r);if(!o.ok)return null;let s=G1(o.data),i=t.toLowerCase()===yG,a=s.find(l=>l.address?.toLowerCase()===t.toLowerCase()||i&&l.address===""||l.token_address?.toLowerCase()===t.toLowerCase()||i&&l.token_address==="");return a?oP(a):null}catch{return null}}async getTokensMetadata(t,n){let r={};if(t.length===0)return r;try{let o=await this.fetchTokensAll(parseInt(n,16),t),s=new Set(t.map(i=>i.toLowerCase()));for(let i of o){let a=i.address?.toLowerCase()||i.token_address?.toLowerCase()||(i.address===""?"":null);a&&s.has(a)&&(r[a]=oP(i))}}catch{}return r}async searchTokensByKey(t){let{key:n,chain:r}=t;if(!n)return{success:!1,error:"Search key is required"};let s=parseInt(r||er,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${r}`};try{let i=W1({chainId:s,key:n}),a=`${this.baseUrl}/token-list/all?${i}`,l=await se.get(a);if(!l.ok)throw new Error(he(l));let c=l.data,u=c?.result??c?.data??c,d=[];return Array.isArray(u)?d=u:u&&typeof u=="object"&&(d=Object.values(u).flat()),{success:!0,data:d.map(oP)}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async getTrendingTokens(t){let n=t?.chain||er,r=5,o=t?.limit&&t.limit>0?Math.floor(t.limit):void 0;try{let s=Q1[n.toLowerCase()]??[],i=o!=null?o+s.length:r+s.length,[a,l]=await Promise.allSettled([this.fetchTopGainers(n,i),s.length>0?this.getTokensMetadata(s,n):Promise.resolve({})]),c=a.status==="fulfilled"?a.value:[],u=l.status==="fulfilled"?s.map(f=>l.value[f.toLowerCase()]).filter(f=>f!=null).map(f=>K1(f,n)):[],d=new Set,p=[];for(let f of u){let y=f.tokenAddress?.toLowerCase();!y||d.has(y)||(d.add(y),p.push(f))}let m=[];for(let f of c){let y=f.tokenAddress?.toLowerCase();!y||d.has(y)||(d.add(y),m.push(f))}let g=o!=null?[...p,...m].slice(0,o):[...p,...m.slice(0,r)];return await this.enrichTrendingMarketData(g,n),{success:!0,data:g}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async enrichTrendingMarketData(t,n){let r=t.filter(s=>s.tokenAddress&&(s.marketCap==null||s.totalVolume?.["24h"]==null||!iy.has(s)));if(r.length===0)return;let o=await this.getTokensMetadata(r.map(s=>s.tokenAddress),n);for(let s of r){let i=o[s.tokenAddress.toLowerCase()];if(!i)continue;let a=typeof i.symbolOnchain=="string"?i.symbolOnchain.trim():"";a&&!iy.has(s)&&(s.symbol=a,iy.add(s)),s.marketCap==null&&(s.marketCap=Un(i.market_cap)??Un(i.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":Un(i.total_volume)??Un(i.volume24h)})}}async fetchTopGainers(t,n,r="24h"){let o=parseInt(t,16),s=W1({chainId:o,duration:r,limit:n}),i=`${this.baseUrl}/token-list/all/top-gainers${s?`?${s}`:""}`,a=[];for(let l=0;l<5;l++){let c=await se.get(i);if(!c.ok)throw new Error(he(c));let u=c.data;if(a=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],a.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return a.map(l=>K1(l,t))}async getTopGainers(t){let n=t?.chain||er,r=t?.limit&&t.limit>0?Math.floor(t.limit):void 0,o=t?.duration||"24h";try{let s=await this.fetchTopGainers(n,r,o);return await this.enrichTrendingMarketData(s,n),{success:!0,data:s}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}};function dt(e,t,n,r=[]){return{target:e,callData:Le({abi:t,functionName:n,args:r})}}var Wa=1e27,ay=10n**27n,vm=31536e3,kG=10;function Hr(e){return Number.isFinite(e)&&e>=0&&e<=kG?e:null}function sP(e){return Math.expm1(e)}function $r(e,t){return Number(e)/10**t}function km(e){return new Date(e).toISOString().slice(0,10)}async function Bi(e,t,n){let r=`${n.lendingRatesBaseUrl}/lending-rates/${t.chainId}/${e.token}?range=h&day=${7}`,o=await se.get(r);if(!o.ok)throw new Error(he(o));return{samples:(Array.isArray(o.data)?o.data:o.data?.data||[]).filter(i=>i?.rate!==null&&i?.rate!==void 0).map(i=>({timeMs:Date.parse(i?.date??""),fraction:Number(i?.rate)})),current:null,rewards:[]}}var Vo=class{underlyingCall(t){return dt(t.contract,Bo,"asset")}liveRateCall(t,n){return null}followUpRateCall(t,n){return null}decodeSize(t,n){if(!Number.isInteger(n.decimals)||n.decimals<0)return null;let r=ht(t);return r===null?null:$r(r,n.decimals)}decodeLiveRate(t){return null}convertToAssetsCall(t,n){return this.balanceIsUnderlying?null:dt(t.contract,Bo,"convertToAssets",[n])}},jo=class extends Vo{type="spark";balanceIsUnderlying=!1;sizeCall(t){return dt(t.contract,Bo,"totalAssets")}fetchApy(t,n,r,o){return Bi(t,n,r)}};var iP=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}];var aP=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]},{type:"function",name:"liquidity",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint128"}]},{type:"function",name:"tickSpacing",stateMutability:"view",inputs:[],outputs:[{name:"",type:"int24"}]},{type:"function",name:"fee",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint24"}]},{type:"function",name:"token0",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"token1",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var cy=[{type:"function",name:"getReserveData",stateMutability:"view",inputs:[{name:"asset",type:"address"}],outputs:[{name:"reserveData",type:"tuple",components:[{name:"configuration",type:"uint256"},{name:"liquidityIndex",type:"uint128"},{name:"currentLiquidityRate",type:"uint128"}]}]}],su=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],lP=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Cs=[{inputs:[],name:"getUtilization",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseToken",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"utilization",type:"uint256"}],name:"getSupplyRate",outputs:[{name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseTrackingSupplySpeed",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseIndexScale",outputs:[{name:"",type:"uint64"}],stateMutability:"pure",type:"function"}],cP=[{inputs:[{name:"comet",type:"address"}],name:"rewardConfig",outputs:[{name:"token",type:"address"},{name:"rescaleFactor",type:"uint64"},{name:"shouldUpscale",type:"bool"}],stateMutability:"view",type:"function"}];var iu=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],Mi=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],uP=[{inputs:[],name:"susds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var dP=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],pP=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var TG=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|