keyring-agent-core 0.4.3 → 0.4.4
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 +13 -16
- package/dist/index.native.js +22 -25
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
"use strict";var ZW=Object.create;var Rg=Object.defineProperty;var ez=Object.getOwnPropertyDescriptor;var tz=Object.getOwnPropertyNames;var nz=Object.getPrototypeOf,rz=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 oz=(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)Rg(e,n,{get:t[n],enumerable:!0})},VL=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of tz(t))!rz.call(e,o)&&o!==n&&Rg(e,o,{get:()=>t[o],enumerable:!(r=ez(t,o))||r.enumerable});return e};var jL=(e,t,n)=>(n=e!=null?ZW(nz(e)):{},VL(t||!e||!e.__esModule?Rg(n,"default",{value:e,enumerable:!0}):n,e)),sz=e=>VL(Rg({},"__esModule",{value:!0}),e);var uU,dU=L(()=>{"use strict";uU="1.3.0"});var Ht,Uu=L(()=>{"use strict";dU();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@${uU}`].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 ZP,eE,Hy,Qm=L(()=>{"use strict";ZP=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,eE=/^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)?$/,Hy=/^\(.+?\).*?$/});function $y(e){let t=e.type;if(pU.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+=$y(s),o<n-1&&(t+=", ")}let r=br(pU,e.type);return t+=`)${r?.array||""}`,$y({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}var pU,mU=L(()=>{"use strict";Qm();pU=/^tuple(?<array>(\[(\d*)\])*)$/});function Ko(e){let t="",n=e.length;for(let r=0;r<n;r++){let o=e[r];t+=$y(o),r!==n-1&&(t+=", ")}return t}var tE=L(()=>{"use strict";mU()});function el(e){return e.type==="function"?`function ${e.name}(${Ko(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${Ko(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${Ko(e.inputs)})`:e.type==="error"?`error ${e.name}(${Ko(e.inputs)})`:e.type==="constructor"?`constructor(${Ko(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}var hU=L(()=>{"use strict";tE()});function gU(e){return fU.test(e)}function yU(e){return br(fU,e)}function wU(e){return bU.test(e)}function vU(e){return br(bU,e)}function xU(e){return kU.test(e)}function AU(e){return br(kU,e)}function Bu(e){return TU.test(e)}function SU(e){return br(TU,e)}function EU(e){return PU.test(e)}function RU(e){return br(PU,e)}function IU(e){return _U.test(e)}function CU(e){return br(_U,e)}function NU(e){return JY.test(e)}var fU,bU,kU,TU,PU,_U,JY,nE,OU,Vy,Xm=L(()=>{"use strict";Qm();fU=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;bU=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;kU=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;TU=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;PU=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;_U=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;JY=/^receive\(\) external payable$/;nE=new Set(["memory","indexed","storage","calldata"]),OU=new Set(["indexed"]),Vy=new Set(["calldata","memory","storage"])});var jy,Wy,zy,Gy=L(()=>{"use strict";Uu();jy=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"})}},Wy=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 Ky,Yy,Qy,Xy,Jy,Zy,eb=L(()=>{"use strict";Uu();Ky=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"})}},Yy=class extends Ht{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},Qy=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"})}},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`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},Jy=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"})}},Zy=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 Yo,tb,nb,rE=L(()=>{"use strict";Uu();Yo=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"})}},tb=class extends Ht{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},nb=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 rb,LU=L(()=>{"use strict";Uu();rb=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 ob,DU=L(()=>{"use strict";Uu();ob=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 UU(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 sb,BU=L(()=>{"use strict";sb=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 oE(e,t={}){if(xU(e))return ZY(e,t);if(wU(e))return e9(e,t);if(gU(e))return t9(e,t);if(EU(e))return n9(e,t);if(IU(e))return r9(e);if(NU(e))return{type:"receive",stateMutability:"payable"};throw new tb({signature:e})}function ZY(e,t={}){let n=AU(e);if(!n)throw new Yo({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:Vy,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:Vy,structs:t,type:"function"}))}return{name:n.name,type:"function",stateMutability:n.stateMutability??"nonpayable",inputs:o,outputs:i}}function e9(e,t={}){let n=vU(e);if(!n)throw new Yo({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:OU,structs:t,type:"event"}));return{name:n.name,type:"event",inputs:o}}function t9(e,t={}){let n=yU(e);if(!n)throw new Yo({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 n9(e,t={}){let n=RU(e);if(!n)throw new Yo({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 r9(e){let t=CU(e);if(!t)throw new Yo({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}function lo(e,t){let n=UU(e,t?.type,t?.structs);if(sb.has(n))return sb.get(n);let r=Hy.test(e),o=br(r?s9:o9,e);if(!o)throw new Yy({param:e});if(o.name&&l9(o.name))throw new Qy({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(i9.test(o.type))l=`${o.type}256`;else if(o.type==="address payable")l="address";else if(l=o.type,t?.type!=="struct"&&!sE(l))throw new zy({type:l});if(o.modifier){if(!t?.modifiers?.has?.(o.modifier))throw new Xy({param:e,type:t?.type,modifier:o.modifier});if(Vy.has(o.modifier)&&!c9(l,!!o.array))throw new Jy({param:e,type:t?.type,modifier:o.modifier})}let u={type:`${l}${o.array??""}`,...s,...i,...c};return sb.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 ob({current:n,depth:r});return t.push(n.trim()),t}function sE(e){return e==="address"||e==="bool"||e==="function"||e==="string"||ZP.test(e)||eE.test(e)}function l9(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||ZP.test(e)||eE.test(e)||a9.test(e)}function c9(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}var o9,s9,i9,a9,Jm=L(()=>{"use strict";Qm();Gy();eb();rE();DU();BU();Xm();o9=/^(?<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$_]*))?$/,s9=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,i9=/^u?int$/;a9=/^(?: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 ib(e){let t={},n=e.length;for(let i=0;i<n;i++){let a=e[i];if(!Bu(a))continue;let l=SU(a);if(!l)throw new Yo({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 nb({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]=MU(l,t)}return r}function MU(e=[],t={},n=new Set){let r=[],o=e.length;for(let s=0;s<o;s++){let i=e[s];if(Hy.test(i.type))r.push(i);else{let l=br(u9,i.type);if(!l?.type)throw new Zy({abiParameter:i});let{array:c,type:u}=l;if(u in t){if(n.has(u))throw new rb({type:u});r.push({...i,type:`tuple${c??""}`,components:MU(t[u],t,new Set([...n,u]))})}else if(sE(u))r.push(i);else throw new Wy({type:u})}}return r}var u9,iE=L(()=>{"use strict";Qm();Gy();eb();rE();LU();Xm();Jm();u9=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/});function ab(e){let t;if(typeof e=="string")t=oE(e);else{let n=ib(e),r=e.length;for(let o=0;o<r;o++){let s=e[o];if(!Bu(s)){t=oE(s,n);break}}}if(!t)throw new jy({signature:e});return t}var FU=L(()=>{"use strict";Gy();Xm();iE();Jm()});function lb(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:nE}))}else{let n=ib(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:nE,structs:n}))}}if(t.length===0)throw new Ky({params:e});return t}var qU=L(()=>{"use strict";eb();Xm();iE();Jm();Jm()});var cb=L(()=>{"use strict";hU();tE();FU();qU()});var HU=L(()=>{"use strict"});var $U,VU=L(()=>{"use strict";$U="0.1.1"});function jU(){return $U}var WU=L(()=>{"use strict";VU()});function zU(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?zU(e.cause,t):t?null:e}var le,An=L(()=>{"use strict";WU();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
|
-
`);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 zU(this,t)}};Object.defineProperty(le,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${jU()}`}});le.setStaticOptions(le.defaultStaticOptions)});function Mu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function pE(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 Zm(e){let t=e.toString(16);return t.length&1?"0"+t:t}function YU(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?dE:BigInt("0x"+e)}function qu(e){if(pE(e),QU)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=p9[e[n]];return t}function GU(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 eh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(QU)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=GU(e.charCodeAt(s)),a=GU(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 YU(qu(e))}function mE(e){return pE(e),YU(qu(Uint8Array.from(e).reverse()))}function tl(e,t){return eh(e.toString(16).padStart(t*2,"0"))}function hE(e,t){return tl(e,t).reverse()}function or(e,t,n){let r;if(typeof t=="string")try{r=eh(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 th(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];pE(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 ub(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 db(e,t,n){return lE(e)&&lE(t)&&lE(n)&&t<=e&&e<n}function nl(e,t,n,r){if(!db(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function XU(e){let t;for(t=0;e>dE;e>>=uE,t+=1);return t}function JU(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=cE(e),o=cE(e),s=0,i=()=>{r.fill(1),o.fill(0),s=0},a=(...d)=>n(o,r,...d),l=(d=cE(0))=>{o=a(KU([0]),d),r=a(),d.length!==0&&(o=a(KU([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 th(...p)};return(d,p)=>{i(),l(d);let m;for(;!(m=p(c()));)l();return i(),m}}function ol(e,t,n={}){let r=(o,s,i)=>{let a=m9[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 fE(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 dE,uE,QU,p9,Fs,lE,rl,cE,KU,m9,Hu=L(()=>{"use strict";dE=BigInt(0),uE=BigInt(1);QU=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",p9=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};lE=e=>typeof e=="bigint"&&dE<=e;rl=e=>(uE<<BigInt(e))-uE,cE=e=>new Uint8Array(e),KU=e=>Uint8Array.from(e);m9={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 nh({givenSize:wr(e),maxSize:t})}function ZU(e,t){if(typeof t=="number"&&t>0&&t>wr(e)-1)throw new $u({offset:t,position:"start",size:wr(e)})}function eB(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 gE(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 yE(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new rh({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 bE(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,wE=L(()=>{"use strict";Xt();Hs={zero:48,nine:57,A:65,F:70,a:97,f:102}});function sl(e,t){if(rt(e)>t)throw new oh({givenSize:rt(e),maxSize:t})}function nB(e,t){if(typeof t=="number"&&t>0&&t>rt(e)-1)throw new Vu({offset:t,position:"start",size:rt(e)})}function rB(e,t,n){if(typeof t=="number"&&typeof n=="number"&&rt(e)!==n-t)throw new Vu({offset:n,position:"end",size:rt(e)})}function vE(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 sh({size:Math.ceil(o.length/2),targetSize:r,type:"Hex"});return`0x${o[n==="right"?"padEnd":"padStart"](r*2,"0")}`}function kE(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 xE=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()+h9:o,n)}var h9,il=L(()=>{"use strict";h9="#__bigint"});var _t={};fr(_t,{IntegerOutOfRangeError:()=>Wu,InvalidHexBooleanError:()=>pb,InvalidHexTypeError:()=>ih,InvalidHexValueError:()=>ah,InvalidLengthError:()=>mb,SizeExceedsPaddingSizeError:()=>sh,SizeOverflowError:()=>oh,SliceOffsetOutOfBoundsError:()=>Vu,assert:()=>sB,concat:()=>Jt,from:()=>uo,fromBoolean:()=>lh,fromBytes:()=>Ke,fromNumber:()=>mt,fromString:()=>Vs,isEqual:()=>y9,padLeft:()=>Qo,padRight:()=>po,random:()=>b9,size:()=>rt,slice:()=>$t,toBigInt:()=>hb,toBoolean:()=>v9,toBytes:()=>k9,toNumber:()=>AE,toString:()=>x9,trimLeft:()=>ch,trimRight:()=>w9,validate:()=>al});function sB(e,t={}){let{strict:n=!1}=t;if(!e)throw new ih(e);if(typeof e!="string")throw new ih(e);if(n&&!/^0x[0-9a-fA-F]*$/.test(e))throw new ah(e);if(!e.startsWith("0x"))throw new ah(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 lh(e,t={}){let n=`0x${Number(e)}`;return typeof t.size=="number"?(sl(n,t.size),Qo(n,t.size)):n}function Ke(e,t={}){let n="";for(let o=0;o<e.length;o++)n+=g9[e[o]];let r=`0x${n}`;return typeof t.size=="number"?(sl(r,t.size),po(r,t.size)):r}function mt(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 Wu({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?Qo(l,r):l}function Vs(e,t={}){return Ke(f9.encode(e),t)}function y9(e,t){return ub(wt(e),wt(t))}function Qo(e,t){return vE(e,{dir:"left",size:t})}function po(e,t){return vE(e,{dir:"right",size:t})}function b9(e){return Ke(fb(e))}function $t(e,t,n,r={}){let{strict:o}=r;nB(e,t);let s=`0x${e.replace("0x","").slice((t??0)*2,(n??e.length)*2)}`;return o&&rB(s,t,n),s}function rt(e){return Math.ceil((e.length-2)/2)}function ch(e){return kE(e,{dir:"left"})}function w9(e){return kE(e,{dir:"right"})}function hb(e,t={}){let{signed:n}=t;t.size&&sl(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 v9(e,t={}){t.size&&sl(e,t.size);let n=ch(e);if(n==="0x")return!1;if(n==="0x1")return!0;throw new pb(e)}function k9(e,t={}){return wt(e,t)}function AE(e,t={}){let{signed:n,size:r}=t;return Number(!n&&!r?e:hb(e,t))}function x9(e,t={}){let{size:n}=t,r=wt(e);return n&&($s(r,n),r=gb(r)),new TextDecoder().decode(r)}function al(e,t={}){let{strict:n=!1}=t;try{return sB(e,{strict:n}),!0}catch{return!1}}var f9,g9,Wu,pb,ih,ah,mb,oh,Vu,sh,Tn=L(()=>{"use strict";Hu();Xt();An();wE();xE();il();f9=new TextEncoder,g9=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Wu=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"})}},pb=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"})}},ih=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"})}},ah=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"})}},mb=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"})}},oh=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"})}},sh=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:()=>yb,InvalidBytesTypeError:()=>ll,SizeExceedsPaddingSizeError:()=>rh,SizeOverflowError:()=>nh,SliceOffsetOutOfBoundsError:()=>$u,assert:()=>iB,concat:()=>zu,from:()=>Fn,fromArray:()=>aB,fromBoolean:()=>S9,fromHex:()=>wt,fromNumber:()=>Gu,fromString:()=>qn,isEqual:()=>P9,padLeft:()=>bb,padRight:()=>lB,random:()=>fb,size:()=>wr,slice:()=>TE,toBigInt:()=>SE,toBoolean:()=>PE,toHex:()=>E9,toNumber:()=>mo,toString:()=>uh,trimLeft:()=>wb,trimRight:()=>gb,validate:()=>Ku});function iB(e){if(!(e instanceof Uint8Array)){if(!e)throw new ll(e);if(typeof e!="object")throw new ll(e);if(!("BYTES_PER_ELEMENT"in e))throw new ll(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new ll(e)}}function zu(...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"?wt(e):aB(e)}function aB(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function S9(e,t={}){let{size:n}=t,r=new Uint8Array(1);return r[0]=Number(e),typeof n=="number"?($s(r,n),bb(r,n)):r}function wt(e,t={}){let{size:n}=t,r=e;n&&(sl(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=gE(o.charCodeAt(l++)),u=gE(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=mt(e,t);return wt(n)}function qn(e,t={}){let{size:n}=t,r=T9.encode(e);return typeof n=="number"?($s(r,n),lB(r,n)):r}function P9(e,t){return ub(e,t)}function bb(e,t){return yE(e,{dir:"left",size:t})}function lB(e,t){return yE(e,{dir:"right",size:t})}function fb(e){return crypto.getRandomValues(new Uint8Array(e))}function wr(e){return e.length}function TE(e,t,n,r={}){let{strict:o}=r;ZU(e,t);let s=e.slice(t,n);return o&&eB(s,t,n),s}function SE(e,t={}){let{size:n}=t;typeof n<"u"&&$s(e,n);let r=Ke(e,t);return hb(r,t)}function PE(e,t={}){let{size:n}=t,r=e;if(typeof n<"u"&&($s(r,n),r=wb(r)),r.length>1||r[0]>1)throw new yb(r);return!!r[0]}function E9(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 AE(r,t)}function uh(e,t={}){let{size:n}=t,r=e;return typeof n<"u"&&($s(r,n),r=gb(r)),A9.decode(r)}function wb(e){return bE(e,{dir:"left"})}function gb(e){return bE(e,{dir:"right"})}function Ku(e){try{return iB(e),!0}catch{return!1}}var A9,T9,yb,ll,nh,$u,rh,Xt=L(()=>{"use strict";Hu();An();Tn();wE();xE();il();A9=new TextDecoder,T9=new TextEncoder;yb=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"})}},ll=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"})}},nh=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"})}},rh=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:()=>RE,keccak256:()=>sn,ripemd160:()=>R9,sha256:()=>_9,validate:()=>I9});function sn(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,dB.keccak_256)(Fn(e));return n==="Bytes"?r:Ke(r)}function RE(e,t,n={}){let{as:r=typeof t=="string"?"Hex":"Bytes"}=n,o=(0,cB.hmac)(EE.sha256,Fn(e),Fn(t));return r==="Bytes"?o:Ke(o)}function R9(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,uB.ripemd160)(Fn(e));return n==="Bytes"?r:Ke(r)}function _9(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,EE.sha256)(Fn(e));return n==="Bytes"?r:Ke(r)}function I9(e){return e.length===66&&al(e,{strict:!0})}var cB,uB,dB,EE,cl=L(()=>{"use strict";cB=require("@noble/hashes/hmac"),uB=require("@noble/hashes/ripemd160"),dB=require("@noble/hashes/sha3"),EE=require("@noble/hashes/sha256");Xt();Tn()});var vb,pB=L(()=>{"use strict";vb=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 C9,kb,_E=L(()=>{"use strict";pB();C9={checksum:new vb(8192)},kb=C9.checksum});function hB(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 xb({prefix:r,cause:new NE});return}if(n===!0||typeof o=="bigint"&&typeof s>"u"){if(r!==3&&r!==2)throw new xb({prefix:r,cause:new CE});return}throw new IE({publicKey:e})}function LE(e){let t=(()=>{if(al(e))return fB(e);if(Ku(e))return N9(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 hB(t),t}function N9(e){return fB(Ke(e))}function fB(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new OE({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 gB(e,t={}){return wt(dh(e,t))}function dh(e,t={}){hB(e);let{prefix:n,x:r,y:o}=e,{includePrefix:s=!0}=t;return Jt(s?mt(n,{size:1}):"0x",mt(r,{size:32}),typeof o=="bigint"?mt(o,{size:32}):"0x")}var IE,xb,CE,NE,OE,Ab=L(()=>{"use strict";Xt();An();Tn();il();IE=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"})}},xb=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"})}},CE=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"})}},NE=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"})}},OE=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 ${rt(uo(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});var Jo={};fr(Jo,{InvalidAddressError:()=>ul,InvalidChecksumError:()=>Tb,InvalidInputError:()=>Yu,assert:()=>Xo,checksum:()=>ph,from:()=>dl,fromPublicKey:()=>UE,isEqual:()=>BE,validate:()=>pl});function Xo(e,t={}){let{strict:n=!0}=t;if(!O9.test(e))throw new ul({address:e,cause:new Yu});if(n){if(e.toLowerCase()===e)return;if(ph(e)!==e)throw new ul({address:e,cause:new Tb})}}function ph(e){if(kb.has(e))return kb.get(e);Xo(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 kb.set(e,o),o}function dl(e,t={}){let{checksum:n=!1}=t;return Xo(e),n?ph(e):e}function UE(e,t={}){let n=sn(`0x${dh(e).slice(4)}`).substring(26);return dl(`0x${n}`,t)}function BE(e,t){return Xo(e,{strict:!1}),Xo(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}function pl(e,t={}){let{strict:n=!0}=t??{};try{return Xo(e,{strict:n}),!0}catch{return!1}}var O9,ul,Yu,Tb,ji=L(()=>{"use strict";Xt();_E();An();cl();Ab();O9=/^0x[a-fA-F0-9]{40}$/;ul=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"})}},Tb=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 Pb(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 Sb(e,t){let n=typeof e,r=t.type;switch(r){case"address":return pl(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)=>Sb(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=>Sb(o,{...t,type:r.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function ME(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 ME(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")?pl(n[r],{strict:!1}):i.includes("address")&&i.includes("bytes")?pl(n[r],{strict:!1}):!1)return i}}var yB=L(()=>{"use strict";ji();An()});function bB(e,t={}){let{prepare:n=!0}=t,r=Array.isArray(e)?ab(e):typeof e=="string"?ab(e):e;return{...r,...n?{hash:Qu(r)}:{}}}function mh(e,t,n){let{args:r=[],prepare:o=!0}=n??{},s=al(t,{strict:!1}),i=e.filter(c=>s?c.type==="function"||c.type==="error"?qE(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?Sb(d,m):!1})){if(a&&"inputs"in a&&a.inputs){let d=ME(c.inputs,a.inputs,r);if(d)throw new FE({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 qE(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,r]=e;return mh(n,r)}return e[0]})();return $t(Qu(t),0,4)}function D9(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,o]=e;return mh(r,o)}return e[0]})(),n=typeof t=="string"?t:el(t);return Pb(n)}function Qu(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,r]=e;return mh(n,r)}return e[0]})();return typeof t!="string"&&"hash"in t&&t.hash?t.hash:sn(Vs(D9(t)))}var FE,Xu,Eb,HE=L(()=>{"use strict";cb();An();cl();Tn();yB();FE=class extends le{constructor(t,n){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${Pb(el(t.abiItem))}\`, and`,`\`${n.type}\` in \`${Pb(el(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"})}},Eb=class extends le{constructor({data:t}){super(`Selector size is invalid. Expected 4 bytes. Received ${rt(t)} bytes ("${t}").`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.InvalidSelectorSizeError"})}}});var vB,Rb,Ju,_Ee,IEe,CEe,NEe,OEe,LEe,DEe,UEe,BEe,MEe,FEe,qEe,HEe,$Ee,VEe,jEe,WEe,zEe,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,_Re,IRe,CRe,NRe,ORe,LRe,DRe,URe,BRe,MRe,FRe,qRe,HRe,$Re,VRe,jRe,WRe,zRe,GRe,KRe,YRe,QRe,XRe,JRe,ZRe,e_e,t_e,n_e,r_e,o_e,s_e,i_e,a_e,l_e,c_e,u_e,d_e,p_e,m_e,h_e,f_e,$E,Zu=L(()=>{"use strict";vB=/^(.*)\[([0-9]*)\]$/,Rb=/^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)?$/,_Ee=2n**(8n-1n)-1n,IEe=2n**(16n-1n)-1n,CEe=2n**(24n-1n)-1n,NEe=2n**(32n-1n)-1n,OEe=2n**(40n-1n)-1n,LEe=2n**(48n-1n)-1n,DEe=2n**(56n-1n)-1n,UEe=2n**(64n-1n)-1n,BEe=2n**(72n-1n)-1n,MEe=2n**(80n-1n)-1n,FEe=2n**(88n-1n)-1n,qEe=2n**(96n-1n)-1n,HEe=2n**(104n-1n)-1n,$Ee=2n**(112n-1n)-1n,VEe=2n**(120n-1n)-1n,jEe=2n**(128n-1n)-1n,WEe=2n**(136n-1n)-1n,zEe=2n**(144n-1n)-1n,GEe=2n**(152n-1n)-1n,KEe=2n**(160n-1n)-1n,YEe=2n**(168n-1n)-1n,QEe=2n**(176n-1n)-1n,XEe=2n**(184n-1n)-1n,JEe=2n**(192n-1n)-1n,ZEe=2n**(200n-1n)-1n,eRe=2n**(208n-1n)-1n,tRe=2n**(216n-1n)-1n,nRe=2n**(224n-1n)-1n,rRe=2n**(232n-1n)-1n,oRe=2n**(240n-1n)-1n,sRe=2n**(248n-1n)-1n,iRe=2n**(256n-1n)-1n,aRe=-(2n**(8n-1n)),lRe=-(2n**(16n-1n)),cRe=-(2n**(24n-1n)),uRe=-(2n**(32n-1n)),dRe=-(2n**(40n-1n)),pRe=-(2n**(48n-1n)),mRe=-(2n**(56n-1n)),hRe=-(2n**(64n-1n)),fRe=-(2n**(72n-1n)),gRe=-(2n**(80n-1n)),yRe=-(2n**(88n-1n)),bRe=-(2n**(96n-1n)),wRe=-(2n**(104n-1n)),vRe=-(2n**(112n-1n)),kRe=-(2n**(120n-1n)),xRe=-(2n**(128n-1n)),ARe=-(2n**(136n-1n)),TRe=-(2n**(144n-1n)),SRe=-(2n**(152n-1n)),PRe=-(2n**(160n-1n)),ERe=-(2n**(168n-1n)),RRe=-(2n**(176n-1n)),_Re=-(2n**(184n-1n)),IRe=-(2n**(192n-1n)),CRe=-(2n**(200n-1n)),NRe=-(2n**(208n-1n)),ORe=-(2n**(216n-1n)),LRe=-(2n**(224n-1n)),DRe=-(2n**(232n-1n)),URe=-(2n**(240n-1n)),BRe=-(2n**(248n-1n)),MRe=-(2n**(256n-1n)),FRe=2n**8n-1n,qRe=2n**16n-1n,HRe=2n**24n-1n,$Re=2n**32n-1n,VRe=2n**40n-1n,jRe=2n**48n-1n,WRe=2n**56n-1n,zRe=2n**64n-1n,GRe=2n**72n-1n,KRe=2n**80n-1n,YRe=2n**88n-1n,QRe=2n**96n-1n,XRe=2n**104n-1n,JRe=2n**112n-1n,ZRe=2n**120n-1n,e_e=2n**128n-1n,t_e=2n**136n-1n,n_e=2n**144n-1n,r_e=2n**152n-1n,o_e=2n**160n-1n,s_e=2n**168n-1n,i_e=2n**176n-1n,a_e=2n**184n-1n,l_e=2n**192n-1n,c_e=2n**200n-1n,u_e=2n**208n-1n,d_e=2n**216n-1n,p_e=2n**224n-1n,m_e=2n**232n-1n,h_e=2n**240n-1n,f_e=2n**248n-1n,$E=2n**256n-1n});function ml(e,t,n){let{checksumAddress:r,staticPosition:o}=n,s=WE(t.type);if(s){let[i,a]=s;return B9(e,{...t,type:a},{checksumAddress:r,length:i,staticPosition:o})}if(t.type==="tuple")return H9(e,t,{checksumAddress:r,staticPosition:o});if(t.type==="address")return U9(e,{checksum:r});if(t.type==="bool")return M9(e);if(t.type.startsWith("bytes"))return F9(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return q9(e,t);if(t.type==="string")return $9(e,{staticPosition:o});throw new hl(t.type)}function U9(e,t={}){let{checksum:n=!1}=t,r=e.readBytes(32);return[(s=>n?ph(s):s)(Ke(TE(r,-20))),32]}function B9(e,t,n){let{checksumAddress:r,length:o,staticPosition:s}=n;if(o===null){let l=mo(e.readBytes(VE)),c=s+l,u=c+kB;e.setPosition(c);let d=mo(e.readBytes(kB)),p=ed(t),m=0,g=[];for(let f=0;f<d;++f){e.setPosition(u+(p?f*32:m));let[y,w]=ml(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(VE)),c=s+l,u=[];for(let d=0;d<o;++d){e.setPosition(c+d*32);let[p]=ml(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]=ml(e,t,{checksumAddress:r,staticPosition:s+i});i+=u,a.push(c),u===0&&(e.assertReadLimit(),e._touch())}return[a,i]}function M9(e){return[PE(e.readBytes(32),{size:32}),32]}function F9(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 q9(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?SE(o,{signed:n}):mo(o,{signed:n}),32]}function H9(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(VE)),c=o+l;for(let u=0;u<t.components.length;++u){let d=t.components[u];e.setPosition(c+a);let[p,m]=ml(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]=ml(e,c,{checksumAddress:r,staticPosition:o});i[s?l:c?.name]=u,a+=d}return[i,a]}function $9(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=uh(wb(s));return e.setPosition(t+32),[i,32]}function xB({checksumAddress:e,parameters:t,values:n}){let r=[];for(let o=0;o<t.length;o++)r.push(jE({checksumAddress:e,parameter:t[o],value:n[o]}));return r}function jE({checksumAddress:e=!1,parameter:t,value:n}){let r=t,o=WE(r.type);if(o){let[s,i]=o;return j9(n,{checksumAddress:e,length:s,parameter:{...r,type:i}})}if(r.type==="tuple")return Y9(n,{checksumAddress:e,parameter:r});if(r.type==="address")return V9(n,{checksum:e});if(r.type==="bool")return z9(n);if(r.type.startsWith("uint")||r.type.startsWith("int")){let s=r.type.startsWith("int"),[,,i="256"]=Ju.exec(r.type)??[];return G9(n,{signed:s,size:Number(i)})}if(r.type.startsWith("bytes"))return W9(n,{type:r.type});if(r.type==="string")return K9(n);throw new hl(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+=rt(a)}let n=[],r=[],o=0;for(let s=0;s<e.length;s++){let{dynamic:i,encoded:a}=e[s];i?(n.push(mt(t+o,{size:32})),r.push(a),o+=rt(a)):n.push(a)}return Jt(...n,...r)}function V9(e,t){let{checksum:n=!1}=t;return Xo(e,{strict:n}),{dynamic:!1,encoded:Qo(e.toLowerCase())}}function j9(e,t){let{checksumAddress:n,length:r,parameter:o}=t,s=r===null;if(!Array.isArray(e))throw new fh(e);if(!s&&e.length!==r)throw new hh({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=jE({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=mt(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 W9(e,{type:t}){let[,n]=t.split("bytes"),r=rt(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(Qo(mt(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 z9(e){if(typeof e!="boolean")throw new le(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Qo(lh(e))}}function G9(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 Wu({max:r.toString(),min:o.toString(),signed:t,size:n/8,value:e.toString()})}return{dynamic:!1,encoded:mt(e,{size:32,signed:t})}}function K9(e){let t=Vs(e),n=Math.ceil(rt(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(mt(rt(t),{size:32})),...r)}}function Y9(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=jE({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 WE(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=WE(e.type);return!!(n&&ed({...e,type:n[1]}))}var kB,VE,AB=L(()=>{"use strict";gh();ji();Xt();An();Tn();Zu();kB=32,VE=32});function Nb(e,{recursiveReadLimit:t=8192}={}){let n=Object.create(X9);return n.bytes=e,n.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}var X9,Cb,zE,GE,KE=L(()=>{"use strict";An();X9={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 GE({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new zE({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Cb({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 Cb({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++}};Cb=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"})}},zE=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"})}},GE=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 Wt={};fr(Wt,{ArrayLengthMismatchError:()=>hh,BytesSizeMismatchError:()=>td,DataSizeTooSmallError:()=>Lb,InvalidArrayError:()=>fh,InvalidTypeError:()=>hl,LengthMismatchError:()=>yh,ZeroDataError:()=>Db,decode:()=>Ub,encode:()=>fl,encodePacked:()=>Ob,format:()=>J9,from:()=>Z9});function Ub(e,t,n={}){let{as:r="Array",checksumAddress:o=!1}=n,s=typeof t=="string"?wt(t):t,i=Nb(s);if(wr(s)===0&&e.length>0)throw new Db;if(wr(s)&&wr(s)<32)throw new Lb({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]=ml(i,u,{checksumAddress:o,staticPosition:0});a+=p,r==="Array"?l.push(d):l[u.name??c]=d}return l}function fl(e,t,n){let{checksumAddress:r=!1}=n??{};if(e.length!==t.length)throw new yh({expectedLength:e.length,givenLength:t.length});let o=xB({checksumAddress:r,parameters:e,values:t}),s=Ib(o);return s.length===0?"0x":s}function Ob(e,t){if(e.length!==t.length)throw new yh({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(Ob.encode(o,s))}return Jt(...n)}function J9(e){return Ko(e)}function Z9(e){return Array.isArray(e)&&typeof e[0]=="string"?lb(e):typeof e=="string"?lb(e):e}var Lb,Db,hh,td,yh,fh,hl,gh=L(()=>{"use strict";cb();ji();Xt();An();Tn();AB();KE();Zu();(function(e){function t(n,r,o=!1){if(n==="address"){let l=r;return Xo(l),Qo(l.toLowerCase(),o?32:0)}if(n==="string")return Vs(r);if(n==="bytes")return r;if(n==="bool")return Qo(lh(r),o?32:1);let s=n.match(Ju);if(s){let[l,c,u="256"]=s,d=Number.parseInt(u,10)/8;return mt(r,{size:o?32:d,signed:c==="int"})}let i=n.match(Rb);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(vB);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 hl(n)}e.encode=t})(Ob||(Ob={}));Lb=class extends le{constructor({data:t,parameters:n,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${Ko(n)})`,`Data: ${t} (${r} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}},Db=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"})}},hh=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${rt(n)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}},yh=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
|
-
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}},fh=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"})}},hl=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 SB=L(()=>{"use strict"});var PB=L(()=>{"use strict"});var EB=L(()=>{"use strict"});var Ie={};fr(Ie,{decodeData:()=>r7,decodeResult:()=>o7,encodeData:()=>s7,encodeResult:()=>i7,format:()=>a7,from:()=>l7,fromAbi:()=>gl,getSelector:()=>RB});function r7(...e){let[t,n]=(()=>{if(Array.isArray(e[0])){let[s,i,a]=e;return[gl(s,i),a]}return e})(),{overloads:r}=t;if(rt(n)<4)throw new Eb({data:n});if(t.inputs?.length===0)return;let o=r?gl([t,...r],n):t;if(!(rt(n)<=4))return Ub(o.inputs,$t(n,4))}function o7(...e){let[t,n,r={}]=(()=>{if(Array.isArray(e[0])){let[s,i,a,l]=e;return[gl(s,i),a,l]}return e})(),o=Ub(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 s7(...e){let[t,n=[]]=(()=>{if(Array.isArray(e[0])){let[c,u,d]=e;return[gl(c,u,{args:d}),d]}let[a,l]=e;return[a,l]})(),{overloads:r}=t,o=r?gl([t,...r],t.name,{args:n}):t,s=RB(o),i=n.length>0?fl(o.inputs,n):void 0;return i?Jt(s,i):s}function i7(...e){let[t,n,r={}]=(()=>{if(Array.isArray(e[0])){let[i,a,l,c]=e;return[gl(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 fl(t.outputs,s)}function a7(e){return el(e)}function l7(e,t={}){return bB(e,t)}function gl(e,t,n){let r=mh(e,t,n);if(r.type!=="function")throw new Xu({name:t,type:"function"});return r}function RB(e){return qE(e)}var _B=L(()=>{"use strict";cb();HE();gh();Tn()});var IB=L(()=>{"use strict"});var CB=L(()=>{"use strict"});function YE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function OB(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 u7(e){if(typeof e!="function")throw new Error("function expected");return!0}function QE(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function JE(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function XE(e){if(!Array.isArray(e))throw new Error("array expected")}function LB(e,t){if(!OB(!0,t))throw new Error(`${e}: array of strings expected`)}function d7(e,t){if(!OB(!1,t))throw new Error(`${e}: array of numbers expected`)}function DB(...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 p7(e){let t=typeof e=="string"?e.split(""):e,n=t.length;LB("alphabet",t);let r=new Map(t.map((o,s)=>[o,s]));return{encode:o=>(XE(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=>(XE(o),o.map(s=>{QE("alphabet.decode",s);let i=r.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return i}))}}function m7(e=""){return QE("join",e),{encode:t=>(LB("join.decode",t),t.join(e)),decode:t=>(QE("join.decode",t),t.split(e))}}function NB(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(XE(e),!e.length)return[];let r=0,o=[],s=Array.from(e,a=>{if(JE(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 h7(e){JE(e);let t=2**8;return{encode:n=>{if(!YE(n))throw new Error("radix.encode input should be Uint8Array");return NB(Array.from(n),t,e)},decode:n=>(d7("radix.decode",n),Uint8Array.from(NB(n,e,t)))}}function f7(e,t){return JE(e),u7(t),{encode(n){if(!YE(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(!YE(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 g7,y7,UB,BB=L(()=>{"use strict";g7=e=>DB(h7(58),p7(e),m7("")),y7=g7("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),UB=e=>DB(f7(4,t=>e(e(t))),y7)});function MB(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function b7(e){let t=MB(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function nR(e,t=""){return(0,ZE.pbkdf2)(eR.sha512,b7(e).nfkd,w7(t),{c:2048,dkLen:64})}var ZE,eR,tR,w7,rR=L(()=>{"use strict";ZE=require("@noble/hashes/pbkdf2"),eR=require("@noble/hashes/sha2"),tR=require("@noble/hashes/utils");w7=e=>MB("mnemonic"+e)});function bh(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function Wi(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 wh(e){let t=e.toString(16);return t.length&1?"0"+t:t}function FB(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?iR:BigInt("0x"+e)}function nd(e){return FB((0,vr.bytesToHex)(e))}function aR(e){return(0,vr.abytes)(e),FB((0,vr.bytesToHex)(Uint8Array.from(e).reverse()))}function Bb(e,t){return(0,vr.hexToBytes)(e.toString(16).padStart(t*2,"0"))}function lR(e,t){return Bb(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 qB(e,t,n){return oR(e)&&oR(t)&&oR(n)&&t<=e&&e<n}function HB(e,t,n,r){if(!qB(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Mb(e){let t;for(t=0;e>iR;e>>=sR,t+=1);return t}function $B(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 vh(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 cR(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,iR,sR,oR,zi,Fb=L(()=>{"use strict";vr=require("@noble/hashes/utils.js"),Qe=require("@noble/hashes/utils.js");iR=BigInt(0),sR=BigInt(1);oR=e=>typeof e=="bigint"&&iR<=e;zi=e=>(sR<<BigInt(e))-sR});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 VB(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 uR(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function QB(e,t){let n=(e.ORDER+Pn)/zB,r=e.pow(t,n);return uR(e,r,t),r}function x7(e,t){let n=(e.ORDER-GB)/KB,r=e.mul(t,yl),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,yl),o),a=e.mul(s,e.sub(i,e.ONE));return uR(e,a,t),a}function A7(e){let t=Gi(e),n=XB(e),r=n(t,t.neg(t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+v7)/YB;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 uR(a,y,l),y}}function XB(e){if(e<WB)throw new Error("sqrt is not defined for small field");let t=e-Pn,n=0;for(;t%yl===Hn;)t/=yl,n++;let r=yl,o=Gi(e);for(;jB(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return QB;let s=o.pow(r,t),i=(t+Pn)/yl;return function(l,c){if(l.is0(c))return c;if(jB(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 T7(e){return e%zB===WB?QB:e%KB===GB?x7:e%YB===k7?A7(e):XB(e)}function dR(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=S7.reduce((r,o)=>(r[o]="function",r),t);return vh(e,n),e}function P7(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 qb(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 jB(e,t){let n=(e.ORDER-Pn)/yl,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 Hb(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 Gi(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}=Hb(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:zi(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)=>P7(d,p,m),div:(p,m)=>sr(p*VB(m,e),e),sqrN:p=>p*p,addN:(p,m)=>p+m,subN:(p,m)=>p-m,mulN:(p,m)=>p*m,inv:p=>VB(p,e),sqrt:s||(p=>(u||(u=T7(e)),u(d,p))),toBytes:p=>n?lR(p,c):Bb(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?aR(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=>qb(d,p),cmov:(p,m,g)=>g?m:p});return Object.freeze(d)}function JB(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=JB(e);return t+Math.ceil(t/2)}function mR(e,t,n=!1){let r=e.length,o=JB(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?aR(e):nd(e),a=sr(i,t-Pn)+Pn;return n?lR(a,o):Bb(a,o)}var Hn,Pn,yl,WB,zB,GB,v7,KB,k7,YB,S7,kh=L(()=>{"use strict";Fb();Hn=BigInt(0),Pn=BigInt(1),yl=BigInt(2),WB=BigInt(3),zB=BigInt(4),GB=BigInt(5),v7=BigInt(7),KB=BigInt(8),k7=BigInt(9),YB=BigInt(16);S7=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function xh(e,t){let n=t.negate();return e?n:t}function Vb(e,t){let n=qb(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function nM(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function hR(e,t){nM(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=zi(e),i=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function ZB(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+=bl);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 E7(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 R7(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 gR(e){return rM.get(e)||1}function eM(e){if(e!==rd)throw new Error("invalid wNAF")}function oM(e,t,n,r){let o=t,s=e.ZERO,i=e.ZERO;for(;n>rd||r>rd;)n&bl&&(s=s.add(o)),r&bl&&(i=i.add(o)),o=o.double(),n>>=bl,r>>=bl;return{p1:s,p2:i}}function sM(e,t,n,r){E7(n,e),R7(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=Mb(BigInt(o)),l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);let c=zi(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 tM(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return dR(t),t}else return Gi(e,{isLE:n})}function iM(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=tM(t.p,n.Fp,r),s=tM(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,bl,fR,rM,$b,aM=L(()=>{"use strict";Fb();kh();rd=BigInt(0),bl=BigInt(1);fR=new WeakMap,rM=new WeakMap;$b=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&bl&&(r=r.add(o)),o=o.double(),n>>=bl;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=hR(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=hR(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:c,isZero:u,isNeg:d,isNegF:p,offsetF:m}=ZB(r,a,i);r=l,u?s=s.add(xh(p,n[m])):o=o.add(xh(d,n[c]))}return eM(r),{p:o,f:s}}wNAFUnsafe(t,n,r,o=this.ZERO){let s=hR(t,this.bits);for(let i=0;i<s.windows&&r!==rd;i++){let{nextN:a,offset:l,isZero:c,isNeg:u}=ZB(r,i,s);if(r=a,!c){let d=n[l];o=o.add(u?d.negate():d)}}return eM(r),o}getPrecomputes(t,n,r){let o=fR.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),fR.set(n,o))),o}cached(t,n,r){let o=gR(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let s=gR(t);return s===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,o)}createCache(t,n){nM(n,this.bits),rM.set(t,n),fR.delete(t)}hasCache(t){return gR(t)!==1}}});function _7(e,t,n){let[[r,o],[s,i]]=t,a=lM(i*e,n),l=lM(-o*e,n),c=e-a*r-l*s,u=-a*o-l*i,d=c<Ws,p=u<Ws;d&&(c=-c),p&&(u=-u);let m=zi(Math.ceil(Mb(n)/2))+sd;if(c<Ws||c>=m||u<Ws||u>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:c,k2neg:p,k2:u}}function bR(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function yR(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return bh(n.lowS,"lowS"),bh(n.prehash,"prehash"),n.format!==void 0&&bR(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 C7(e,t={}){let n=iM("weierstrass",e,t),{Fp:r,Fn:o}=n,s=n.CURVE,{h:i,n:a}=s;vh(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=mM(r,o);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(oe,F,z){let{x:_,y:N}=F.toAffine(),G=r.toBytes(_);if(bh(z,"isCompressed"),z){u();let ne=!r.isOdd(N);return(0,Qe.concatBytes)(pM(ne),G)}else return(0,Qe.concatBytes)(Uint8Array.of(4),G,r.toBytes(N))}function p(oe){Wi(oe,void 0,"Point");let{publicKey:F,publicKeyUncompressed:z}=c,_=oe.length,N=oe[0],G=oe.subarray(1);if(_===F&&(N===2||N===3)){let ne=r.fromBytes(G);if(!r.isValid(ne))throw new Error("bad point: is not on curve, wrong x");let Z=f(ne),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:ne,y:Q}}else if(_===z&&N===4){let ne=r.BYTES,Z=r.fromBytes(G.subarray(0,ne)),Q=r.fromBytes(G.subarray(ne,ne*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 ${_}, expected compressed=${F} or uncompressed=${z}`)}let m=t.toBytes||d,g=t.fromBytes||p;function f(oe){let F=r.sqr(oe),z=r.mul(F,oe);return r.add(r.add(z,r.mul(oe,s.a)),s.b)}function y(oe,F){let z=r.sqr(F),_=f(oe);return r.eql(z,_)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=r.mul(r.pow(s.a,jb),I7),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 A(oe,F,z=!1){if(!r.isValid(F)||z&&r.is0(F))throw new Error(`bad point coordinate ${oe}`);return F}function k(oe){if(!(oe instanceof Y))throw new Error("ProjectivePoint expected")}function T(oe){if(!l||!l.basises)throw new Error("no endo");return _7(oe,l.basises,o.ORDER)}let D=cR((oe,F)=>{let{X:z,Y:_,Z:N}=oe;if(r.eql(N,r.ONE))return{x:z,y:_};let G=oe.is0();F==null&&(F=G?r.ONE:r.inv(N));let ne=r.mul(z,F),Z=r.mul(_,F),Q=r.mul(N,F);if(G)return{x:r.ZERO,y:r.ZERO};if(!r.eql(Q,r.ONE))throw new Error("invZ was invalid");return{x:ne,y:Z}}),q=cR(oe=>{if(oe.is0()){if(t.allowInfinityPoint&&!r.is0(oe.Y))return;throw new Error("bad point: ZERO")}let{x:F,y:z}=oe.toAffine();if(!r.isValid(F)||!r.isValid(z))throw new Error("bad point: x or y not field elements");if(!y(F,z))throw new Error("bad point: equation left != right");if(!oe.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function V(oe,F,z,_,N){return z=new Y(r.mul(z.X,oe),z.Y,z.Z),F=xh(_,F),z=xh(N,z),F.add(z)}class Y{constructor(F,z,_){this.X=A("x",F),this.Y=A("y",z,!0),this.Z=A("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(F){let{x:z,y:_}=F||{};if(!F||!r.isValid(z)||!r.isValid(_))throw new Error("invalid affine point");if(F instanceof Y)throw new Error("projective point not allowed");return r.is0(z)&&r.is0(_)?Y.ZERO:new Y(z,_,r.ONE)}static fromBytes(F){let z=Y.fromAffine(g(Wi(F,void 0,"point")));return z.assertValidity(),z}static fromHex(F){return Y.fromBytes(Sn("pointHex",F))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(F=8,z=!0){return de.createCache(this,F),z||this.multiply(jb),this}assertValidity(){q(this)}hasEvenY(){let{y:F}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(F)}equals(F){k(F);let{X:z,Y:_,Z:N}=this,{X:G,Y:ne,Z}=F,Q=r.eql(r.mul(z,Z),r.mul(G,N)),ie=r.eql(r.mul(_,Z),r.mul(ne,N));return Q&&ie}negate(){return new Y(this.X,r.neg(this.Y),this.Z)}double(){let{a:F,b:z}=s,_=r.mul(z,jb),{X:N,Y:G,Z:ne}=this,Z=r.ZERO,Q=r.ZERO,ie=r.ZERO,me=r.mul(N,N),Ne=r.mul(G,G),ke=r.mul(ne,ne),be=r.mul(N,G);return be=r.add(be,be),ie=r.mul(N,ne),ie=r.add(ie,ie),Z=r.mul(F,ie),Q=r.mul(_,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(_,ie),ke=r.mul(F,ke),be=r.sub(me,ke),be=r.mul(F,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,ne),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(F){k(F);let{X:z,Y:_,Z:N}=this,{X:G,Y:ne,Z}=F,Q=r.ZERO,ie=r.ZERO,me=r.ZERO,Ne=s.a,ke=r.mul(s.b,jb),be=r.mul(z,G),qe=r.mul(_,ne),We=r.mul(N,Z),dt=r.add(z,_),He=r.add(G,ne);dt=r.mul(dt,He),He=r.add(be,qe),dt=r.sub(dt,He),He=r.add(z,N);let it=r.add(G,Z);return He=r.mul(He,it),it=r.add(be,We),He=r.sub(He,it),it=r.add(_,N),Q=r.add(ne,Z),it=r.mul(it,Q),Q=r.add(qe,We),it=r.sub(it,Q),me=r.mul(Ne,He),Q=r.mul(ke,We),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),We=r.mul(Ne,We),He=r.mul(ke,He),qe=r.add(qe,We),We=r.sub(be,We),We=r.mul(Ne,We),He=r.add(He,We),be=r.mul(qe,He),ie=r.add(ie,be),be=r.mul(it,He),Q=r.mul(dt,Q),Q=r.sub(Q,be),be=r.mul(dt,qe),me=r.mul(it,me),me=r.add(me,be),new Y(Q,ie,me)}subtract(F){return this.add(F.negate())}is0(){return this.equals(Y.ZERO)}multiply(F){let{endo:z}=t;if(!o.isValidNot0(F))throw new Error("invalid scalar: out of range");let _,N,G=ne=>de.cached(this,ne,Z=>Vb(Y,Z));if(z){let{k1neg:ne,k1:Z,k2neg:Q,k2:ie}=T(F),{p:me,f:Ne}=G(Z),{p:ke,f:be}=G(ie);N=Ne.add(be),_=V(z.beta,me,ke,ne,Q)}else{let{p:ne,f:Z}=G(F);_=ne,N=Z}return Vb(Y,[_,N])[0]}multiplyUnsafe(F){let{endo:z}=t,_=this;if(!o.isValid(F))throw new Error("invalid scalar: out of range");if(F===Ws||_.is0())return Y.ZERO;if(F===sd)return _;if(de.hasCache(this))return this.multiply(F);if(z){let{k1neg:N,k1:G,k2neg:ne,k2:Z}=T(F),{p1:Q,p2:ie}=oM(Y,_,G,Z);return V(z.beta,Q,ie,N,ne)}else return de.unsafe(_,F)}multiplyAndAddUnsafe(F,z,_){let N=this.multiplyUnsafe(z).add(F.multiplyUnsafe(_));return N.is0()?void 0:N}toAffine(F){return D(this,F)}isTorsionFree(){let{isTorsionFree:F}=t;return i===sd?!0:F?F(Y,this):de.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:F}=t;return i===sd?this:F?F(Y,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(F=!0){return bh(F,"isCompressed"),this.assertValidity(),m(Y,this,F)}toHex(F=!0){return(0,Qe.bytesToHex)(this.toBytes(F))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(F=!0){return this.toBytes(F)}_setWindowSize(F){this.precompute(F)}static normalizeZ(F){return Vb(Y,F)}static msm(F,z){return sM(Y,o,F,z)}static fromPrivateKey(F){return Y.BASE.multiply(od(o,F))}}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 te=o.BITS,de=new $b(Y,t.endo?Math.ceil(te/2):te);return Y.BASE.precompute(8),Y}function pM(e){return Uint8Array.of(e?2:3)}function mM(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function N7(e,t={}){let{Fn:n}=e,r=t.randomBytes||Qe.randomBytes,o=Object.assign(mM(e.Fp,n),{seed:pR(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 mR(Wi(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 O7(e,t,n={}){(0,uM.ahash)(t),vh(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=n.randomBytes||Qe.randomBytes,o=n.hmac||((z,..._)=>(0,cM.hmac)(t,z,(0,Qe.concatBytes)(..._))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:l}=i,{keygen:c,getPublicKey:u,getSharedSecret:d,utils:p,lengths:m}=N7(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},f="compact";function y(z){let _=a>>sd;return z>_}function w(z,_){if(!i.isValidNot0(_))throw new Error(`invalid signature ${z}: out of range 1..Point.Fn.ORDER`);return _}function v(z,_){bR(_);let N=m.signature,G=_==="compact"?N:_==="recovered"?N+1:void 0;return Wi(z,G,`${_} signature`)}class A{constructor(_,N,G){this.r=w("r",_),this.s=w("s",N),G!=null&&(this.recovery=G),Object.freeze(this)}static fromBytes(_,N=f){v(_,N);let G;if(N==="der"){let{r:ie,s:me}=js.toSig(Wi(_));return new A(ie,me)}N==="recovered"&&(G=_[0],N="compact",_=_.subarray(1));let ne=i.BYTES,Z=_.subarray(0,ne),Q=_.subarray(ne,ne*2);return new A(i.fromBytes(Z),i.fromBytes(Q),G)}static fromHex(_,N){return this.fromBytes((0,Qe.hexToBytes)(_),N)}addRecoveryBit(_){return new A(this.r,this.s,_)}recoverPublicKey(_){let N=s.ORDER,{r:G,s:ne,recovery:Z}=this;if(Z==null||![0,1,2,3].includes(Z))throw new Error("recovery id invalid");if(a*dM<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)(pM((Z&1)===0),me)),ke=i.inv(ie),be=T(Sn("msgHash",_)),qe=i.create(-be*ke),We=i.create(ne*ke),dt=e.BASE.multiplyUnsafe(qe).add(Ne.multiplyUnsafe(We));if(dt.is0())throw new Error("point at infinify");return dt.assertValidity(),dt}hasHighS(){return y(this.s)}toBytes(_=f){if(bR(_),_==="der")return(0,Qe.hexToBytes)(js.hexFromSig(this));let N=i.toBytes(this.r),G=i.toBytes(this.s);if(_==="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(_){return(0,Qe.bytesToHex)(this.toBytes(_))}assertValidity(){}static fromCompact(_){return A.fromBytes(Sn("sig",_),"compact")}static fromDER(_){return A.fromBytes(Sn("sig",_),"der")}normalizeS(){return this.hasHighS()?new A(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(_){if(_.length>8192)throw new Error("input is too large");let N=nd(_),G=_.length*8-l;return G>0?N>>BigInt(G):N},T=n.bits2int_modN||function(_){return i.create(k(_))},D=zi(l);function q(z){return HB("num < 2^"+l,z,Ws,D),i.toBytes(z)}function V(z,_){return Wi(z,void 0,"message"),_?Wi(t(z),void 0,"prehashed message"):z}function Y(z,_,N){if(["recovered","canonical"].some(qe=>qe in N))throw new Error("sign() legacy options not supported");let{lowS:G,prehash:ne,extraEntropy:Z}=yR(N,g);z=V(z,ne);let Q=T(z),ie=od(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 We=k(qe);if(!i.isValidNot0(We))return;let dt=i.inv(We),He=e.BASE.multiply(We).toAffine(),it=i.create(He.x);if(it===Ws)return;let je=i.create(dt*i.create(ke+it*ie));if(je===Ws)return;let Ss=(He.x===it?0:2)|Number(He.y&sd),Mr=je;return G&&y(je)&&(Mr=i.neg(je),Ss^=1),new A(it,Mr,Ss)}return{seed:Ne,k2sig:be}}function te(z,_,N={}){z=Sn("message",z);let{seed:G,k2sig:ne}=Y(z,_,N);return $B(t.outputLen,i.BYTES,o)(G,ne)}function de(z){let _,N=typeof z=="string"||(0,Qe.isBytes)(z),G=!N&&z!==null&&typeof z=="object"&&typeof z.r=="bigint"&&typeof z.s=="bigint";if(!N&&!G)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(G)_=new A(z.r,z.s);else if(N){try{_=A.fromBytes(Sn("sig",z),"der")}catch(ne){if(!(ne instanceof js.Err))throw ne}if(!_)try{_=A.fromBytes(Sn("sig",z),"compact")}catch{return!1}}return _||!1}function oe(z,_,N,G={}){let{lowS:ne,prehash:Z,format:Q}=yR(G,g);if(N=Sn("publicKey",N),_=V(Sn("message",_),Z),"strict"in G)throw new Error("options.strict was renamed to lowS");let ie=Q===void 0?de(z):A.fromBytes(Sn("sig",z),Q);if(ie===!1)return!1;try{let me=e.fromBytes(N);if(ne&&ie.hasHighS())return!1;let{r:Ne,s:ke}=ie,be=T(_),qe=i.inv(ke),We=i.create(be*qe),dt=i.create(Ne*qe),He=e.BASE.multiplyUnsafe(We).add(me.multiplyUnsafe(dt));return He.is0()?!1:i.create(He.x)===Ne}catch{return!1}}function F(z,_,N={}){let{prehash:G}=yR(N,g);return _=V(_,G),A.fromBytes(z,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:c,getPublicKey:u,getSharedSecret:d,utils:p,lengths:m,Point:e,sign:te,verify:oe,recoverPublicKey:F,Signature:A,hash:t})}function L7(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=Gi(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 D7(e){let{CURVE:t,curveOpts:n}=L7(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 U7(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Hb(n.Fn.ORDER,n.Fn.BITS))})}function hM(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=D7(e),s=C7(t,n),i=O7(s,r,o);return U7(e,i)}var cM,uM,lM,wR,js,Ws,sd,dM,jb,I7,fM=L(()=>{"use strict";cM=require("@noble/hashes/hmac.js"),uM=require("@noble/hashes/utils");Fb();aM();kh();lM=(e,t)=>(e+(e>=0?t:-t)/dM)/t;wR=class extends Error{constructor(t=""){super(t)}},js={Err:wR,_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=wh(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let s=r>127?wh(o.length/2|128):"";return wh(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<Ws)throw new t("integer: negative integers are not allowed");let n=wh(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)}},Ws=BigInt(0),sd=BigInt(1),dM=BigInt(2),jb=BigInt(3),I7=BigInt(4)});function gM(e,t){let n=r=>hM({...e,hash:r});return{...n(t),create:n}}var yM=L(()=>{"use strict";fM();});function F7(e){let t=kR.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,bM,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,A=kr(v,n,t)*u%t,k=kr(A,i,t)*g%t,T=kr(k,r,t)*c%t,D=kr(T,bM,t);if(!vR.eql(vR.sqr(D),e))throw new Error("Cannot find square root");return D}var wM,B7,kR,M7,bM,vR,Zo,vM=L(()=>{"use strict";wM=require("@noble/hashes/sha2.js"),B7=require("@noble/hashes/utils.js");yM();kh();kR={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},M7={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},bM=BigInt(2);vR=Gi(kR.p,{sqrt:F7}),Zo=gM({...kR,Fp:vR,lowS:!0,endo:M7},wM.sha256)});function kM(e){(0,It.abytes)(e);let t=e.length===0?"0":(0,It.bytesToHex)(e);return BigInt("0x"+t)}function q7(e){if(typeof e!="bigint")throw new Error("bigint expected");return(0,It.hexToBytes)(e.toString(16).padStart(64,"0"))}var SR,xM,id,It,Wb,xR,H7,AR,TR,$7,V7,zb,Gb,AM=L(()=>{"use strict";kh();vM();SR=require("@noble/hashes/hmac"),xM=require("@noble/hashes/legacy"),id=require("@noble/hashes/sha2"),It=require("@noble/hashes/utils");BB();Wb=Zo.ProjectivePoint,xR=UB(id.sha256);H7=(0,It.utf8ToBytes)("Bitcoin seed"),AR={private:76066276,public:76067358},TR=2147483648,$7=e=>(0,xM.ripemd160)((0,id.sha256)(e)),V7=e=>(0,It.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,It.createView)(t).setUint32(0,e,!1),t},Gb=class e{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return V7(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 xR.encode(this.serialize(this.versions.private,(0,It.concatBytes)(new Uint8Array([0]),t)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return xR.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(t,n=AR){if((0,It.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,SR.hmac)(id.sha512,H7,t);return new e({versions:n,chainCode:r.slice(32),privateKey:r.slice(0,32)})}static fromExtendedKey(t,n=AR){let r=xR.decode(t),o=(0,It.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||AR,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(!Zo.utils.isValidPrivateKey(t.privateKey))throw new Error("Invalid private key");this.privKey=typeof t.privateKey=="bigint"?t.privateKey:kM(t.privateKey),this.privKeyBytes=q7(this.privKey),this.pubKey=Zo.getPublicKey(t.privateKey,!0)}else if(t.publicKey)this.pubKey=Wb.fromHex(t.publicKey).toRawBytes(!0);else throw new Error("HDKey: no public or private key provided");this.pubHash=$7(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>=TR)throw new Error("Invalid index");s[2]==="'"&&(a+=TR),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>=TR){let a=this.privateKey;if(!a)throw new Error("Could not derive hardened child key");n=(0,It.concatBytes)(new Uint8Array([0]),a,n)}else n=(0,It.concatBytes)(this.pubKey,n);let r=(0,SR.hmac)(id.sha512,this.chainCode,n),o=kM(r.slice(0,32)),s=r.slice(32);if(!Zo.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,Zo.CURVE.n);if(!Zo.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=Wb.fromHex(this.pubKey).add(Wb.fromPrivateKey(o));if(a.equals(Wb.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,It.abytes)(t,32),Zo.sign(t,this.privKey).toCompactRawBytes()}verify(t,n){if((0,It.abytes)(t,32),(0,It.abytes)(n,64),!this.publicKey)throw new Error("No publicKey set!");let r;try{r=Zo.Signature.fromCompact(n)}catch{return!1}return Zo.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,It.abytes)(n,33),(0,It.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 Kb(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 _M(e,t){let n=(e.ORDER+Rn)/PM,r=e.pow(t,n);if(!e.eql(e.sqr(r),t))throw new Error("Cannot find square root");return r}function W7(e,t){let n=(e.ORDER-EM)/RM,r=e.mul(t,wl),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,wl),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 z7(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-Rn,n=0;for(;t%wl===$n;)t/=wl,n++;let r=wl,o=Ah(e);for(;TM(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return _M;let s=o.pow(r,t),i=(t+Rn)/wl;return function(l,c){if(l.is0(c))return c;if(TM(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 G7(e){return e%PM===j7?_M:e%RM===EM?W7:z7(e)}function PR(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=K7.reduce((r,o)=>(r[o]="function",r),t);return ol(e,n)}function Y7(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 ER(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 TM(e,t){let n=(e.ORDER-Rn)/wl,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 RR(e,t){t!==void 0&&(0,SM.anumber)(t);let n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Ah(e,t,n=!1,r={}){if(e<=$n)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=RR(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:rl(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)=>Y7(a,l,c),div:(l,c)=>En(l*Kb(c,e),e),sqrN:l=>l*l,addN:(l,c)=>l+c,subN:(l,c)=>l-c,mulN:(l,c)=>l*c,inv:l=>Kb(l,e),sqrt:r.sqrt||(l=>(i||(i=G7(e)),i(a,l))),toBytes:l=>n?hE(l,s):tl(l,s),fromBytes:l=>{if(l.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+l.length);return n?mE(l):qs(l)},invertBatch:l=>ER(a,l),cmov:(l,c,u)=>u?c:l});return Object.freeze(a)}function IM(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 _R(e){let t=IM(e);return t+Math.ceil(t/2)}function CM(e,t,n=!1){let r=e.length,o=IM(t),s=_R(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);let i=n?mE(e):qs(e),a=En(i,t-Rn)+Rn;return n?hE(a,o):tl(a,o)}var SM,$n,Rn,wl,j7,PM,EM,RM,K7,Yb=L(()=>{"use strict";SM=require("@noble/hashes/utils");Hu();$n=BigInt(0),Rn=BigInt(1),wl=BigInt(2),j7=BigInt(3),PM=BigInt(4),EM=BigInt(5),RM=BigInt(8);K7=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function IR(e,t){let n=t.negate();return e?n:t}function LM(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function CR(e,t){LM(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=rl(e),i=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function OM(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+=LR);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 Q7(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 X7(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 OR(e){return DM.get(e)||1}function UM(e,t){return{constTimeNegate:IR,hasPrecomputes(n){return OR(n)!==1},unsafeLadder(n,r,o=e.ZERO){let s=n;for(;r>NM;)r&LR&&(o=o.add(s)),s=s.double(),r>>=LR;return o},precomputeWindow(n,r){let{windows:o,windowSize:s}=CR(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=CR(n,t);for(let l=0;l<a.windows;l++){let{nextN:c,offset:u,isZero:d,isNeg:p,isNegF:m,offsetF:g}=OM(o,l,a);o=c,d?i=i.add(IR(m,r[g])):s=s.add(IR(p,r[u]))}return{p:s,f:i}},wNAFUnsafe(n,r,o,s=e.ZERO){let i=CR(n,t);for(let a=0;a<i.windows&&o!==NM;a++){let{nextN:l,offset:c,isZero:u,isNeg:d}=OM(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=NR.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&NR.set(r,o(s))),s},wNAFCached(n,r,o){let s=OR(n);return this.wNAF(s,this.getPrecomputes(s,n,o),r)},wNAFCachedUnsafe(n,r,o,s){let i=OR(n);return i===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(i,this.getPrecomputes(i,n,o),r,s)},setWindowSize(n,r){LM(r,t),DM.set(n,r),NR.delete(n)}}}function BM(e,t,n,r){Q7(n,e),X7(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=XU(BigInt(o)),l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);let c=rl(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 DR(e){return PR(e.Fp),ol(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...RR(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}var NM,LR,NR,DM,MM=L(()=>{"use strict";Yb();Hu();NM=BigInt(0),LR=BigInt(1);NR=new WeakMap,DM=new WeakMap});function FM(e){e.lowS!==void 0&&Fu("lowS",e.lowS),e.prehash!==void 0&&Fu("prehash",e.prehash)}function J7(e){let t=DR(e);ol(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 UR(e,t){return qu(tl(e,t))}function eQ(e){let t=J7(e),{Fp:n}=t,r=Ah(t.n,t.nBitLength),o=t.toBytes||((A,k,T)=>{let D=k.toAffine();return th(Uint8Array.from([4]),n.toBytes(D.x),n.toBytes(D.y))}),s=t.fromBytes||(A=>{let k=A.subarray(1),T=n.fromBytes(k.subarray(0,n.BYTES)),D=n.fromBytes(k.subarray(n.BYTES,2*n.BYTES));return{x:T,y:D}});function i(A){let{a:k,b:T}=t,D=n.sqr(A),q=n.mul(D,A);return n.add(n.add(q,n.mul(A,k)),T)}function a(A,k){let T=n.sqr(k),D=i(A);return n.eql(T,D)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let l=n.mul(n.pow(t.a,BR),Z7),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(A){return db(A,an,t.n)}function d(A){let{allowedPrivateKeyLengths:k,nByteLength:T,wrapPrivateKey:D,n:q}=t;if(k&&typeof A!="bigint"){if(Mu(A)&&(A=qu(A)),typeof A!="string"||!k.includes(A.length))throw new Error("invalid private key");A=A.padStart(T*2,"0")}let V;try{V=typeof A=="bigint"?A:qs(or("private key",A,T))}catch{throw new Error("invalid private key, expected hex or "+T+" bytes, got "+typeof A)}return D&&(V=En(V,q)),nl("private key",V,an,q),V}function p(A){if(!(A instanceof f))throw new Error("ProjectivePoint expected")}let m=fE((A,k)=>{let{px:T,py:D,pz:q}=A;if(n.eql(q,n.ONE))return{x:T,y:D};let V=A.is0();k==null&&(k=V?n.ONE:n.inv(q));let Y=n.mul(T,k),te=n.mul(D,k),de=n.mul(q,k);if(V)return{x:n.ZERO,y:n.ZERO};if(!n.eql(de,n.ONE))throw new Error("invZ was invalid");return{x:Y,y:te}}),g=fE(A=>{if(A.is0()){if(t.allowInfinityPoint&&!n.is0(A.py))return;throw new Error("bad point: ZERO")}let{x:k,y:T}=A.toAffine();if(!n.isValid(k)||!n.isValid(T))throw new Error("bad point: x or y not FE");if(!a(k,T))throw new Error("bad point: equation left != right");if(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(k,T,D){if(k==null||!n.isValid(k))throw new Error("x required");if(T==null||!n.isValid(T)||n.is0(T))throw new Error("y required");if(D==null||!n.isValid(D))throw new Error("z required");this.px=k,this.py=T,this.pz=D,Object.freeze(this)}static fromAffine(k){let{x:T,y:D}=k||{};if(!k||!n.isValid(T)||!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(T)&&q(D)?f.ZERO:new f(T,D,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(k){let T=ER(n,k.map(D=>D.pz));return k.map((D,q)=>D.toAffine(T[q])).map(f.fromAffine)}static fromHex(k){let T=f.fromAffine(s(or("pointHex",k)));return T.assertValidity(),T}static fromPrivateKey(k){return f.BASE.multiply(d(k))}static msm(k,T){return BM(f,r,k,T)}_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:T,py:D,pz:q}=this,{px:V,py:Y,pz:te}=k,de=n.eql(n.mul(T,te),n.mul(V,q)),oe=n.eql(n.mul(D,te),n.mul(Y,q));return de&&oe}negate(){return new f(this.px,n.neg(this.py),this.pz)}double(){let{a:k,b:T}=t,D=n.mul(T,BR),{px:q,py:V,pz:Y}=this,te=n.ZERO,de=n.ZERO,oe=n.ZERO,F=n.mul(q,q),z=n.mul(V,V),_=n.mul(Y,Y),N=n.mul(q,V);return N=n.add(N,N),oe=n.mul(q,Y),oe=n.add(oe,oe),te=n.mul(k,oe),de=n.mul(D,_),de=n.add(te,de),te=n.sub(z,de),de=n.add(z,de),de=n.mul(te,de),te=n.mul(N,te),oe=n.mul(D,oe),_=n.mul(k,_),N=n.sub(F,_),N=n.mul(k,N),N=n.add(N,oe),oe=n.add(F,F),F=n.add(oe,F),F=n.add(F,_),F=n.mul(F,N),de=n.add(de,F),_=n.mul(V,Y),_=n.add(_,_),F=n.mul(_,N),te=n.sub(te,F),oe=n.mul(_,z),oe=n.add(oe,oe),oe=n.add(oe,oe),new f(te,de,oe)}add(k){p(k);let{px:T,py:D,pz:q}=this,{px:V,py:Y,pz:te}=k,de=n.ZERO,oe=n.ZERO,F=n.ZERO,z=t.a,_=n.mul(t.b,BR),N=n.mul(T,V),G=n.mul(D,Y),ne=n.mul(q,te),Z=n.add(T,D),Q=n.add(V,Y);Z=n.mul(Z,Q),Q=n.add(N,G),Z=n.sub(Z,Q),Q=n.add(T,q);let ie=n.add(V,te);return Q=n.mul(Q,ie),ie=n.add(N,ne),Q=n.sub(Q,ie),ie=n.add(D,q),de=n.add(Y,te),ie=n.mul(ie,de),de=n.add(G,ne),ie=n.sub(ie,de),F=n.mul(z,Q),de=n.mul(_,ne),F=n.add(de,F),de=n.sub(G,F),F=n.add(G,F),oe=n.mul(de,F),G=n.add(N,N),G=n.add(G,N),ne=n.mul(z,ne),Q=n.mul(_,Q),G=n.add(G,ne),ne=n.sub(N,ne),ne=n.mul(z,ne),Q=n.add(Q,ne),N=n.mul(G,Q),oe=n.add(oe,N),N=n.mul(ie,Q),de=n.mul(Z,de),de=n.sub(de,N),N=n.mul(Z,G),F=n.mul(ie,F),F=n.add(F,N),new f(de,oe,F)}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:T,n:D}=t;nl("scalar",k,Gs,D);let q=f.ZERO;if(k===Gs)return q;if(this.is0()||k===an)return this;if(!T||v.hasPrecomputes(this))return v.wNAFCachedUnsafe(this,k,f.normalizeZ);let{k1neg:V,k1:Y,k2neg:te,k2:de}=T.splitScalar(k),oe=q,F=q,z=this;for(;Y>Gs||de>Gs;)Y&an&&(oe=oe.add(z)),de&an&&(F=F.add(z)),z=z.double(),Y>>=an,de>>=an;return V&&(oe=oe.negate()),te&&(F=F.negate()),F=new f(n.mul(F.px,T.beta),F.py,F.pz),oe.add(F)}multiply(k){let{endo:T,n:D}=t;nl("scalar",k,an,D);let q,V;if(T){let{k1neg:Y,k1:te,k2neg:de,k2:oe}=T.splitScalar(k),{p:F,f:z}=this.wNAF(te),{p:_,f:N}=this.wNAF(oe);F=v.constTimeNegate(Y,F),_=v.constTimeNegate(de,_),_=new f(n.mul(_.px,T.beta),_.py,_.pz),q=F.add(_),V=z.add(N)}else{let{p:Y,f:te}=this.wNAF(k);q=Y,V=te}return f.normalizeZ([q,V])[0]}multiplyAndAddUnsafe(k,T,D){let q=f.BASE,V=(te,de)=>de===Gs||de===an||!te.equals(q)?te.multiplyUnsafe(de):te.multiply(de),Y=V(this,T).add(V(k,D));return Y.is0()?void 0:Y}toAffine(k){return m(this,k)}isTorsionFree(){let{h:k,isTorsionFree:T}=t;if(k===an)return!0;if(T)return T(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:k,clearCofactor:T}=t;return k===an?this:T?T(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=UM(f,y?Math.ceil(w/2):w);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:d,weierstrassEquation:i,isWithinCurveOrder:u}}function tQ(e){let t=DR(e);return ol(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function qM(e){let t=tQ(e),{Fp:n,n:r,nByteLength:o,nBitLength:s}=t,i=n.BYTES+1,a=2*n.BYTES+1;function l(_){return En(_,r)}function c(_){return Kb(_,r)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:p,isWithinCurveOrder:m}=eQ({...t,toBytes(_,N,G){let ne=N.toAffine(),Z=n.toBytes(ne.x),Q=th;return Fu("isCompressed",G),G?Q(Uint8Array.from([N.hasEvenY()?2:3]),Z):Q(Uint8Array.from([4]),Z,n.toBytes(ne.y))},fromBytes(_){let N=_.length,G=_[0],ne=_.subarray(1);if(N===i&&(G===2||G===3)){let Z=qs(ne);if(!db(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(ne.subarray(0,n.BYTES)),Q=n.fromBytes(ne.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(_){let N=r>>an;return _>N}function f(_){return g(_)?l(-_):_}let y=(_,N,G)=>qs(_.slice(N,G));class w{constructor(N,G,ne){nl("r",N,an,r),nl("s",G,an,r),this.r=N,this.s=G,ne!=null&&(this.recovery=ne),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:ne}=zs.toSig(or("DER",N));return new w(G,ne)}assertValidity(){}addRecoveryBit(N){return new w(this.r,this.s,N)}recoverPublicKey(N){let{r:G,s:ne,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+UR(ie,n.BYTES)),ke=c(ie),be=l(-Q*ke),qe=l(ne*ke),We=u.BASE.multiplyAndAddUnsafe(Ne,be,qe);if(!We)throw new Error("point at infinify");return We.assertValidity(),We}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,l(-this.s),this.recovery):this}toDERRawBytes(){return eh(this.toDERHex())}toDERHex(){return zs.hexFromSig(this)}toCompactRawBytes(){return eh(this.toCompactHex())}toCompactHex(){let N=o;return UR(this.r,N)+UR(this.s,N)}}let v={isValidPrivateKey(_){try{return d(_),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let _=_R(t.n);return CM(t.randomBytes(_),t.n)},precompute(_=8,N=u.BASE){return N._setWindowSize(_),N.multiply(BigInt(3)),N}};function A(_,N=!0){return u.fromPrivateKey(_).toRawBytes(N)}function k(_){if(typeof _=="bigint")return!1;if(_ instanceof u)return!0;let G=or("key",_).length,ne=n.BYTES,Z=ne+1,Q=2*ne+1;if(!(t.allowedPrivateKeyLengths||o===Z))return G===Z||G===Q}function T(_,N,G=!0){if(k(_)===!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(_)).toRawBytes(G)}let D=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let N=qs(_),G=_.length*8-s;return G>0?N>>BigInt(G):N},q=t.bits2int_modN||function(_){return l(D(_))},V=rl(s);function Y(_){return nl("num < 2^"+s,_,Gs,V),tl(_,o)}function te(_,N,G=de){if(["recovered","canonical"].some(He=>He in G))throw new Error("sign() legacy options not supported");let{hash:ne,randomBytes:Z}=t,{lowS:Q,prehash:ie,extraEntropy:me}=G;Q==null&&(Q=!0),_=or("msgHash",_),FM(G),ie&&(_=or("prehashed msgHash",ne(_)));let Ne=q(_),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=th(...be),We=Ne;function dt(He){let it=D(He);if(!m(it))return;let je=c(it),Ss=u.BASE.multiply(it).toAffine(),Mr=l(Ss.x);if(Mr===Gs)return;let _a=l(je*l(We+Mr*ke));if(_a===Gs)return;let ze=(Ss.x===Mr?0:2)|Number(Ss.y&an),vc=_a;return Q&&g(_a)&&(vc=f(_a),ze^=1),new w(Mr,vc,ze)}return{seed:qe,k2sig:dt}}let de={lowS:t.lowS,prehash:!1},oe={lowS:t.lowS,prehash:!1};function F(_,N,G=de){let{seed:ne,k2sig:Z}=te(_,N,G),Q=t;return JU(Q.hash.outputLen,Q.nByteLength,Q.hmac)(ne,Z)}u.BASE._setWindowSize(8);function z(_,N,G,ne=oe){let Z=_;N=or("msgHash",N),G=or("publicKey",G);let{lowS:Q,prehash:ie,format:me}=ne;if(FM(ne),"strict"in ne)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(ze){if(!(ze instanceof zs.Err))throw ze}!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:We,s:dt}=be,He=q(N),it=c(dt),je=l(He*it),Ss=l(We*it),Mr=u.BASE.multiplyAndAddUnsafe(qe,je,Ss)?.toAffine();return Mr?l(Mr.x)===We:!1}return{CURVE:t,getPublicKey:A,getSharedSecret:T,sign:F,verify:z,ProjectivePoint:u,Signature:w,utils:v}}var MR,zs,Gs,an,G_e,BR,Z7,HM=L(()=>{"use strict";MM();Yb();Hu();MR=class extends Error{constructor(t=""){super(t)}},zs={Err:MR,_tlv:{encode:(e,t)=>{let{Err:n}=zs;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=Zm(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let s=r>127?Zm(o.length/2|128):"";return Zm(e)+s+o+t},decode(e,t){let{Err:n}=zs,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}=zs;if(e<Gs)throw new t("integer: negative integers are not allowed");let n=Zm(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}=zs;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}=zs,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}=zs,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),G_e=BigInt(2),BR=BigInt(3),Z7=BigInt(4)});function nQ(e){return{hash:e,hmac:(t,...n)=>(0,$M.hmac)(e,t,(0,Qb.concatBytes)(...n)),randomBytes:Qb.randomBytes}}function VM(e,t){let n=r=>qM({...e,...nQ(r)});return{...n(t),create:n}}var $M,Qb,jM=L(()=>{"use strict";$M=require("@noble/hashes/hmac"),Qb=require("@noble/hashes/utils");HM();});function iQ(e){let t=KM,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,FR,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,A=xr(v,n,t)*u%t,k=xr(A,i,t)*g%t,T=xr(k,r,t)*c%t,D=xr(T,FR,t);if(!qR.eql(qR.sqr(D),e))throw new Error("Cannot find square root");return D}var GM,rQ,KM,WM,oQ,sQ,FR,zM,qR,Ar,HR=L(()=>{"use strict";GM=require("@noble/hashes/sha2"),rQ=require("@noble/hashes/utils");jM();Yb();KM=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),WM=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),oQ=BigInt(0),sQ=BigInt(1),FR=BigInt(2),zM=(e,t)=>(e+t/FR)/t;qR=Ah(KM,void 0,void 0,{sqrt:iQ}),Ar=VM({a:oQ,b:BigInt(7),Fp:qR,n:WM,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=WM,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-sQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,i=BigInt("0x100000000000000000000000000000000"),a=zM(s*e,t),l=zM(-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}}}},GM.sha256)});var YM,QM=L(()=>{"use strict";YM=!1});function XM(e,t,n={}){let{validate:r}=n;for(let o=0;;o++){let s=RE(e,zu(t,Gu(o,{size:4})),{as:"Bytes"});if(!r||r(s))return s;s.fill(0)}}var JM=L(()=>{"use strict";Xt();cl()});function ZM(e,t={}){let{path:n="m/44'/60'/0'/0/0",passphrase:r}=t,o=Gb.fromMasterSeed(cQ(e,{passphrase:r})).derive(n).privateKey;return t.as==="Bytes"?o:Ke(o)}function cQ(e,t={}){return nR(e,t.passphrase)}var e2=L(()=>{"use strict";AM();rR();Tn()});var ad={};fr(ad,{InvalidSeedSizeError:()=>Xb,createKeyPair:()=>dQ,fromMnemonic:()=>pQ,fromSeed:()=>mQ,getPublicKey:()=>n2,getSharedSecret:()=>hQ,noble:()=>t2,randomPrivateKey:()=>r2,recoverAddress:()=>o2,recoverPublicKey:()=>s2,sign:()=>fQ,verify:()=>gQ});function dQ(e={}){let{as:t="Hex"}=e,n=r2({as:t}),r=n2({privateKey:n});return{privateKey:n,publicKey:r}}function pQ(e,t={}){let{as:n="Hex",passphrase:r,path:o}=t;return ZM(e,{as:n,passphrase:r,path:o})}function mQ(e,t={}){let{as:n="Hex"}=t,r=Fn(e);if(r.length<32)throw new Xb({size:r.length});let o=XM(r,yQ,{validate:t2.utils.isValidPrivateKey});if(n==="Hex"){let s=Ke(o);return o.fill(0),s}return o}function n2(e){let{privateKey:t}=e,n=Ar.ProjectivePoint.fromPrivateKey(uo(t).slice(2));return LE(n)}function hQ(e){let{as:t="Hex",privateKey:n,publicKey:r}=e,i=Ar.ProjectivePoint.fromHex(dh(r).slice(2)).multiply(Ar.utils.normPrivateKeyToScalar(uo(n).slice(2))).toRawBytes(!0);return t==="Hex"?Ke(i):i}function r2(e={}){let{as:t="Hex"}=e,n=Ar.utils.randomPrivateKey();return t==="Hex"?Ke(n):n}function o2(e){return UE(s2(e))}function s2(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 LE(a)}function fQ(e){let{extraEntropy:t=YM,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 gQ(e){let{hash:t,payload:n}=e;return e.address?BE(e.address,o2({payload:n,signature:e.signature})):Ar.verify(e.signature,Fn(n),gB(e.publicKey),...t?[{prehash:!0,lowS:!0}]:[])}var t2,Xb,yQ,i2=L(()=>{"use strict";HR();ji();Xt();An();Tn();QM();JM();e2();Ab();t2=Ar;Xb=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"})}},yQ=qn("ox.secp256k1.fromSeed.v1")});var a2=L(()=>{"use strict"});var l2=L(()=>{"use strict";rR()});var iIe,c2=L(()=>{"use strict";Xt();iIe=qn("ox.aesGcm.fromSeed.v1")});function kQ(e,t){let{as:n}=t,r=d2(e),o=Nb(new Uint8Array(r.length));return r.encode(o),n==="Hex"?Ke(o.bytes):o.bytes}function u2(e,t={}){let{as:n="Bytes"}=t;return kQ(e,{as:n})}function d2(e){return Array.isArray(e)?xQ(e.map(t=>d2(t))):AQ(e)}function xQ(e){let t=e.reduce((o,s)=>o+s.length,0),n=p2(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 AQ(e){let t=typeof e=="string"?wt(e):e,n=p2(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 p2(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 $R=L(()=>{"use strict";Xt();An();Tn();KE()});var ow={};fr(ow,{InvalidRError:()=>Zb,InvalidSError:()=>ew,InvalidSerializedSizeError:()=>Jb,InvalidVError:()=>tw,InvalidYParityError:()=>vl,MissingPropertiesError:()=>ld,assert:()=>nw,extract:()=>TQ,from:()=>jR,fromBytes:()=>h2,fromDerBytes:()=>SQ,fromDerHex:()=>f2,fromHex:()=>VR,fromLegacy:()=>g2,fromRpc:()=>y2,fromTuple:()=>PQ,toBytes:()=>EQ,toDerBytes:()=>RQ,toDerHex:()=>_Q,toHex:()=>b2,toLegacy:()=>IQ,toRpc:()=>CQ,toTuple:()=>NQ,vToYParity:()=>rw,validate:()=>OQ,yParityToV:()=>WR});function nw(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>$E)throw new Zb({value:e.r});if(e.s<0n||e.s>$E)throw new ew({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new vl({value:e.yParity})}function h2(e){return VR(Ke(e))}function VR(e){if(e.length!==130&&e.length!==132)throw new Jb({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 rw(o)}catch{throw new vl({value:o})}})();return typeof r>"u"?{r:t,s:n}:{r:t,s:n,yParity:r}}function TQ(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return jR(e)}function jR(e){let t=typeof e=="string"?VR(e):e instanceof Uint8Array?h2(e):typeof e.r=="string"?y2(e):e.v?g2(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return nw(t),t}function SQ(e){return f2(Ke(e))}function f2(e){let{r:t,s:n}=Ar.Signature.fromDER(uo(e).slice(2));return{r:t,s:n}}function g2(e){return{r:e.r,s:e.s,yParity:rw(e.v)}}function y2(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=rw(n)),typeof r!="number")throw new vl({value:e.yParity});return r})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function PQ(e){let[t,n,r]=e;return jR({r:n==="0x"?0n:BigInt(n),s:r==="0x"?0n:BigInt(r),yParity:t==="0x"?0:Number(t)})}function EQ(e){return wt(b2(e))}function b2(e){nw(e);let t=e.r,n=e.s;return Jt(mt(t,{size:32}),mt(n,{size:32}),typeof e.yParity=="number"?mt(WR(e.yParity),{size:1}):"0x")}function RQ(e){return new Ar.Signature(e.r,e.s).toDERRawBytes()}function _Q(e){return`0x${new Ar.Signature(e.r,e.s).toDERHex()}`}function IQ(e){return{r:e.r,s:e.s,v:WR(e.yParity)}}function CQ(e){let{r:t,s:n,yParity:r}=e;return{r:mt(t,{size:32}),s:mt(n,{size:32}),yParity:r===0?"0x0":"0x1"}}function NQ(e){let{r:t,s:n,yParity:r}=e;return[r?"0x01":"0x",t===0n?"0x":ch(mt(t)),n===0n?"0x":ch(mt(n))]}function OQ(e,t={}){try{return nw(e,t),!0}catch{return!1}}function rw(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 tw({value:e})}function WR(e){if(e===0)return 27;if(e===1)return 28;throw new vl({value:e})}var Jb,ld,Zb,ew,vl,tw,w2=L(()=>{"use strict";HR();Xt();An();Tn();il();Zu();Jb=class extends le{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${rt(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"})}},Zb=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"})}},ew=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"})}},vl=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"})}},tw=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 v2=L(()=>{"use strict"});var k2=L(()=>{"use strict"});var x2=L(()=>{"use strict"});var lIe,cIe,A2=L(()=>{"use strict";lIe=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),cIe={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var T2=L(()=>{"use strict"});var FQ,S2=L(()=>{"use strict";FQ=require("@noble/hashes/blake3")});var P2=L(()=>{"use strict"});var E2,$Q,R2,VQ,uIe,_2=L(()=>{"use strict";E2=6,$Q=32,R2=4096,VQ=$Q*R2,uIe=VQ*E2-1-1*R2*E2});var I2=L(()=>{"use strict"});var C2=L(()=>{"use strict"});var N2=L(()=>{"use strict"});var O2=L(()=>{"use strict"});var L2=L(()=>{"use strict"});var D2=L(()=>{"use strict"});var U2=L(()=>{"use strict"});var B2=L(()=>{"use strict"});var M2=L(()=>{"use strict"});function es(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 es.number(e);if(typeof e=="bigint")throw new QR;if(typeof e=="string")return es.string(e);if(Array.isArray(e))return es.array(e);if(e instanceof Uint8Array)return es.byteString(e);if(e instanceof ArrayBuffer)return es.byteString(new Uint8Array(e));if(ArrayBuffer.isView(e))return es.byteString(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(e instanceof Map)return es.map(e);if(typeof e=="object")return es.object(e);throw new XR({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 KR({tag:r});case 7:return Ks.readSimpleOrFloat(e,r);default:throw new zR({majorType:n})}}var zR,sw,GR,KR,iw,YR,QR,XR,aw,JR,ZR,lw,e_,F2=L(()=>{"use strict";Xt();An();zR=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"})}},sw=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"})}},GR=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"})}},KR=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"})}},iw=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"})}},YR=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"})}},QR=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"})}},XR=class extends le{constructor({token:t}){super(`Unexpected token: ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.UnexpectedTokenError"})}},aw=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"})}},JR=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"})}},ZR=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"})}},lw=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"})}},e_=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 aw({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 aw({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 JR({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 ZR({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 e_({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 lw({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 lw({size:u})}e.map=i})(es||(es={}));(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 GR:new sw({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 iw({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 iw({type:"text string"});g.push(y)}return g.join("")}let p=t(u,d),m=u.readBytes(p);return uh(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 YR({value:p});return}throw new sw({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 q2=L(()=>{"use strict"});var ho={};fr(ho,{from:()=>nX,fromCreate:()=>H2,fromCreate2:()=>$2});function nX(e){return e.salt?$2(e):H2(e)}function H2(e){let t=wt(dl(e.from)),n=Gu(e.nonce);return n[0]===0&&(n=new Uint8Array([])),dl(`0x${sn(u2([t,n],{as:"Hex"})).slice(26)}`)}function $2(e){let t=wt(dl(e.from)),n=bb(Ku(e.salt)?e.salt:wt(e.salt),32),r="bytecodeHash"in e?Ku(e.bytecodeHash)?e.bytecodeHash:wt(e.bytecodeHash):sn(e.bytecode,{as:"Bytes"});return dl($t(sn(zu(wt("0xff"),t,n,r),{as:"Hex"}),12))}var V2=L(()=>{"use strict";ji();Xt();cl();Tn();$R()});var j2=L(()=>{"use strict"});var dIe,W2=L(()=>{"use strict";Xt();dIe=qn("ox.ed25519.fromSeed.v1")});var sX,iX,aX,lX,z2,G2,K2,cX,uX,pIe,mIe,hIe,fIe,Y2=L(()=>{"use strict";sX=44032,iX=4352,aX=4449,lX=4519,z2=19,G2=21,K2=28,cX=G2*K2,uX=z2*cX,pIe=sX+uX,mIe=iX+z2,hIe=aX+G2,fIe=lX+K2});var Q2=L(()=>{"use strict";Y2()});var X2=L(()=>{"use strict"});var J2=L(()=>{"use strict"});var Z2=L(()=>{"use strict"});var eF=L(()=>{"use strict"});var tF,nF,fX,rF=L(()=>{"use strict";tF=require("@noble/hashes/pbkdf2"),nF=require("@noble/hashes/scrypt"),fX=require("@noble/hashes/sha2")});var oF=L(()=>{"use strict"});var wIe,sF=L(()=>{"use strict";Xt();wIe=qn("ox.p256.fromSeed.v1")});var iF=L(()=>{"use strict"});var lF=oz((vIe,t_)=>{"use strict";var vX=Object.prototype.hasOwnProperty,Vn="~";function Th(){}Object.create&&(Th.prototype=Object.create(null),new Th().__proto__||(Vn=!1));function kX(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function aF(e,t,n,r,o){if(typeof n!="function")throw new TypeError("The listener must be a function");var s=new kX(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 cw(e,t){--e._eventsCount===0?e._events=new Th:delete e._events[t]}function _n(){this._events=new Th,this._eventsCount=0}_n.prototype.eventNames=function(){var t=[],n,r;if(this._eventsCount===0)return t;for(r in n=this._events)vX.call(n,r)&&t.push(Vn?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(n)):t};_n.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};_n.prototype.listenerCount=function(t){var n=Vn?Vn+t:t,r=this._events[n];return r?r.fn?1:r.length:0};_n.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};_n.prototype.on=function(t,n,r){return aF(this,t,n,r,!1)};_n.prototype.once=function(t,n,r){return aF(this,t,n,r,!0)};_n.prototype.removeListener=function(t,n,r,o){var s=Vn?Vn+t:t;if(!this._events[s])return this;if(!n)return cw(this,s),this;var i=this._events[s];if(i.fn)i.fn===n&&(!o||i.once)&&(!r||i.context===r)&&cw(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:cw(this,s)}return this};_n.prototype.removeAllListeners=function(t){var n;return t?(n=Vn?Vn+t:t,this._events[n]&&cw(this,n)):(this._events=new Th,this._eventsCount=0),this};_n.prototype.off=_n.prototype.removeListener;_n.prototype.addListener=_n.prototype.on;_n.prefixed=Vn;_n.EventEmitter=_n;typeof t_<"u"&&(t_.exports=_n)});var cF,uF=L(()=>{"use strict";cF=jL(lF(),1)});var ir,n_,r_,o_,s_,i_,a_,l_,c_,u_,d_,p_,m_,dF=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??""}},n_=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(n_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});r_=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(r_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});o_=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(o_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});s_=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(s_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});i_=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(i_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});a_=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(a_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});l_=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(l_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});c_=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(c_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});u_=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(u_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});d_=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(d_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});p_=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(p_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});m_=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(m_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700})});var jn,h_,f_,g_,y_,b_,w_,v_,k_,x_,A_,T_,S_,P_,pF=L(()=>{"use strict";uF();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}},h_=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(h_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});f_=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(f_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});g_=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(g_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});y_=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(y_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});b_=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(b_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});w_=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(w_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});v_=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(v_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});k_=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(k_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});x_=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(x_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});A_=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(A_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});T_=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(T_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});S_=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(S_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});P_=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(P_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760})});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 wF=L(()=>{"use strict"});var vF=L(()=>{"use strict"});var kF=L(()=>{"use strict"});var xF=L(()=>{"use strict"});var AF=L(()=>{"use strict"});var TF=L(()=>{"use strict"});var SF=L(()=>{"use strict"});var PF=L(()=>{"use strict"});var EF=L(()=>{"use strict"});var fo={};fr(fo,{BytesSizeMismatchError:()=>uw,InvalidDomainError:()=>dw,InvalidPrimaryTypeError:()=>pw,InvalidStructTypeError:()=>mw,assert:()=>E_,domainSeparator:()=>FX,encode:()=>RF,encodeData:()=>I_,encodeField:()=>C_,encodeType:()=>_F,extractEip712DomainTypes:()=>hw,findTypeDependencies:()=>N_,getSignPayload:()=>qX,hashDomain:()=>R_,hashStruct:()=>__,hashType:()=>IF,serialize:()=>HX,validate:()=>$X});function E_(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;mt(d,{signed:f==="int",size:Number.parseInt(y??"",10)/8})}if(u==="address"&&typeof d=="string"&&!pl(d))throw new ul({address:d,cause:new Yu});let m=u.match(Rb);if(m){let[,f]=m;if(f&&rt(d)!==Number.parseInt(f,10))throw new uw({expectedSize:Number.parseInt(f,10),givenSize:rt(d)})}let g=o[u];g&&(VX(u),s(g,d))}};if(o.EIP712Domain&&t){if(typeof t!="object")throw new dw({domain:t});s(o.EIP712Domain,t)}if(r!=="EIP712Domain")if(o[r])s(o[r],n);else throw new pw({primaryType:r,types:o})}function FX(e){return R_({domain:e})}function RF(e){let{domain:t={},message:n,primaryType:r}=e,o={EIP712Domain:hw(t),...e.types};E_({domain:t,message:n,primaryType:r,types:o});let s=["0x19","0x01"];return t&&s.push(R_({domain:t,types:o})),r!=="EIP712Domain"&&s.push(__({data:n,primaryType:r,types:o})),Jt(...s)}function _F(e){let{primaryType:t,types:n}=e,r="",o=N_({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 hw(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 qX(e){return sn(RF(e))}function R_(e){let{domain:t,types:n}=e;return __({data:t,primaryType:"EIP712Domain",types:{...n,EIP712Domain:n?.EIP712Domain||hw(t)}})}function __(e){let{data:t,primaryType:n,types:r}=e,o=I_({data:t,primaryType:n,types:r});return sn(o)}function HX(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??hw(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 $X(e){try{return E_(e),!0}catch{return!1}}function I_(e){let{data:t,primaryType:n,types:r}=e,o=[{type:"bytes32"}],s=[IF({primaryType:n,types:r})];for(let i of r[n]??[]){let[a,l]=C_({types:r,name:i.name,type:i.type,value:t[i.name]});o.push(a),s.push(l)}return fl(o,s)}function IF(e){let{primaryType:t,types:n}=e,r=Vs(_F({primaryType:t,types:n}));return sn(r)}function C_(e){let{types:t,name:n,type:r,value:o}=e;if(t[r]!==void 0)return[{type:"bytes32"},sn(I_({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=>C_({name:n,type:s,types:t,value:a}));return[{type:"bytes32"},sn(fl(i.map(([a])=>a),i.map(([,a])=>a)))]}return[{type:r},o]}function N_(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])N_({primaryType:i.type,types:r},t);return t}function VX(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new mw({type:e})}var uw,dw,pw,mw,CF=L(()=>{"use strict";gh();ji();Xt();An();cl();Tn();il();Zu();uw=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"})}},dw=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"})}},pw=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"})}},mw=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 NF=L(()=>{"use strict"});var OF=L(()=>{"use strict"});var LF=L(()=>{"use strict"});var DF=L(()=>{"use strict"});var fw=L(()=>{"use strict";HU();SB();PB();EB();_B();HE();gh();IB();CB();ji();c2();v2();k2();x2();A2();T2();S2();_2();L2();D2();U2();B2();M2();Xt();_E();F2();q2();V2();j2();W2();Q2();An();X2();J2();I2();Z2();eF();C2();cl();a2();Tn();il();rF();P2();oF();l2();sF();iF();pF();Ab();$R();mF();dF();hF();fF();i2();w2();gF();Zu();yF();N2();bF();wF();kF();xF();AF();TF();SF();PF();EF();CF();NF();vF();OF();LF();O2();DF()});function kl(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 QF(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 ns(e){return this instanceof ns?(this.v=e,this):new ns(e)}function XF(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 ns?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 AJ(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:ns(e[o](i)),done:!1}:s?s(i):i}:s}}function TJ(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 QF=="function"?QF(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 xl(e){return new In(Promise.resolve(new Tr(e)))}function go(e){return new Gr(e)}function Sr(e){return new Tr(e)}var xJ,JF,In,$Ie,VIe,jIe,ZF,SJ,eq,PJ,q_,Gr,Tr,WIe,H_=L(()=>{"use strict";xJ={withStackTrace:!1},JF=(e,t,n=xJ)=>{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}};In=class e{constructor(t){this._promise=t}static fromSafePromise(t){let n=t.then(r=>new Gr(r));return new e(n)}static fromPromise(t,n){let r=t.then(o=>new Gr(o)).catch(o=>new Tr(n(o)));return new e(r)}static fromThrowable(t,n){return(...r)=>new e(kl(this,void 0,void 0,function*(){try{return new Gr(yield t(...r))}catch(o){return new Tr(n?n(o):o)}}))}static combine(t){return SJ(t)}static combineWithAllErrors(t){return PJ(t)}map(t){return new e(this._promise.then(n=>kl(this,void 0,void 0,function*(){return n.isErr()?new Tr(n.error):new Gr(yield t(n.value))})))}andThrough(t){return new e(this._promise.then(n=>kl(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 Gr(n.value)})))}andTee(t){return new e(this._promise.then(n=>kl(this,void 0,void 0,function*(){if(n.isErr())return new Tr(n.error);try{yield t(n.value)}catch{}return new Gr(n.value)})))}orTee(t){return new e(this._promise.then(n=>kl(this,void 0,void 0,function*(){if(n.isOk())return new Gr(n.value);try{yield t(n.error)}catch{}return new Tr(n.error)})))}mapErr(t){return new e(this._promise.then(n=>kl(this,void 0,void 0,function*(){return n.isOk()?new Gr(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=>kl(this,void 0,void 0,function*(){return n.isErr()?t(n.error):new Gr(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 XF(this,arguments,function*(){return yield ns(yield ns(yield*AJ(TJ(yield ns(this._promise.then(n=>n.safeUnwrap()))))))})}then(t,n){return this._promise.then(t,n)}[Symbol.asyncIterator](){return XF(this,arguments,function*(){let n=yield ns(this._promise);return n.isErr()&&(yield yield ns(xl(n.error))),yield ns(n.value)})}};$Ie=In.fromPromise,VIe=In.fromSafePromise,jIe=In.fromThrowable,ZF=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},SJ=e=>In.fromSafePromise(Promise.all(e)).andThen(ZF),eq=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},PJ=e=>In.fromSafePromise(Promise.all(e)).andThen(eq);(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 ZF(o)}e.combine=n;function r(o){return eq(o)}e.combineWithAllErrors=r})(q_||(q_={}));Gr=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 In.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 JF("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 xl(this.error)}asyncAndThrough(t){return xl(this.error)}asyncMap(t){return xl(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 JF("Called `_unsafeUnwrap` on an Err",this,t)}_unsafeUnwrapErr(t){return this.error}*[Symbol.iterator](){let t=this;return yield t,t}},WIe=q_.fromThrowable});function EJ(e){return e==null}function Kr(e){return!EJ(e)}function fe(e,t){if(!e)throw new rq(t)}function oq(e="Unexpected call to never()"){throw new rq(e)}function os(e){return new Promise(t=>setTimeout(t,e))}function sq(e){let t=e.unref;typeof t=="function"&&t.call(e)}function ud(e,t){let n=setInterval(e,t);return sq(n),n}function yn(e,t){let n=setTimeout(e,t);return sq(n),n}function ln(e){return typeof e=="string"&&/^0x[a-fA-F0-9]+$/.test(e)}function zt(e,t){return e.toLowerCase()===t.toLowerCase()}function $_(e){return ln(e)&&e.length===66}function Qs(e,t="Expected value to be present"){return fe(e!=null,t),e}function iq(e,t="Expected a non-empty array"){return fe(e.length>0,t),e}function Wn(e,t="Expected a hex string"){return fe(ln(e),t),e}function aq(e,t="Expected a private key"){return fe($_(e),t),e}function Be(e,t="Expected an EVM address"){return fe(ln(e)&&e.length===42,t),e}function ss(e,t="Expected an EVM signature"){return fe(ln(e)&&e.length===132,t),e}function lq(e,t="Expected an ERC-1271 signature payload"){return fe(ln(e),t),e}function cq(e,t="Expected a session-signer signature envelope"){return fe(ln(e),t),e}function tq(e){throw e}function X(e){return e instanceof In?e.match(t=>t,tq):e.match(t=>t,tq)}var rs,Ct,rq,Al=L(()=>{"use strict";H_();H_();rs="0x0000000000000000000000000000000000000000",Ct=class nq extends Error{static isError(t){return t instanceof nq}},rq=class extends Ct{name="InvariantError"}});function dd(e){if(!Number.isInteger(e))throw new TypeError(`Expected an integer, received: ${e}`);return e}function j_(e){return e}function xw(e){if(!ln(e)||e.length!==66)throw new TypeError(`Expected a 32-byte hex string, received: ${e}`);return e}function uq(e){return e}function dq(e){return e}function W_(e){return e}function pq(e){return e}function mq(e){return e}function hq(e){return e}function Oh(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 V_(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 z_(e){let t=V_(e);if(t!==void 0)return t;throw new TypeError(`Expected a protocol v2 combo condition ID, received: ${e}`)}function G_(e){return e}function K_(e){return e}function Y_(e){return dd(e)}function pd(e){return dd(e)}function Q_(e){return e}function fq(e){return e}function gq(e){return e}function yq(e){return e}function X_(e){return e}function bq(e){return e}function Aw(e){return e}function wq(e){return dd(e)}function vq(e){return e}function J_(e){return dd(e)}function Tw(e){return e}function kq(e){return IJ(e)}function md(e){return e}function Sw(e){return e}function xq(e){return e}function Z_(e){return e}function eI(e){return dd(e)}function Aq(e){return e}function tI(e){return dd(e)}function nI(e){return e}function Tq(e){return e}function Sq(e){return e}function Lh(e){return e}function Tl(e){return e}function Gn(e){return e===""?null:e}function gd(e){return e===""?void 0:e}function _J(e){return e}function IJ(e){if(!ln(e)||e.length!==66)throw new TypeError(`Expected a 32-byte hex string, received: ${e}`);return e}var ue,Ch,Ue,cn,Ki,yo,Nh,rI,is,bo,oI,Xs,sI,Zt,xe,Dh,J,pe,wo,Pw,Ew,Pr,hd,Yi,RJ,iI,un,Gt,Sl,re,zn,aI,lI,cI,Qi,uI,Js,fd,Nt,Uh,Bh,ye,Xe,Me,vo,dI,ar,Xi,Rw,Mh,_w,Ji,et,R,bn,H,ko,as,dn,xo=L(()=>{"use strict";Al();ue=require("zod"),Ch=(e=>(e.Event="Event",e.Series="Series",e))(Ch||{}),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||{}),Ki=(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))(Ki||{}),yo=(e=>(e.ALL="ALL",e.CLOB="CLOB",e.COMBOSRFQ="COMBOSRFQ",e))(yo||{}),Nh=ue.z.string().min(1).transform(e=>e);rI=ue.z.string().transform(dq),is=ue.z.string().transform(uq),bo=ue.z.string().transform(xw),oI=ue.z.string().transform(pq),Xs=ue.z.string().transform(mq),sI=ue.z.string().transform(hq),Zt=ue.z.string().refine(e=>V_(e)!==void 0,"Expected a protocol v2 combo condition ID").transform(e=>V_(e)),xe=ue.z.string().refine(e=>ln(e)&&(e.length===64||e.length===66),"Expected a 31-byte or 32-byte hex string").transform(e=>e),Dh=ue.z.custom(ln,"Expected a hex-encoded market condition ID"),J=ue.z.string().refine(e=>ln(e)&&e.length===42,"Expected an EVM address").transform(_J),pe=ue.z.number().int().transform(pd),wo=ue.z.number().int().transform(e=>pd(e*1e3)),Pw=ue.z.union([ue.z.number().int(),ue.z.string().regex(/^\d+$/).transform(Number)]),Ew=ue.z.string().transform(e=>/^\d{4}-\d{2}-\d{2}$/.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString():e),Pr=ue.z.string().regex(/^\d+$/).transform(e=>pd(Number(e))),hd=ue.z.union([Pw.transform(e=>new Date(e).toISOString()),Ew]),Yi=ue.z.union([Pw.transform(e=>new Date(e<1e12?e*1e3:e).toISOString()),Ew]),RJ=ue.z.union([Pw.transform(e=>e===0?void 0:new Date(e).toISOString()),Ew]),iI=ue.z.union([Pw.transform(e=>e===0?void 0:new Date(e<1e12?e*1e3:e).toISOString()),Ew]),un=hd,Gt=ue.z.union([ue.z.string(),ue.z.number().int().transform(String)]).transform(Q_),Sl=ue.z.union([ue.z.literal(.1),ue.z.literal(.01),ue.z.literal(.005),ue.z.literal(.0025),ue.z.literal(.001),ue.z.literal(1e-4)]),re=ue.z.string().transform(X_).or(ue.z.date().transform(e=>e.toISOString())),zn=ue.z.string().transform(yq).or(ue.z.date().transform(e=>e.toISOString().slice(0,10))),aI=ue.z.string().transform(bq),lI=ue.z.string().transform(fq),cI=ue.z.string().transform(gq),Qi=ue.z.string().transform(Aw),uI=ue.z.number().int().transform(wq),Js=ue.z.enum(Ch),fd=ue.z.string().transform(vq),Nt=ue.z.enum(Ue),Uh=ue.z.enum(cn),Bh=ue.z.preprocess(e=>typeof e!="string"||e.startsWith("TRADE_STATUS_")?e:Object.values(Ki).find(t=>t.slice(13)===e)??e,ue.z.enum(Ki)),ye=ue.z.custom(e=>typeof e=="string"&&e.length>0,"Expected a non-empty pagination cursor"),Xe=ue.z.string().transform(Tw),Me=ue.z.string().transform(e=>e),vo=ue.z.string().refine(e=>ln(e)&&e.length===66,"Expected a 32-byte hex string").transform(e=>e),dI=ue.z.string().transform(kq),ar=ue.z.string().transform(md),Xi=ue.z.string().transform(Sw),Rw=ue.z.string().transform(xq),Mh=ue.z.string().transform(Aq),_w=ue.z.string().transform(Sq),Ji=ue.z.string().min(1).transform(Tq),et=ue.z.string().refine(e=>ln(e)&&e.length===66,"Expected a transaction hash").transform(e=>e),R=ue.z.string().transform(Lh),bn=ue.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=ue.z.union([R,ue.z.number().transform(e=>String(e))]),ko=ue.z.union([ue.z.number(),ue.z.string().transform(Number)]).pipe(ue.z.number().positive()),as=ue.z.string().transform(Tl);dn=ue.z.preprocess(Gn,R.nullish())});function Ow(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:$J(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 Fh(e){return e??null}function Lw(e){return typeof e=="string"?JSON.parse(e):e}function qh(e){return e.outcomes.length===2}function $J(e){if(!qh(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 nZ(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,CJ,Zs,Pq,NJ,Eq,Pl,Rq,_q,pI,OJ,LJ,DJ,UJ,BJ,Iw,MJ,Zi,FJ,mI,qJ,Cw,Nw,Iq,HJ,hI,fI,VJ,jJ,WJ,zJ,GJ,KJ,Cq,Hh,YJ,QJ,XJ,JJ,Dw,Uw,Bw,Nq,Oq,Lq,Dq,Uq,$h,gI,yI,bI,wI,vI,ZJ,eZ,Bq,ei,tZ,kI,xI,Mq,El,AI,Fq,yd,Mw,Vh,jh,TI,Wh=L(()=>{"use strict";xo();b=require("zod"),CJ=b.z.preprocess(e=>e===""?void 0:e,Dh.optional()),Zs=b.z.object({id:lI,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:re.nullish(),relID:b.z.number().int().nullish(),field:b.z.string().nullish(),relname:b.z.string().nullish()}),Pq=b.z.object({exponent:b.z.number(),rate:H,takerOnly:b.z.boolean(),rebateRate:H}),NJ=b.z.object({id:Gt}),Eq=b.z.object({id:rI,label:b.z.string().nullish(),parentCategory:b.z.string().nullish(),slug:b.z.string().nullish(),publishedAt:re.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.nullish()}),Pl=b.z.object({id:Mh,label:b.z.string().nullish(),slug:b.z.string().nullish(),forceShow:b.z.boolean().nullish(),publishedAt:re.nullish(),createdBy:b.z.number().int().nullish(),updatedBy:b.z.number().int().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),forceHide:b.z.boolean().nullish(),isCarousel:b.z.boolean().nullish(),activeEventsCount:b.z.number().int().nullish()}),Rq=b.z.object({id:Qi,conditionId:CJ,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:re.nullish(),eventSlug:b.z.string().nullish()}),_q=b.z.object({id:oI,conditionId:Dh,assetAddress:b.z.string(),rewardsAmount:H,rewardsDailyRate:H,startDate:zn,endDate:zn.nullish()}),pI=b.z.object({id:cI,username:b.z.string().nullish()}),OJ=b.z.object({id:Gt,slug:b.z.string().nullish(),title:b.z.string().nullish()}),LJ=b.z.preprocess(Lw,b.z.array(b.z.string()).nullish()).transform(e=>e??[]),DJ=b.z.preprocess(Lw,b.z.array(R).nullish()).transform(e=>e??[]),UJ=b.z.preprocess(Lw,b.z.array(_w).nullish()).transform(e=>e??[]),BJ=b.z.preprocess(Lw,b.z.array(Xe).nullish()).transform(e=>e??[]),Iw=(e=>(e.Pending="pending",e.Enabled="enabled",e.Disabled="disabled",e))(Iw||{}),MJ=b.z.string().transform(e=>e),Zi=(e=>(e.V1="v1",e.V2="v2",e))(Zi||{}),FJ=b.z.enum(Zi),mI=(e=>(e.Disputed="disputed",e.Proposed="proposed",e.Requested="requested",e.Resolved="resolved",e.Settled="settled",e))(mI||{}),qJ=b.z.enum(mI),Cw=b.z.object({id:Qi,version:FJ.nullish(),question:b.z.string().nullish(),conditionId:b.z.preprocess(Gn,Dh.nullish()).transform(Fh),slug:b.z.string().nullish(),twitterCardImage:b.z.string().nullish(),resolutionSource:b.z.string().nullish(),endDate:re.nullish(),category:b.z.string().nullish(),liquidity:R.nullish(),sponsorName:b.z.string().nullish(),sponsorImage:b.z.string().nullish(),startDate:re.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:LJ,outcomePrices:DJ,volume:R.nullish(),active:b.z.boolean().nullish(),marketType:b.z.string().nullish(),formatType:b.z.string().nullish(),lowerBoundDate:zn.nullish(),upperBoundDate:zn.nullish(),closed:b.z.boolean().nullish(),createdBy:b.z.number().int().nullish(),updatedBy:b.z.number().int().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),closedTime:re.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:re.nullish(),twitterCardLastValidated:re.nullish(),archived:b.z.boolean().nullish(),resolvedBy:b.z.preprocess(Gn,J.nullish()).transform(Fh),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(Fh),umaEndDate:aI.nullish(),enableOrderBook:b.z.boolean().nullish(),orderPriceMinTickSize:Sl.nullish(),orderMinSize:H.nullish(),umaResolutionStatus:b.z.preprocess(Gn,qJ.nullish()).transform(Fh),curationOrder:b.z.number().int().nullish(),volumeNum:H.nullish(),liquidityNum:H.nullish(),endDateIso:zn.nullish(),startDateIso:zn.nullish(),umaEndDateIso:zn.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:re.nullish(),secondsDelay:b.z.number().int().nullish(),clobTokenIds:UJ,comboStatus:MJ.nullish(),positionIds:BJ,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,dI.nullish()).transform(Fh),notificationsEnabled:b.z.boolean().nullish(),score:b.z.number().int().nullish(),imageOptimized:Zs.nullish(),iconOptimized:Zs.nullish(),events:b.z.array(OJ).nullish(),categories:b.z.array(b.z.unknown()).nullish(),markets:b.z.array(Rq).nullish(),creator:b.z.string().nullish(),ready:b.z.boolean().nullish(),funded:b.z.boolean().nullish(),pastSlugs:b.z.string().nullish(),readyTimestamp:re.nullish(),fundedTimestamp:re.nullish(),acceptingOrdersTimestamp:re.nullish(),tags:b.z.array(Pl).nullish(),cyom:b.z.boolean().nullish(),competitive:b.z.number().nullish(),approved:b.z.boolean().nullish(),clobRewards:b.z.array(_q).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:re.nullish(),scheduledDeploymentTimestamp:re.nullish(),rfqEnabled:b.z.boolean().nullish(),eventStartTime:re.nullish(),internalUsers:b.z.array(pI).nullish(),holdingRewardsEnabled:b.z.boolean().nullish(),feesEnabled:b.z.boolean().nullish(),makerRebatesFeeShareBps:b.z.number().nullish(),feeType:b.z.string().nullish(),feeSchedule:Pq.nullish()}),Nw=Cw.transform((e,t)=>qh(e)?Ow(e):(t.addIssue({code:"custom",message:`Expected binary market outcomes, received ${e.outcomes.length}`}),b.z.NEVER)),Iq=Cw.transform(e=>qh(e)?Ow(e):null),HJ=b.z.array(Iq).transform(e=>e.filter(t=>t!==null)),hI=b.z.object({markets:b.z.array(Iq),next_cursor:ye.optional()}).transform(({markets:e,next_cursor:t})=>({items:e.filter(n=>n!==null),nextCursor:t})),fI=b.z.array(Pl);VJ=b.z.string().transform(j_),jJ=b.z.string().transform(W_),WJ=b.z.string().transform(G_),zJ=b.z.string().transform(K_),GJ=b.z.number().int().transform(Y_),KJ=b.z.union([Gt,b.z.number().int().transform(e=>String(e))]),Cq=b.z.number().int().transform(J_),Hh=b.z.union([b.z.string(),b.z.number().int().transform(String)]).transform(Z_),YJ=b.z.number().int().transform(eI),QJ=b.z.number().int().transform(tI),XJ=b.z.string().transform(nI),JJ=b.z.enum(Zi),Dw=b.z.object({id:WJ,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:re.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),disqusThread:b.z.string().nullish(),commentsEnabled:b.z.boolean().nullish()}),Uw=b.z.object({id:Hh,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:re.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),commentsEnabled:b.z.boolean().nullish(),competitive:b.z.string().nullish(),volume24hr:H.nullish(),volume:H.nullish(),liquidity:H.nullish(),startDate:re.nullish(),pythTokenID:b.z.string().nullish(),cgAssetName:b.z.string().nullish(),score:b.z.number().int().nullish(),commentCount:b.z.number().int().nullish()}),Bw=b.z.object({id:XJ,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:re.nullish(),updatedAt:re.nullish()}),Nq=b.z.object({id:jJ,channelId:b.z.string().nullish(),channelName:b.z.string().nullish(),channelImage:b.z.string().nullish(),live:b.z.boolean().nullish(),startTime:re.nullish(),endTime:re.nullish()}),Oq=b.z.object({id:zJ,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:re.nullish(),updatedAt:re.nullish()}),Lq=b.z.object({id:Cq,slug:b.z.string(),name:b.z.string(),createdAt:re.nullish(),updatedAt:re.nullish()}),Dq=b.z.object({id:GJ,eventId:KJ,partnerId:Cq,externalId:b.z.string(),partner:Lq.nullish(),createdAt:re.nullish(),updatedAt:re.nullish()}),Uq=b.z.object({id:VJ,lineType:b.z.string().nullish(),line:b.z.number().nullish()}),$h=(e=>(e.Home="home",e.Away="away",e))($h||{}),gI=b.z.object({id:QJ,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:re.nullish(),updatedAt:re.nullish(),providerId:b.z.number().int().nullish(),color:b.z.string().nullish(),ordering:b.z.enum($h).nullish()}),yI=b.z.object({id:YJ,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:re.nullish(),updatedAt:re.nullish()}),bI=b.z.array(gI),wI=b.z.array(yI),vI=b.z.object({marketTypes:b.z.array(b.z.string()).nullish()}),ZJ=Cw.transform(e=>qh(e)?Ow(e):null),eZ=b.z.array(ZJ).transform(e=>e.filter(t=>t!==null)),Bq=b.z.object({id:Gt,version:JJ.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:re.nullish(),creationDate:re.nullish(),endDate:re.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:re.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.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:eZ.nullish(),series:b.z.array(Uw).nullish(),categories:b.z.array(Eq).nullish(),collections:b.z.array(Dw).nullish(),tags:b.z.array(Pl).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:re.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:zn.nullish(),startTime:re.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:re.nullish(),gmpChartMode:b.z.string().nullish(),eventCreators:b.z.array(Oq).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(Nq).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(Bw).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:re.nullish(),scheduledDeploymentTimestamp:re.nullish(),gameStatus:b.z.string().nullish(),internalUsers:b.z.array(pI).nullish(),gameId:b.z.number().int().nullish(),rescheduledFromGameId:b.z.number().int().nullish(),sportsradarMatchId:b.z.string().nullish(),bestLines:b.z.array(Uq).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:re.nullish(),eventMetadata:b.z.record(b.z.string(),b.z.unknown()).nullish(),teams:b.z.array(gI).nullish(),sport:yI.nullish(),externalPartners:b.z.array(Dq).nullish()}),ei=Bq.transform(nZ),tZ=b.z.array(ei),kI=b.z.object({events:b.z.array(ei),next_cursor:ye.optional()}).transform(({events:e,next_cursor:t})=>({items:e,nextCursor:t})),xI=b.z.array(Pl);Mq=b.z.object({tokenId:_w.nullish(),positionSize:as.nullish()}),El=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(Mq).nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),AI=(e=>(e.Heart="HEART",e))(AI||{}),Fq=b.z.enum(AI),yd=b.z.object({id:b.z.string(),commentID:b.z.number().int().nullish(),reactionType:Fq.nullish(),icon:b.z.string().nullish(),userAddress:b.z.string().nullish(),createdAt:re.nullish(),profile:El.nullish()}),Mw=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:re.nullish()}),Vh=b.z.object({id:Xs,body:b.z.string().nullish(),parentEntityType:Js.nullish(),parentEntityID:b.z.union([Gt,Hh]).nullish(),parentCommentID:Xs.nullish(),userAddress:b.z.string().nullish(),replyAddress:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),media:b.z.array(Mw).nullish(),profile:El.nullish(),reactions:b.z.array(yd).nullish(),reportCount:b.z.number().int().nullish(),reactionCount:b.z.number().int().nullish(),tradeAsset:b.z.string().nullish()}),jh=b.z.array(Vh),TI=b.z.object({comments:b.z.array(Vh),next_cursor:ye.optional()}).transform(({comments:e,next_cursor:t})=>({items:e,nextCursor:t}))});function Rl(e){return e}function vH(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 AH(e){return e??"Perps command was rejected."}var P,Ae,Cn,Er,_l,qq,ea,SI,Fw,PI,Hq,$q,Ao,Gh,Kh,Yh,ti,ta,vd,Qh,qw,Hw,Xh,Jh,EI,Zh,RI,ef,ni,_I,Vq,jq,kd,xd,Wq,zq,$w,Vw,II,Kn,Il,To,jw,CI,Gq,NI,Kq,rZ,oZ,Ww,OI,Yq,LI,DI,Qq,UI,Xq,BI,Jq,MI,sZ,Zq,FI,qI,HI,Yr,wd,Ad,tf,zw,$I,nf,Gw,VI,iZ,jI,eH,WI,tH,zI,GI,nH,KI,YI,QI,rH,XI,JI,aZ,lZ,oH,ZI,sH,eC,tC,Td,iH,nC,rC,zh,oC,sC,cZ,iC,aH,aC,lC,lH,cC,cH,uH,dH,uC,dC,rf,pH,of,pC,sf,mH,hH,fH,gH,uZ,dZ,yH,bH,Kw,wH,pZ,mZ,mC,hC,fC,bd,af,gC,yC,kH,Sd,xH,hZ,lf,cf,Yw,bC,wC,vC,kC,xC,AC,TH,TC,SC,PC=L(()=>{"use strict";xo();P=require("zod");Ae=P.z.number().int().nonnegative().transform(Rl),Cn=P.z.number().int().nonnegative().transform(Rl),Er=P.z.string().regex(/^[0-9a-f]{32}$/).transform(e=>e),_l=P.z.uuid().transform(e=>e),qq=P.z.string().min(1).transform(e=>e),ea=P.z.number().int().nonnegative().transform(Rl),SI=P.z.number().int().nonnegative().transform(Rl),Fw=P.z.number().int().nonnegative().transform(Rl),PI=P.z.number().int().nonnegative().transform(Rl),Hq=P.z.number().int().positive().transform(Rl),$q=P.z.string().regex(/^[1-9]\d*h$/).transform(e=>e),Ao=H,Gh=(e=>(e.Perpetual="perpetual",e))(Gh||{}),Kh=(e=>(e.Equity="equity",e.Commodity="commodity",e.Index="index",e.Crypto="crypto",e))(Kh||{}),Yh=(e=>(e.Long="long",e.Short="short",e))(Yh||{}),ti=(e=>(e.GTC="gtc",e.IOC="ioc",e.FOK="fok",e))(ti||{}),ta=(e=>(e.TakeProfit="tp",e.StopLoss="sl",e))(ta||{}),vd=(e=>(e.Order="order",e.Position="position",e))(vd||{}),Qh=(e=>(e.Pending="pending",e.Confirmed="confirmed",e.Removed="removed",e))(Qh||{}),qw=(e=>(e.Pending="pending",e.Confirmed="confirmed",e.Removed="removed",e.Failed="failed",e))(qw||{}),Hw=(e=>(e.Transfer="transfer",e.ReferralPayout="referral_payout",e))(Hw||{}),Xh=(e=>(e.In="in",e.Out="out",e))(Xh||{}),Jh=(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))(Jh||{}),EI=(e=>(e.OneHour="1h",e.FourHours="4h",e.OneDay="1d",e.OneWeek="1w",e))(EI||{}),Zh=(e=>(e.Descending="desc",e.Ascending="asc",e))(Zh||{}),RI=P.z.enum(Gh),ef=P.z.enum(Kh),ni=P.z.enum(Yh),_I=P.z.enum(ti),Vq=P.z.enum(ta),jq=P.z.enum(vd),kd=P.z.enum(Qh),xd=P.z.string().transform(e=>e),Wq=P.z.string().min(1).transform(e=>e),zq=P.z.enum(Xh),$w=P.z.enum(Jh),Vw=P.z.enum(EI),II=P.z.enum(Zh),Kn=P.z.string().min(1),Il=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()}),jw=P.z.object({asset:Kn,balance:R,value:R}),CI=P.z.array(jw),Gq=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:Hq.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})),NI=Gq,Kq=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})),rZ=P.z.object({totalAccountValue:R,totalInitialMargin:R,totalMaintenanceMargin:R,totalPositionValue:R}),oZ=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})),Ww=P.z.object({positions:P.z.array(Kq),margin:oZ,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})),OI=Ww,Yq=P.z.object({id:SI,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})),LI=To(Yq),DI=P.z.object({id:SI,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})),Qq=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})),UI=P.z.array(Qq),Xq=P.z.tuple([pe,R]).transform(([e,t])=>({timestamp:e,equity:t})),BI=To(Xq),Jq=P.z.tuple([pe,R]).transform(([e,t])=>({timestamp:e,pnl:t})),MI=To(Jq),sZ=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),Zq=P.z.object({proxy:J,label:P.z.string().optional(),expiry:sZ}).transform(e=>({proxy:e.proxy,label:e.label,expiresAt:e.expiry})),FI=P.z.object({address:J,keys:P.z.array(Zq)}).transform(e=>({address:e.address,keys:e.keys})),qI=P.z.object({secret:P.z.string().min(1)}),HI=P.z.object({status:P.z.enum(["ok","err"]),error:P.z.string().optional()}),Yr=P.z.string().regex(/^-?\d+(?:\.\d+)?$/).pipe(R),wd=P.z.number().int().nonnegative(),Ad=P.z.object({address:J,fee_rate:Yr}).transform(e=>({address:e.address,feeRate:e.fee_rate})),tf=P.z.object({address:J,registered:P.z.boolean(),enabled:P.z.boolean(),admission_enabled:P.z.boolean(),max_fee_rate:Yr}).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:Yr,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})),$I=P.z.object({data:P.z.array(zw)}),nf=(e=>(e.Maker="maker",e.Taker="taker",e))(nf||{}),Gw=P.z.object({earning_id:qq,trade_id:ea,order_id:Cn,instrument_id:Ae,trader:J,buy:P.z.boolean(),price:Yr,quantity:Yr,client_order_id:Er.optional(),side:P.z.enum(nf),timestamp:pe,sequence:wd,notional:Yr,fee_asset:Kn,fee:Yr,builder_fee:Yr,total_fee:Yr,fee_rate:Yr}).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})),VI=P.z.object({start_timestamp:pe,end_timestamp:pe,as_of_sequence:wd}),iZ=VI.transform(e=>({start:e.start_timestamp,end:e.end_timestamp,asOfSequence:e.as_of_sequence})),jI=VI.extend({data:P.z.array(Gw),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}})),eH=P.z.object({fee_asset:Kn,fill_count:wd,notional:Yr,builder_fee:Yr}).transform(e=>({feeAsset:e.fee_asset,fillCount:e.fill_count,notional:e.notional,builderFee:e.builder_fee})),WI=VI.extend({data:P.z.array(eH),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}})),tH=P.z.object({hash:et,asset:Kn,amount:as,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})),zI=To(tH),GI=P.z.object({hash:Il,asset:Kn,amount:as,status:kd}).transform(e=>({hash:e.hash,asset:e.asset,amount:e.amount,status:e.status})),nH=P.z.object({withdraw_id:Fw,asset:Kn,amount:as,fee:R,status:xd,to:J,hash:Il,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})),KI=To(nH),YI=P.z.object({status:P.z.enum(["ok","err"]),withdraw_id:Fw.optional(),error:P.z.string().optional()}).transform(e=>({status:e.status,withdrawalId:e.withdraw_id,error:e.error})),QI=P.z.object({withdraw_id:Fw,asset:Kn,amount:as,fee:R,status:xd,to:J,hash:Il}).transform(e=>({withdrawalId:e.withdraw_id,asset:e.asset,amount:e.amount,fee:e.fee,status:e.status,to:e.to,hash:e.hash})),rH=P.z.object({transfer_id:PI,type:Wq,asset:Kn,amount:R,direction:zq,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})),XI=To(rH),JI=P.z.strictObject({status:P.z.literal("ok"),transfer_id:PI}).transform(e=>({status:e.status,transferId:e.transfer_id})),aZ=P.z.object({lowerBound:R,maxLeverage:P.z.number().int().positive()}),lZ=P.z.object({lower_bound:R,max_leverage:P.z.number().int().positive()}).transform(e=>({lowerBound:e.lower_bound,maxLeverage:e.max_leverage})),oH=P.z.object({instrument_id:Ae,instrument_type:RI,category:ef,symbol:P.z.string().min(1),base_asset:Kn,quote_asset:Kn,funding_interval:$q,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(lZ)}).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})),ZI=P.z.array(oH),sH=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})),eC=P.z.array(sH),tC=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})),iH=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})),nC=P.z.array(iH),rC=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})),zh=P.z.tuple([R,R]).transform(([e,t])=>({price:e,quantity:t})),oC=P.z.object({instrument_id:Ae,bids:P.z.array(zh),asks:P.z.array(zh),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})),sC=P.z.object({b:P.z.array(zh),a:P.z.array(zh)}).transform(e=>({bids:e.b,asks:e.a})),cZ=P.z.object({instrumentId:Ae,bidPrice:R,bidQuantity:R,askPrice:R,askQuantity:R,timestamp:pe.optional()}),iC=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})),aH=P.z.object({trade_id:ea,instrument_id:Ae,side:ni,price:R,quantity:R,timestamp:pe,hash:Il}).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})),aC=P.z.object({tid:ea,iid:Ae,side:ni,p:R,qty:R,ts:pe,hash:Il}).transform(e=>({tradeId:e.tid,instrumentId:e.iid,side:e.side,price:e.p,quantity:e.qty,timestamp:e.ts,hash:e.hash})),lC=To(aH),lH=P.z.object({funding_rate:R,timestamp:pe}).transform(e=>({fundingRate:e.funding_rate,timestamp:e.timestamp})),cC=To(lH),cH=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})),uH=P.z.object({instrument_type:RI,category:ef,taker_fee_rate:R,maker_fee_rate:R,tiers:P.z.array(cH)}).transform(e=>({category:e.category,takerFeeRate:e.taker_fee_rate,makerFeeRate:e.maker_fee_rate,tiers:e.tiers})),dH=P.z.object({fee_schedule:P.z.array(uH)}).transform(e=>({feeSchedule:e.fee_schedule})),uC=dH,dC=To(Td),rf=(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))(rf||{}),pH=P.z.enum(rf),of=(e=>(e.Market="market",e.Limit="limit",e.TakeProfit="take_profit",e.StopLoss="stop_loss",e))(of||{}),pC=P.z.enum(of),sf=(e=>(e.Cross="cross",e.Isolated="isolated",e))(sf||{}),mH=P.z.enum(sf),hH=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:pC.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})),fH=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:pC.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})),gH=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})),uZ=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})),dZ=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})),yH=P.z.discriminatedUnion("margin_type",[uZ,dZ]),bH=P.z.object({id:_l,type:P.z.literal("position_liquidated"),instrument_id:Ae,side:ni,size_closed:R,pnl:R.nullable(),margin_type:mH,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})),Kw=P.z.discriminatedUnion("type",[hH,fH,gH,yH,bH]),wH=P.z.object({notification:Kw,read_at:pe.nullable(),ts:pe}).transform(e=>({notification:e.notification,readAt:e.read_at,timestamp:e.ts})),pZ=P.z.object({notification:P.z.object({type:pH})}),mZ=P.z.array(P.z.unknown()).transform((e,t)=>{let n=[];return e.forEach((r,o)=>{if(!pZ.safeParse(r).success)return;let s=wH.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}),mC=P.z.object({items:mZ,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()}),hC=P.z.object({unread:P.z.number().int().nonnegative()}),fC=P.z.object({status:P.z.enum(["ok","err"]),error:P.z.string().optional()}),bd=P.z.string().regex(/^-?\d+(?:\.\d+)?$/).pipe(R);af=(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))(af||{}),gC=P.z.object({kind:Vq,scope:jq,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})),yC=P.z.enum(af),kH=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||{}),xH=P.z.string().min(1).transform(e=>e),hZ=P.z.string().min(1).optional().transform(AH),lf=P.z.discriminatedUnion("status",[P.z.object({status:P.z.literal("ok")}),P.z.object({status:P.z.literal("err"),error:hZ})]),cf=P.z.object({status:kH,oid:Cn.optional(),coid:Er.optional(),error:P.z.string().optional(),builder:Ad.optional()}).transform((e,t)=>e.status==="err"?{status:"err",error:AH(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}}),Yw=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:xH,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}),bC=P.z.object({status:P.z.literal("ok")}),wC=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}));vC=P.z.object({order_id:Cn,instrument_id:Ae,buy:P.z.boolean(),price:R,quantity:R,tif:_I,post_only:P.z.boolean(),ro:P.z.boolean(),status:yC,resting_quantity:R,filled_quantity:R,created_timestamp:pe,updated_timestamp:pe,client_order_id:P.z.string().optional(),tpsl:gC.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}})),kC=P.z.array(vC),xC=P.z.array(vC),AC=P.z.object({oid:Cn,iid:Ae,buy:P.z.boolean(),p:R,qty:R,tif:_I,po:P.z.boolean(),ro:P.z.boolean(),status:yC,rest:R,fill:R,cts:pe,uts:pe,coid:P.z.string().optional(),tpsl:gC.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}})),TH=P.z.object({trade_id:ea,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:Il}).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??vH(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})),TC=To(TH),SC=P.z.object({tid:ea,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??vH(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 na(e,t,n){return UZ.extend({ch:S.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 VH(e){let[,t]=e.split("::");return Ae.parse(Number(t))}function KZ(e){let[,,t]=e.split("::");return t}function KH(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 JZ.safeParse({...t,topic:"prices.crypto"}).data;case"price.crypto.twap":return ZZ.safeParse({...t,topic:"prices.crypto.twap"}).data;case"price.equity":return eee.safeParse({...t,topic:"prices.equity"}).data}}function bee(e){let t=BigInt(e),n=t<0n,r=n?-t:t,o=r/PH,s=(r%PH).toString().padStart(18,"0").replace(/0+$/,"");return`${n?"-":""}${o}${s===""?"":`.${s}`}`}function XH(e){return vee.extend({window_s:S.z.literal(e)}).transform(t=>({symbol:t.symbol,timestamp:t.timestamp,value:t.full_accuracy_value,windowSeconds:t.window_s}))}var S,uf,EH,fZ,SH,Qw,gZ,RH,yZ,_H,IH,CH,NH,OH,LH,DH,UH,bZ,wZ,vZ,kZ,iCe,aCe,BH,MH,FH,xZ,AZ,TZ,SZ,PZ,EZ,RZ,_Z,ri,IZ,CZ,NZ,OZ,LZ,DZ,qH,UZ,BZ,MZ,FZ,qZ,HZ,$Z,VZ,jZ,WZ,HH,zZ,GZ,$H,Ed,Rd,Cl,jH,WH,YZ,zH,EC,GH,QZ,XZ,Pd,JZ,ZZ,eee,tee,nee,ree,oee,see,YH,iee,aee,QH,lee,cee,uee,dee,pee,mee,hee,fee,gee,yee,PH,wee,vee,JH,ZH,lCe,kee,xee,Aee,Tee,See,Pee,e3,Eee,Ree,_ee,Iee,t3,Cee,n3,Xw=L(()=>{"use strict";Wh();PC();xo();S=require("zod"),uf=S.z.preprocess(e=>typeof e=="string"?e.toUpperCase():e,Nt),EH=(e=>(e.Live="LIVE",e.Matched="MATCHED",e.Delayed="DELAYED",e.Unmatched="UNMATCHED",e.Canceled="CANCELED",e))(EH||{}),fZ=S.z.enum(EH),SH=S.z.object({price:R,size:R}),Qw=S.z.string().regex(/^\d+$/).transform(e=>new Date(Number(e)*1e3).toISOString()),gZ=S.z.string().regex(/^\d+$/).transform(e=>e==="0"?void 0:new Date(Number(e)*1e3).toISOString()),RH=S.z.object({event_type:S.z.literal("book"),market:xe,asset_id:Me,bids:S.z.array(SH),asks:S.z.array(SH),hash:S.z.string().nullish(),timestamp:Pr.nullish(),min_order_size:dn,tick_size:dn,neg_risk:S.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}})),yZ=S.z.object({asset_id:Me,price:R,size:R,side:uf,hash:S.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})),_H=S.z.object({event_type:S.z.literal("price_change"),market:xe,price_changes:S.z.array(yZ),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}})),IH=S.z.object({event_type:S.z.literal("last_trade_price"),market:xe,asset_id:Me,price:R,size:dn,fee_rate_bps:dn,side:uf,timestamp:Pr.nullish(),transaction_hash:S.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}})),CH=S.z.object({event_type:S.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}})),NH=S.z.object({event_type:S.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}})),OH=S.z.object({id:S.z.string(),ticker:S.z.string().nullish(),slug:S.z.string().nullish(),title:S.z.string().nullish(),description:S.z.string().nullish()}),LH=S.z.object({event_type:S.z.literal("new_market"),id:S.z.string(),question:S.z.string().nullish(),market:S.z.string(),slug:S.z.string().nullish(),description:S.z.string().nullish(),assets_ids:S.z.array(Me).nullish(),outcomes:S.z.array(S.z.string()).nullish(),event_message:OH.nullish(),timestamp:Pr.nullish(),tags:S.z.array(S.z.string()).nullish(),condition_id:xe.nullish(),active:S.z.boolean().nullish(),clob_token_ids:S.z.array(S.z.string()).nullish(),sports_market_type:S.z.string().nullish(),line:dn,game_start_time:un.nullish(),order_price_min_tick_size:dn,group_item_title:S.z.string().nullish(),taker_base_fee:dn,fees_enabled:S.z.boolean().nullish(),fee_schedule:S.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}})),DH=S.z.object({event_type:S.z.literal("market_resolved"),id:S.z.string(),market:xe,assets_ids:S.z.array(Me).nullish(),winning_asset_id:Me.nullish(),winning_outcome:S.z.string().nullish(),event_message:OH.nullish(),timestamp:Pr.nullish(),tags:S.z.array(S.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}})),UH=(e=>(e.Placement="PLACEMENT",e.Update="UPDATE",e.Cancellation="CANCELLATION",e))(UH||{}),bZ=S.z.enum(UH),wZ=S.z.object({event_type:S.z.literal("order"),id:S.z.string(),owner:S.z.string(),market:xe,asset_id:Me,side:uf,order_owner:S.z.string().nullish(),original_size:R,size_matched:R,price:R,associate_trades:S.z.array(S.z.string()).nullish(),outcome:S.z.string().nullish(),type:bZ,created_at:Qw.nullish(),expiration:gZ.nullish(),order_type:Uh.nullish(),status:fZ.nullish(),maker_address:S.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}})),vZ=S.z.object({order_id:S.z.string(),owner:S.z.string(),maker_address:S.z.string().nullish(),matched_amount:R,price:R,fee_rate_bps:dn,asset_id:Me,outcome:S.z.string().nullish(),outcome_index:S.z.number().int().nullish(),side:uf}).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})),kZ=S.z.object({event_type:S.z.literal("trade"),type:S.z.literal("TRADE"),id:S.z.string(),taker_order_id:S.z.string(),market:xe,asset_id:Me,side:uf,size:R,fee_rate_bps:dn,price:R,status:Bh,match_time:Qw.nullish(),matchtime:Qw.nullish(),last_update:Qw.nullish(),outcome:S.z.string().nullish(),owner:S.z.string(),trade_owner:S.z.string().nullish(),maker_address:S.z.string().nullish(),transaction_hash:S.z.string().nullish(),bucket_index:S.z.number().int().nullish(),maker_orders:S.z.array(vZ).nullish(),trader_side:S.z.union([S.z.literal("TAKER"),S.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}})),iCe=S.z.discriminatedUnion("event_type",[RH,_H,IH,CH]),aCe=S.z.discriminatedUnion("event_type",[NH,LH,DH]),BH=S.z.discriminatedUnion("event_type",[RH,_H,IH,CH,NH,LH,DH]),MH=S.z.discriminatedUnion("event_type",[wZ,kZ]),FH=S.z.number().int().nonnegative(),xZ=S.z.string().regex(/^trades::\d+$/),AZ=S.z.string().regex(/^bbo::\d+$/),TZ=S.z.string().regex(/^book::\d+$/),SZ=S.z.string().regex(/^tickers::(all|\d+)$/),PZ=S.z.string().regex(/^statistics::(all|\d+)$/),EZ=S.z.string().regex(/^klines::\d+::(1m|5m|15m|1h|4h|1d|1w)$/),RZ=S.z.string().regex(/^tpsl::\d+$/),_Z=S.z.enum(["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications"]),ri=S.z.object({ts:pe,sq:FH}),IZ=ri.extend({ch:xZ,data:S.z.array(aC)}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.trades",type:"trade",channel:e,timestamp:t,sequence:n,payload:r})),CZ=ri.extend({ch:AZ,data:iC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.bbo",type:"bbo",channel:e,timestamp:t,sequence:n,payload:r})),NZ=ri.extend({ch:TZ,data:sC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.book",type:"book",channel:e,timestamp:t,sequence:n,payload:{instrumentId:VH(e),...r}})),OZ=ri.extend({ch:SZ,data:tC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.tickers",type:"ticker",channel:e,timestamp:t,sequence:n,payload:r})),LZ=ri.extend({ch:PZ,data:rC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.statistics",type:"statistic",channel:e,timestamp:t,sequence:n,payload:r})),DZ=ri.extend({ch:EZ,data:S.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:VH(e),interval:KZ(e),candles:r}})),qH=S.z.union([IZ,CZ,NZ,OZ,LZ,DZ]),UZ=ri.extend({ch:_Z});BZ=na("balance","balances",jw),MZ=na("portfolio","portfolio",Ww),FZ=na("order","orders",AC),qZ=na("fill","fills",S.z.array(SC)),HZ=ri.extend({ch:S.z.literal("builderFills"),data:S.z.array(Gw)}).transform(({ch:e,ts:t,sq:n,data:r})=>({type:"builderFill",channel:e,timestamp:t,sequence:n,payload:r})),$Z=na("funding","funding",DI),VZ=na("deposit","deposits",GI),jZ=na("withdrawal","withdrawals",QI),WZ=na("notification","notifications",Kw),HH=S.z.object({ch:S.z.literal("notifications"),ts:pe,sq:FH,type:S.z.literal("resync")}).transform(({ch:e,ts:t,sq:n})=>({type:"resync",channel:e,timestamp:t,sequence:n})),zZ=S.z.object({oid:Cn,st:S.z.enum(["untriggered","armed","cancelled","expired"]),reason:S.z.string().optional()}),GZ=ri.extend({ch:RZ,data:zZ.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})),$H=S.z.union([BZ,MZ,FZ,qZ,HZ,$Z,VZ,jZ,WZ,GZ]);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||{}),Cl=(e=>(e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.Pong="pong",e.Authed="authed",e.Error="error",e))(Cl||{}),jH=S.z.object({op:S.z.enum(Cl),channel:S.z.string().optional(),rid:S.z.string().optional(),code:S.z.string().transform(e=>e).optional()}),WH=S.z.object({v:S.z.literal(1),channel:S.z.enum(Rd),seq:S.z.number().int().nonnegative(),ts:pe,snapshot:S.z.boolean().optional(),dropped:S.z.number().int().nonnegative().optional(),payload:S.z.unknown()}),YZ=S.z.object({timestamp:pe,value:H,full_accuracy_value:R}).transform(({timestamp:e,full_accuracy_value:t})=>({timestamp:e,value:t})),zH=S.z.object({symbol:S.z.string(),timestamp:pe,value:H,full_accuracy_value:R,received_at:pe.optional(),is_carried_forward:S.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})),EC=S.z.object({symbol:S.z.string(),data:S.z.array(YZ)}),GH=S.z.literal(60),QZ=S.z.object({symbol:S.z.string(),timestamp:pe,value:H,full_accuracy_value:R,window_seconds:GH}).transform(({symbol:e,timestamp:t,full_accuracy_value:n,window_seconds:r})=>({symbol:e,timestamp:t,value:n,windowSeconds:r})),XZ=EC.extend({window_seconds:GH}).transform(({symbol:e,data:t,window_seconds:n})=>({symbol:e,data:t,windowSeconds:n})),Pd=S.z.object({timestamp:pe,seq:S.z.number().optional(),dropped:S.z.number().optional()}),JZ=S.z.union([Pd.extend({topic:S.z.literal("prices.crypto"),type:S.z.literal("update"),payload:zH}),Pd.extend({topic:S.z.literal("prices.crypto"),type:S.z.literal("subscribe"),payload:EC})]),ZZ=S.z.union([Pd.extend({topic:S.z.literal("prices.crypto.twap"),type:S.z.literal("update"),payload:QZ}),Pd.extend({topic:S.z.literal("prices.crypto.twap"),type:S.z.literal("subscribe"),payload:XZ})]),eee=S.z.union([Pd.extend({topic:S.z.literal("prices.equity"),type:S.z.literal("update"),payload:zH}),Pd.extend({topic:S.z.literal("prices.equity"),type:S.z.literal("subscribe"),payload:EC})]);tee=S.z.object({id:S.z.string(),body:S.z.string().nullish(),parentEntityType:Js.nullish(),parentEntityID:S.z.number().int().nullish(),parentCommentID:S.z.string().nullish(),userAddress:S.z.string().nullish(),replyAddress:S.z.string().nullish(),createdAt:S.z.string().nullish(),updatedAt:S.z.string().nullish(),media:S.z.array(Mw).nullish(),profile:El.nullish(),reactions:S.z.array(yd).nullish(),reportCount:S.z.number().int().nullish(),reactionCount:S.z.number().int().nullish(),tradeAsset:S.z.string().nullish()}),nee=S.z.object({topic:S.z.literal("comments"),type:S.z.literal("comment_created"),timestamp:pe,payload:Vh}),ree=S.z.object({topic:S.z.literal("comments"),type:S.z.literal("comment_removed"),timestamp:pe,payload:tee}),oee=S.z.object({topic:S.z.literal("comments"),type:S.z.literal("reaction_created"),timestamp:pe,payload:yd}),see=S.z.object({topic:S.z.literal("comments"),type:S.z.literal("reaction_removed"),timestamp:pe,payload:yd}),YH=S.z.object({symbol:S.z.string(),timestamp:pe,value:H}),iee="prices.crypto.binance",aee="prices.crypto.chainlink",QH="prices.crypto.chainlink.twap",lee=S.z.literal("crypto_prices"),cee=S.z.literal("crypto_prices_chainlink"),uee=S.z.literal("crypto_prices_twap_thirty"),dee=S.z.literal("crypto_prices_twap_sixty"),pee=lee.transform(()=>iee),mee=cee.transform(()=>aee),hee=uee.transform(()=>QH),fee=dee.transform(()=>QH),gee=S.z.object({topic:pee,type:S.z.literal("update"),timestamp:pe,payload:YH}),yee=S.z.object({topic:mee,type:S.z.literal("update"),timestamp:pe,payload:YH}),PH=1000000000000000000n;wee=S.z.string().regex(/^-?\d+$/).transform(bee),vee=S.z.object({symbol:S.z.string(),value:H,full_accuracy_value:wee,timestamp:pe});JH=S.z.object({topic:hee,type:S.z.literal("update"),timestamp:pe,payload:XH(30)}),ZH=S.z.object({topic:fee,type:S.z.literal("update"),timestamp:pe,payload:XH(60)}),lCe=S.z.union([JH,ZH]),kee=S.z.discriminatedUnion("topic",[gee,yee,JH,ZH]),xee=S.z.object({symbol:S.z.string(),value:H,full_accuracy_value:R.nullish(),timestamp:pe,received_at:pe.nullish(),is_carried_forward:S.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})),Aee=S.z.object({timestamp:S.z.number(),value:H}),Tee=S.z.object({symbol:S.z.string(),data:S.z.array(Aee)}),See=S.z.literal("equity_prices"),Pee="prices.equity.pyth",e3=See.transform(()=>Pee),Eee=S.z.object({topic:e3,type:S.z.literal("update"),timestamp:pe,payload:xee}),Ree=S.z.object({topic:e3,type:S.z.literal("subscribe"),timestamp:pe,payload:Tee}),_ee=S.z.discriminatedUnion("type",[Eee,Ree]),Iee=S.z.discriminatedUnion("type",[nee,ree,oee,see]),t3=S.z.discriminatedUnion("topic",[Iee,kee,_ee]),Cee=S.z.object({gameId:S.z.number().int(),sportradarGameId:S.z.string().nullish(),slug:S.z.string().nullish(),leagueAbbreviation:S.z.string(),homeTeam:S.z.string().nullish(),awayTeam:S.z.string().nullish(),status:S.z.string(),live:S.z.boolean(),ended:S.z.boolean(),score:S.z.string(),period:S.z.string().nullish(),elapsed:S.z.string().nullish(),finishedTimestamp:un.nullish(),finished_timestamp:un.nullish(),turn:S.z.string().nullish()}).transform(({finishedTimestamp:e,finished_timestamp:t,...n})=>({...n,finishedAt:e??t})),n3=Cee.transform(e=>({topic:"sports",type:"sport_result",payload:e}))});function Oee(e){let t=o3(e.issues);return t.length===0?"It was not possible to determine a more specific reason.":["Fix the following issues:",r3(t)].join(`
|
|
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 zU(this,t)}};Object.defineProperty(le,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${jU()}`}});le.setStaticOptions(le.defaultStaticOptions)});function Mu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function pE(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 Zm(e){let t=e.toString(16);return t.length&1?"0"+t:t}function YU(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?dE:BigInt("0x"+e)}function qu(e){if(pE(e),QU)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=p9[e[n]];return t}function GU(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 eh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(QU)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=GU(e.charCodeAt(s)),a=GU(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 YU(qu(e))}function mE(e){return pE(e),YU(qu(Uint8Array.from(e).reverse()))}function tl(e,t){return eh(e.toString(16).padStart(t*2,"0"))}function hE(e,t){return tl(e,t).reverse()}function or(e,t,n){let r;if(typeof t=="string")try{r=eh(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 th(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];pE(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 ub(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 db(e,t,n){return lE(e)&&lE(t)&&lE(n)&&t<=e&&e<n}function nl(e,t,n,r){if(!db(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function XU(e){let t;for(t=0;e>dE;e>>=uE,t+=1);return t}function JU(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=cE(e),o=cE(e),s=0,i=()=>{r.fill(1),o.fill(0),s=0},a=(...d)=>n(o,r,...d),l=(d=cE(0))=>{o=a(KU([0]),d),r=a(),d.length!==0&&(o=a(KU([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 th(...p)};return(d,p)=>{i(),l(d);let m;for(;!(m=p(c()));)l();return i(),m}}function ol(e,t,n={}){let r=(o,s,i)=>{let a=m9[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 fE(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 dE,uE,QU,p9,Fs,lE,rl,cE,KU,m9,Hu=L(()=>{"use strict";dE=BigInt(0),uE=BigInt(1);QU=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",p9=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};lE=e=>typeof e=="bigint"&&dE<=e;rl=e=>(uE<<BigInt(e))-uE,cE=e=>new Uint8Array(e),KU=e=>Uint8Array.from(e);m9={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 nh({givenSize:wr(e),maxSize:t})}function ZU(e,t){if(typeof t=="number"&&t>0&&t>wr(e)-1)throw new $u({offset:t,position:"start",size:wr(e)})}function eB(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 gE(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 yE(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new rh({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 bE(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,wE=L(()=>{"use strict";Xt();Hs={zero:48,nine:57,A:65,F:70,a:97,f:102}});function sl(e,t){if(rt(e)>t)throw new oh({givenSize:rt(e),maxSize:t})}function nB(e,t){if(typeof t=="number"&&t>0&&t>rt(e)-1)throw new Vu({offset:t,position:"start",size:rt(e)})}function rB(e,t,n){if(typeof t=="number"&&typeof n=="number"&&rt(e)!==n-t)throw new Vu({offset:n,position:"end",size:rt(e)})}function vE(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 sh({size:Math.ceil(o.length/2),targetSize:r,type:"Hex"});return`0x${o[n==="right"?"padEnd":"padStart"](r*2,"0")}`}function kE(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 xE=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()+h9:o,n)}var h9,il=L(()=>{"use strict";h9="#__bigint"});var _t={};fr(_t,{IntegerOutOfRangeError:()=>Wu,InvalidHexBooleanError:()=>pb,InvalidHexTypeError:()=>ih,InvalidHexValueError:()=>ah,InvalidLengthError:()=>mb,SizeExceedsPaddingSizeError:()=>sh,SizeOverflowError:()=>oh,SliceOffsetOutOfBoundsError:()=>Vu,assert:()=>sB,concat:()=>Jt,from:()=>uo,fromBoolean:()=>lh,fromBytes:()=>Ke,fromNumber:()=>mt,fromString:()=>Vs,isEqual:()=>y9,padLeft:()=>Qo,padRight:()=>po,random:()=>b9,size:()=>rt,slice:()=>$t,toBigInt:()=>hb,toBoolean:()=>v9,toBytes:()=>k9,toNumber:()=>AE,toString:()=>x9,trimLeft:()=>ch,trimRight:()=>w9,validate:()=>al});function sB(e,t={}){let{strict:n=!1}=t;if(!e)throw new ih(e);if(typeof e!="string")throw new ih(e);if(n&&!/^0x[0-9a-fA-F]*$/.test(e))throw new ah(e);if(!e.startsWith("0x"))throw new ah(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 lh(e,t={}){let n=`0x${Number(e)}`;return typeof t.size=="number"?(sl(n,t.size),Qo(n,t.size)):n}function Ke(e,t={}){let n="";for(let o=0;o<e.length;o++)n+=g9[e[o]];let r=`0x${n}`;return typeof t.size=="number"?(sl(r,t.size),po(r,t.size)):r}function mt(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 Wu({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?Qo(l,r):l}function Vs(e,t={}){return Ke(f9.encode(e),t)}function y9(e,t){return ub(wt(e),wt(t))}function Qo(e,t){return vE(e,{dir:"left",size:t})}function po(e,t){return vE(e,{dir:"right",size:t})}function b9(e){return Ke(fb(e))}function $t(e,t,n,r={}){let{strict:o}=r;nB(e,t);let s=`0x${e.replace("0x","").slice((t??0)*2,(n??e.length)*2)}`;return o&&rB(s,t,n),s}function rt(e){return Math.ceil((e.length-2)/2)}function ch(e){return kE(e,{dir:"left"})}function w9(e){return kE(e,{dir:"right"})}function hb(e,t={}){let{signed:n}=t;t.size&&sl(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 v9(e,t={}){t.size&&sl(e,t.size);let n=ch(e);if(n==="0x")return!1;if(n==="0x1")return!0;throw new pb(e)}function k9(e,t={}){return wt(e,t)}function AE(e,t={}){let{signed:n,size:r}=t;return Number(!n&&!r?e:hb(e,t))}function x9(e,t={}){let{size:n}=t,r=wt(e);return n&&($s(r,n),r=gb(r)),new TextDecoder().decode(r)}function al(e,t={}){let{strict:n=!1}=t;try{return sB(e,{strict:n}),!0}catch{return!1}}var f9,g9,Wu,pb,ih,ah,mb,oh,Vu,sh,Tn=L(()=>{"use strict";Hu();Xt();An();wE();xE();il();f9=new TextEncoder,g9=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Wu=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"})}},pb=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"})}},ih=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"})}},ah=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"})}},mb=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"})}},oh=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"})}},sh=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:()=>yb,InvalidBytesTypeError:()=>ll,SizeExceedsPaddingSizeError:()=>rh,SizeOverflowError:()=>nh,SliceOffsetOutOfBoundsError:()=>$u,assert:()=>iB,concat:()=>zu,from:()=>Fn,fromArray:()=>aB,fromBoolean:()=>S9,fromHex:()=>wt,fromNumber:()=>Gu,fromString:()=>qn,isEqual:()=>P9,padLeft:()=>bb,padRight:()=>lB,random:()=>fb,size:()=>wr,slice:()=>TE,toBigInt:()=>SE,toBoolean:()=>PE,toHex:()=>E9,toNumber:()=>mo,toString:()=>uh,trimLeft:()=>wb,trimRight:()=>gb,validate:()=>Ku});function iB(e){if(!(e instanceof Uint8Array)){if(!e)throw new ll(e);if(typeof e!="object")throw new ll(e);if(!("BYTES_PER_ELEMENT"in e))throw new ll(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new ll(e)}}function zu(...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"?wt(e):aB(e)}function aB(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function S9(e,t={}){let{size:n}=t,r=new Uint8Array(1);return r[0]=Number(e),typeof n=="number"?($s(r,n),bb(r,n)):r}function wt(e,t={}){let{size:n}=t,r=e;n&&(sl(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=gE(o.charCodeAt(l++)),u=gE(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=mt(e,t);return wt(n)}function qn(e,t={}){let{size:n}=t,r=T9.encode(e);return typeof n=="number"?($s(r,n),lB(r,n)):r}function P9(e,t){return ub(e,t)}function bb(e,t){return yE(e,{dir:"left",size:t})}function lB(e,t){return yE(e,{dir:"right",size:t})}function fb(e){return crypto.getRandomValues(new Uint8Array(e))}function wr(e){return e.length}function TE(e,t,n,r={}){let{strict:o}=r;ZU(e,t);let s=e.slice(t,n);return o&&eB(s,t,n),s}function SE(e,t={}){let{size:n}=t;typeof n<"u"&&$s(e,n);let r=Ke(e,t);return hb(r,t)}function PE(e,t={}){let{size:n}=t,r=e;if(typeof n<"u"&&($s(r,n),r=wb(r)),r.length>1||r[0]>1)throw new yb(r);return!!r[0]}function E9(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 AE(r,t)}function uh(e,t={}){let{size:n}=t,r=e;return typeof n<"u"&&($s(r,n),r=gb(r)),A9.decode(r)}function wb(e){return bE(e,{dir:"left"})}function gb(e){return bE(e,{dir:"right"})}function Ku(e){try{return iB(e),!0}catch{return!1}}var A9,T9,yb,ll,nh,$u,rh,Xt=L(()=>{"use strict";Hu();An();Tn();wE();xE();il();A9=new TextDecoder,T9=new TextEncoder;yb=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"})}},ll=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"})}},nh=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"})}},rh=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:()=>RE,keccak256:()=>sn,ripemd160:()=>R9,sha256:()=>_9,validate:()=>I9});function sn(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,dB.keccak_256)(Fn(e));return n==="Bytes"?r:Ke(r)}function RE(e,t,n={}){let{as:r=typeof t=="string"?"Hex":"Bytes"}=n,o=(0,cB.hmac)(EE.sha256,Fn(e),Fn(t));return r==="Bytes"?o:Ke(o)}function R9(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,uB.ripemd160)(Fn(e));return n==="Bytes"?r:Ke(r)}function _9(e,t={}){let{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=(0,EE.sha256)(Fn(e));return n==="Bytes"?r:Ke(r)}function I9(e){return e.length===66&&al(e,{strict:!0})}var cB,uB,dB,EE,cl=L(()=>{"use strict";cB=require("@noble/hashes/hmac"),uB=require("@noble/hashes/ripemd160"),dB=require("@noble/hashes/sha3"),EE=require("@noble/hashes/sha256");Xt();Tn()});var vb,pB=L(()=>{"use strict";vb=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 C9,kb,_E=L(()=>{"use strict";pB();C9={checksum:new vb(8192)},kb=C9.checksum});function hB(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 xb({prefix:r,cause:new NE});return}if(n===!0||typeof o=="bigint"&&typeof s>"u"){if(r!==3&&r!==2)throw new xb({prefix:r,cause:new CE});return}throw new IE({publicKey:e})}function LE(e){let t=(()=>{if(al(e))return fB(e);if(Ku(e))return N9(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 hB(t),t}function N9(e){return fB(Ke(e))}function fB(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new OE({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 gB(e,t={}){return wt(dh(e,t))}function dh(e,t={}){hB(e);let{prefix:n,x:r,y:o}=e,{includePrefix:s=!0}=t;return Jt(s?mt(n,{size:1}):"0x",mt(r,{size:32}),typeof o=="bigint"?mt(o,{size:32}):"0x")}var IE,xb,CE,NE,OE,Ab=L(()=>{"use strict";Xt();An();Tn();il();IE=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"})}},xb=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"})}},CE=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"})}},NE=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"})}},OE=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 ${rt(uo(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});var Jo={};fr(Jo,{InvalidAddressError:()=>ul,InvalidChecksumError:()=>Tb,InvalidInputError:()=>Yu,assert:()=>Xo,checksum:()=>ph,from:()=>dl,fromPublicKey:()=>UE,isEqual:()=>BE,validate:()=>pl});function Xo(e,t={}){let{strict:n=!0}=t;if(!O9.test(e))throw new ul({address:e,cause:new Yu});if(n){if(e.toLowerCase()===e)return;if(ph(e)!==e)throw new ul({address:e,cause:new Tb})}}function ph(e){if(kb.has(e))return kb.get(e);Xo(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 kb.set(e,o),o}function dl(e,t={}){let{checksum:n=!1}=t;return Xo(e),n?ph(e):e}function UE(e,t={}){let n=sn(`0x${dh(e).slice(4)}`).substring(26);return dl(`0x${n}`,t)}function BE(e,t){return Xo(e,{strict:!1}),Xo(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}function pl(e,t={}){let{strict:n=!0}=t??{};try{return Xo(e,{strict:n}),!0}catch{return!1}}var O9,ul,Yu,Tb,ji=L(()=>{"use strict";Xt();_E();An();cl();Ab();O9=/^0x[a-fA-F0-9]{40}$/;ul=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"})}},Tb=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 Pb(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 Sb(e,t){let n=typeof e,r=t.type;switch(r){case"address":return pl(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)=>Sb(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=>Sb(o,{...t,type:r.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function ME(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 ME(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")?pl(n[r],{strict:!1}):i.includes("address")&&i.includes("bytes")?pl(n[r],{strict:!1}):!1)return i}}var yB=L(()=>{"use strict";ji();An()});function bB(e,t={}){let{prepare:n=!0}=t,r=Array.isArray(e)?ab(e):typeof e=="string"?ab(e):e;return{...r,...n?{hash:Qu(r)}:{}}}function mh(e,t,n){let{args:r=[],prepare:o=!0}=n??{},s=al(t,{strict:!1}),i=e.filter(c=>s?c.type==="function"||c.type==="error"?qE(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?Sb(d,m):!1})){if(a&&"inputs"in a&&a.inputs){let d=ME(c.inputs,a.inputs,r);if(d)throw new FE({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 qE(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,r]=e;return mh(n,r)}return e[0]})();return $t(Qu(t),0,4)}function D9(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,o]=e;return mh(r,o)}return e[0]})(),n=typeof t=="string"?t:el(t);return Pb(n)}function Qu(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,r]=e;return mh(n,r)}return e[0]})();return typeof t!="string"&&"hash"in t&&t.hash?t.hash:sn(Vs(D9(t)))}var FE,Xu,Eb,HE=L(()=>{"use strict";cb();An();cl();Tn();yB();FE=class extends le{constructor(t,n){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${Pb(el(t.abiItem))}\`, and`,`\`${n.type}\` in \`${Pb(el(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"})}},Eb=class extends le{constructor({data:t}){super(`Selector size is invalid. Expected 4 bytes. Received ${rt(t)} bytes ("${t}").`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.InvalidSelectorSizeError"})}}});var vB,Rb,Ju,REe,_Ee,IEe,CEe,NEe,OEe,LEe,DEe,UEe,BEe,MEe,FEe,qEe,HEe,$Ee,VEe,jEe,WEe,zEe,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,_Re,IRe,CRe,NRe,ORe,LRe,DRe,URe,BRe,MRe,FRe,qRe,HRe,$Re,VRe,jRe,WRe,zRe,GRe,KRe,YRe,QRe,XRe,JRe,ZRe,e_e,t_e,n_e,r_e,o_e,s_e,i_e,a_e,l_e,c_e,u_e,d_e,p_e,m_e,h_e,$E,Zu=L(()=>{"use strict";vB=/^(.*)\[([0-9]*)\]$/,Rb=/^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)?$/,REe=2n**(8n-1n)-1n,_Ee=2n**(16n-1n)-1n,IEe=2n**(24n-1n)-1n,CEe=2n**(32n-1n)-1n,NEe=2n**(40n-1n)-1n,OEe=2n**(48n-1n)-1n,LEe=2n**(56n-1n)-1n,DEe=2n**(64n-1n)-1n,UEe=2n**(72n-1n)-1n,BEe=2n**(80n-1n)-1n,MEe=2n**(88n-1n)-1n,FEe=2n**(96n-1n)-1n,qEe=2n**(104n-1n)-1n,HEe=2n**(112n-1n)-1n,$Ee=2n**(120n-1n)-1n,VEe=2n**(128n-1n)-1n,jEe=2n**(136n-1n)-1n,WEe=2n**(144n-1n)-1n,zEe=2n**(152n-1n)-1n,GEe=2n**(160n-1n)-1n,KEe=2n**(168n-1n)-1n,YEe=2n**(176n-1n)-1n,QEe=2n**(184n-1n)-1n,XEe=2n**(192n-1n)-1n,JEe=2n**(200n-1n)-1n,ZEe=2n**(208n-1n)-1n,eRe=2n**(216n-1n)-1n,tRe=2n**(224n-1n)-1n,nRe=2n**(232n-1n)-1n,rRe=2n**(240n-1n)-1n,oRe=2n**(248n-1n)-1n,sRe=2n**(256n-1n)-1n,iRe=-(2n**(8n-1n)),aRe=-(2n**(16n-1n)),lRe=-(2n**(24n-1n)),cRe=-(2n**(32n-1n)),uRe=-(2n**(40n-1n)),dRe=-(2n**(48n-1n)),pRe=-(2n**(56n-1n)),mRe=-(2n**(64n-1n)),hRe=-(2n**(72n-1n)),fRe=-(2n**(80n-1n)),gRe=-(2n**(88n-1n)),yRe=-(2n**(96n-1n)),bRe=-(2n**(104n-1n)),wRe=-(2n**(112n-1n)),vRe=-(2n**(120n-1n)),kRe=-(2n**(128n-1n)),xRe=-(2n**(136n-1n)),ARe=-(2n**(144n-1n)),TRe=-(2n**(152n-1n)),SRe=-(2n**(160n-1n)),PRe=-(2n**(168n-1n)),ERe=-(2n**(176n-1n)),RRe=-(2n**(184n-1n)),_Re=-(2n**(192n-1n)),IRe=-(2n**(200n-1n)),CRe=-(2n**(208n-1n)),NRe=-(2n**(216n-1n)),ORe=-(2n**(224n-1n)),LRe=-(2n**(232n-1n)),DRe=-(2n**(240n-1n)),URe=-(2n**(248n-1n)),BRe=-(2n**(256n-1n)),MRe=2n**8n-1n,FRe=2n**16n-1n,qRe=2n**24n-1n,HRe=2n**32n-1n,$Re=2n**40n-1n,VRe=2n**48n-1n,jRe=2n**56n-1n,WRe=2n**64n-1n,zRe=2n**72n-1n,GRe=2n**80n-1n,KRe=2n**88n-1n,YRe=2n**96n-1n,QRe=2n**104n-1n,XRe=2n**112n-1n,JRe=2n**120n-1n,ZRe=2n**128n-1n,e_e=2n**136n-1n,t_e=2n**144n-1n,n_e=2n**152n-1n,r_e=2n**160n-1n,o_e=2n**168n-1n,s_e=2n**176n-1n,i_e=2n**184n-1n,a_e=2n**192n-1n,l_e=2n**200n-1n,c_e=2n**208n-1n,u_e=2n**216n-1n,d_e=2n**224n-1n,p_e=2n**232n-1n,m_e=2n**240n-1n,h_e=2n**248n-1n,$E=2n**256n-1n});function ml(e,t,n){let{checksumAddress:r,staticPosition:o}=n,s=WE(t.type);if(s){let[i,a]=s;return B9(e,{...t,type:a},{checksumAddress:r,length:i,staticPosition:o})}if(t.type==="tuple")return H9(e,t,{checksumAddress:r,staticPosition:o});if(t.type==="address")return U9(e,{checksum:r});if(t.type==="bool")return M9(e);if(t.type.startsWith("bytes"))return F9(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return q9(e,t);if(t.type==="string")return $9(e,{staticPosition:o});throw new hl(t.type)}function U9(e,t={}){let{checksum:n=!1}=t,r=e.readBytes(32);return[(s=>n?ph(s):s)(Ke(TE(r,-20))),32]}function B9(e,t,n){let{checksumAddress:r,length:o,staticPosition:s}=n;if(o===null){let l=mo(e.readBytes(VE)),c=s+l,u=c+kB;e.setPosition(c);let d=mo(e.readBytes(kB)),p=ed(t),m=0,g=[];for(let f=0;f<d;++f){e.setPosition(u+(p?f*32:m));let[y,w]=ml(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(VE)),c=s+l,u=[];for(let d=0;d<o;++d){e.setPosition(c+d*32);let[p]=ml(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]=ml(e,t,{checksumAddress:r,staticPosition:s+i});i+=u,a.push(c),u===0&&(e.assertReadLimit(),e._touch())}return[a,i]}function M9(e){return[PE(e.readBytes(32),{size:32}),32]}function F9(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 q9(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?SE(o,{signed:n}):mo(o,{signed:n}),32]}function H9(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(VE)),c=o+l;for(let u=0;u<t.components.length;++u){let d=t.components[u];e.setPosition(c+a);let[p,m]=ml(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]=ml(e,c,{checksumAddress:r,staticPosition:o});i[s?l:c?.name]=u,a+=d}return[i,a]}function $9(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=uh(wb(s));return e.setPosition(t+32),[i,32]}function xB({checksumAddress:e,parameters:t,values:n}){let r=[];for(let o=0;o<t.length;o++)r.push(jE({checksumAddress:e,parameter:t[o],value:n[o]}));return r}function jE({checksumAddress:e=!1,parameter:t,value:n}){let r=t,o=WE(r.type);if(o){let[s,i]=o;return j9(n,{checksumAddress:e,length:s,parameter:{...r,type:i}})}if(r.type==="tuple")return Y9(n,{checksumAddress:e,parameter:r});if(r.type==="address")return V9(n,{checksum:e});if(r.type==="bool")return z9(n);if(r.type.startsWith("uint")||r.type.startsWith("int")){let s=r.type.startsWith("int"),[,,i="256"]=Ju.exec(r.type)??[];return G9(n,{signed:s,size:Number(i)})}if(r.type.startsWith("bytes"))return W9(n,{type:r.type});if(r.type==="string")return K9(n);throw new hl(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+=rt(a)}let n=[],r=[],o=0;for(let s=0;s<e.length;s++){let{dynamic:i,encoded:a}=e[s];i?(n.push(mt(t+o,{size:32})),r.push(a),o+=rt(a)):n.push(a)}return Jt(...n,...r)}function V9(e,t){let{checksum:n=!1}=t;return Xo(e,{strict:n}),{dynamic:!1,encoded:Qo(e.toLowerCase())}}function j9(e,t){let{checksumAddress:n,length:r,parameter:o}=t,s=r===null;if(!Array.isArray(e))throw new fh(e);if(!s&&e.length!==r)throw new hh({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=jE({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=mt(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 W9(e,{type:t}){let[,n]=t.split("bytes"),r=rt(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(Qo(mt(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 z9(e){if(typeof e!="boolean")throw new le(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Qo(lh(e))}}function G9(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 Wu({max:r.toString(),min:o.toString(),signed:t,size:n/8,value:e.toString()})}return{dynamic:!1,encoded:mt(e,{size:32,signed:t})}}function K9(e){let t=Vs(e),n=Math.ceil(rt(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(mt(rt(t),{size:32})),...r)}}function Y9(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=jE({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 WE(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=WE(e.type);return!!(n&&ed({...e,type:n[1]}))}var kB,VE,AB=L(()=>{"use strict";gh();ji();Xt();An();Tn();Zu();kB=32,VE=32});function Nb(e,{recursiveReadLimit:t=8192}={}){let n=Object.create(X9);return n.bytes=e,n.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}var X9,Cb,zE,GE,KE=L(()=>{"use strict";An();X9={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 GE({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new zE({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Cb({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 Cb({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++}};Cb=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"})}},zE=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"})}},GE=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 Wt={};fr(Wt,{ArrayLengthMismatchError:()=>hh,BytesSizeMismatchError:()=>td,DataSizeTooSmallError:()=>Lb,InvalidArrayError:()=>fh,InvalidTypeError:()=>hl,LengthMismatchError:()=>yh,ZeroDataError:()=>Db,decode:()=>Ub,encode:()=>fl,encodePacked:()=>Ob,format:()=>J9,from:()=>Z9});function Ub(e,t,n={}){let{as:r="Array",checksumAddress:o=!1}=n,s=typeof t=="string"?wt(t):t,i=Nb(s);if(wr(s)===0&&e.length>0)throw new Db;if(wr(s)&&wr(s)<32)throw new Lb({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]=ml(i,u,{checksumAddress:o,staticPosition:0});a+=p,r==="Array"?l.push(d):l[u.name??c]=d}return l}function fl(e,t,n){let{checksumAddress:r=!1}=n??{};if(e.length!==t.length)throw new yh({expectedLength:e.length,givenLength:t.length});let o=xB({checksumAddress:r,parameters:e,values:t}),s=Ib(o);return s.length===0?"0x":s}function Ob(e,t){if(e.length!==t.length)throw new yh({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(Ob.encode(o,s))}return Jt(...n)}function J9(e){return Ko(e)}function Z9(e){return Array.isArray(e)&&typeof e[0]=="string"?lb(e):typeof e=="string"?lb(e):e}var Lb,Db,hh,td,yh,fh,hl,gh=L(()=>{"use strict";cb();ji();Xt();An();Tn();AB();KE();Zu();(function(e){function t(n,r,o=!1){if(n==="address"){let l=r;return Xo(l),Qo(l.toLowerCase(),o?32:0)}if(n==="string")return Vs(r);if(n==="bytes")return r;if(n==="bool")return Qo(lh(r),o?32:1);let s=n.match(Ju);if(s){let[l,c,u="256"]=s,d=Number.parseInt(u,10)/8;return mt(r,{size:o?32:d,signed:c==="int"})}let i=n.match(Rb);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(vB);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 hl(n)}e.encode=t})(Ob||(Ob={}));Lb=class extends le{constructor({data:t,parameters:n,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${Ko(n)})`,`Data: ${t} (${r} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}},Db=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"})}},hh=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${rt(n)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}},yh=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
|
+
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}},fh=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"})}},hl=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 SB=L(()=>{"use strict"});var PB=L(()=>{"use strict"});var EB=L(()=>{"use strict"});var Ie={};fr(Ie,{decodeData:()=>r7,decodeResult:()=>o7,encodeData:()=>s7,encodeResult:()=>i7,format:()=>a7,from:()=>l7,fromAbi:()=>gl,getSelector:()=>RB});function r7(...e){let[t,n]=(()=>{if(Array.isArray(e[0])){let[s,i,a]=e;return[gl(s,i),a]}return e})(),{overloads:r}=t;if(rt(n)<4)throw new Eb({data:n});if(t.inputs?.length===0)return;let o=r?gl([t,...r],n):t;if(!(rt(n)<=4))return Ub(o.inputs,$t(n,4))}function o7(...e){let[t,n,r={}]=(()=>{if(Array.isArray(e[0])){let[s,i,a,l]=e;return[gl(s,i),a,l]}return e})(),o=Ub(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 s7(...e){let[t,n=[]]=(()=>{if(Array.isArray(e[0])){let[c,u,d]=e;return[gl(c,u,{args:d}),d]}let[a,l]=e;return[a,l]})(),{overloads:r}=t,o=r?gl([t,...r],t.name,{args:n}):t,s=RB(o),i=n.length>0?fl(o.inputs,n):void 0;return i?Jt(s,i):s}function i7(...e){let[t,n,r={}]=(()=>{if(Array.isArray(e[0])){let[i,a,l,c]=e;return[gl(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 fl(t.outputs,s)}function a7(e){return el(e)}function l7(e,t={}){return bB(e,t)}function gl(e,t,n){let r=mh(e,t,n);if(r.type!=="function")throw new Xu({name:t,type:"function"});return r}function RB(e){return qE(e)}var _B=L(()=>{"use strict";cb();HE();gh();Tn()});var IB=L(()=>{"use strict"});var CB=L(()=>{"use strict"});function YE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function OB(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 u7(e){if(typeof e!="function")throw new Error("function expected");return!0}function QE(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function JE(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function XE(e){if(!Array.isArray(e))throw new Error("array expected")}function LB(e,t){if(!OB(!0,t))throw new Error(`${e}: array of strings expected`)}function d7(e,t){if(!OB(!1,t))throw new Error(`${e}: array of numbers expected`)}function DB(...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 p7(e){let t=typeof e=="string"?e.split(""):e,n=t.length;LB("alphabet",t);let r=new Map(t.map((o,s)=>[o,s]));return{encode:o=>(XE(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=>(XE(o),o.map(s=>{QE("alphabet.decode",s);let i=r.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return i}))}}function m7(e=""){return QE("join",e),{encode:t=>(LB("join.decode",t),t.join(e)),decode:t=>(QE("join.decode",t),t.split(e))}}function NB(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(XE(e),!e.length)return[];let r=0,o=[],s=Array.from(e,a=>{if(JE(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 h7(e){JE(e);let t=2**8;return{encode:n=>{if(!YE(n))throw new Error("radix.encode input should be Uint8Array");return NB(Array.from(n),t,e)},decode:n=>(d7("radix.decode",n),Uint8Array.from(NB(n,e,t)))}}function f7(e,t){return JE(e),u7(t),{encode(n){if(!YE(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(!YE(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 g7,y7,UB,BB=L(()=>{"use strict";g7=e=>DB(h7(58),p7(e),m7("")),y7=g7("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),UB=e=>DB(f7(4,t=>e(e(t))),y7)});function MB(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function b7(e){let t=MB(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function nR(e,t=""){return(0,ZE.pbkdf2)(eR.sha512,b7(e).nfkd,w7(t),{c:2048,dkLen:64})}var ZE,eR,tR,w7,rR=L(()=>{"use strict";ZE=require("@noble/hashes/pbkdf2"),eR=require("@noble/hashes/sha2"),tR=require("@noble/hashes/utils");w7=e=>MB("mnemonic"+e)});function bh(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function Wi(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 wh(e){let t=e.toString(16);return t.length&1?"0"+t:t}function FB(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?iR:BigInt("0x"+e)}function nd(e){return FB((0,vr.bytesToHex)(e))}function aR(e){return(0,vr.abytes)(e),FB((0,vr.bytesToHex)(Uint8Array.from(e).reverse()))}function Bb(e,t){return(0,vr.hexToBytes)(e.toString(16).padStart(t*2,"0"))}function lR(e,t){return Bb(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 qB(e,t,n){return oR(e)&&oR(t)&&oR(n)&&t<=e&&e<n}function HB(e,t,n,r){if(!qB(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Mb(e){let t;for(t=0;e>iR;e>>=sR,t+=1);return t}function $B(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 vh(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 cR(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,iR,sR,oR,zi,Fb=L(()=>{"use strict";vr=require("@noble/hashes/utils.js"),Qe=require("@noble/hashes/utils.js");iR=BigInt(0),sR=BigInt(1);oR=e=>typeof e=="bigint"&&iR<=e;zi=e=>(sR<<BigInt(e))-sR});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 VB(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 uR(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function QB(e,t){let n=(e.ORDER+Pn)/zB,r=e.pow(t,n);return uR(e,r,t),r}function x7(e,t){let n=(e.ORDER-GB)/KB,r=e.mul(t,yl),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,yl),o),a=e.mul(s,e.sub(i,e.ONE));return uR(e,a,t),a}function A7(e){let t=Gi(e),n=XB(e),r=n(t,t.neg(t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+v7)/YB;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 uR(a,y,l),y}}function XB(e){if(e<WB)throw new Error("sqrt is not defined for small field");let t=e-Pn,n=0;for(;t%yl===Hn;)t/=yl,n++;let r=yl,o=Gi(e);for(;jB(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return QB;let s=o.pow(r,t),i=(t+Pn)/yl;return function(l,c){if(l.is0(c))return c;if(jB(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 T7(e){return e%zB===WB?QB:e%KB===GB?x7:e%YB===k7?A7(e):XB(e)}function dR(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=S7.reduce((r,o)=>(r[o]="function",r),t);return vh(e,n),e}function P7(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 qb(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 jB(e,t){let n=(e.ORDER-Pn)/yl,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 Hb(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 Gi(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}=Hb(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:zi(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)=>P7(d,p,m),div:(p,m)=>sr(p*VB(m,e),e),sqrN:p=>p*p,addN:(p,m)=>p+m,subN:(p,m)=>p-m,mulN:(p,m)=>p*m,inv:p=>VB(p,e),sqrt:s||(p=>(u||(u=T7(e)),u(d,p))),toBytes:p=>n?lR(p,c):Bb(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?aR(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=>qb(d,p),cmov:(p,m,g)=>g?m:p});return Object.freeze(d)}function JB(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=JB(e);return t+Math.ceil(t/2)}function mR(e,t,n=!1){let r=e.length,o=JB(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?aR(e):nd(e),a=sr(i,t-Pn)+Pn;return n?lR(a,o):Bb(a,o)}var Hn,Pn,yl,WB,zB,GB,v7,KB,k7,YB,S7,kh=L(()=>{"use strict";Fb();Hn=BigInt(0),Pn=BigInt(1),yl=BigInt(2),WB=BigInt(3),zB=BigInt(4),GB=BigInt(5),v7=BigInt(7),KB=BigInt(8),k7=BigInt(9),YB=BigInt(16);S7=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function xh(e,t){let n=t.negate();return e?n:t}function Vb(e,t){let n=qb(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function nM(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function hR(e,t){nM(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=zi(e),i=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function ZB(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+=bl);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 E7(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 R7(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 gR(e){return rM.get(e)||1}function eM(e){if(e!==rd)throw new Error("invalid wNAF")}function oM(e,t,n,r){let o=t,s=e.ZERO,i=e.ZERO;for(;n>rd||r>rd;)n&bl&&(s=s.add(o)),r&bl&&(i=i.add(o)),o=o.double(),n>>=bl,r>>=bl;return{p1:s,p2:i}}function sM(e,t,n,r){E7(n,e),R7(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=Mb(BigInt(o)),l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);let c=zi(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 tM(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return dR(t),t}else return Gi(e,{isLE:n})}function iM(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=tM(t.p,n.Fp,r),s=tM(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,bl,fR,rM,$b,aM=L(()=>{"use strict";Fb();kh();rd=BigInt(0),bl=BigInt(1);fR=new WeakMap,rM=new WeakMap;$b=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&bl&&(r=r.add(o)),o=o.double(),n>>=bl;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=hR(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=hR(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:c,isZero:u,isNeg:d,isNegF:p,offsetF:m}=ZB(r,a,i);r=l,u?s=s.add(xh(p,n[m])):o=o.add(xh(d,n[c]))}return eM(r),{p:o,f:s}}wNAFUnsafe(t,n,r,o=this.ZERO){let s=hR(t,this.bits);for(let i=0;i<s.windows&&r!==rd;i++){let{nextN:a,offset:l,isZero:c,isNeg:u}=ZB(r,i,s);if(r=a,!c){let d=n[l];o=o.add(u?d.negate():d)}}return eM(r),o}getPrecomputes(t,n,r){let o=fR.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),fR.set(n,o))),o}cached(t,n,r){let o=gR(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let s=gR(t);return s===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,o)}createCache(t,n){nM(n,this.bits),rM.set(t,n),fR.delete(t)}hasCache(t){return gR(t)!==1}}});function _7(e,t,n){let[[r,o],[s,i]]=t,a=lM(i*e,n),l=lM(-o*e,n),c=e-a*r-l*s,u=-a*o-l*i,d=c<Ws,p=u<Ws;d&&(c=-c),p&&(u=-u);let m=zi(Math.ceil(Mb(n)/2))+sd;if(c<Ws||c>=m||u<Ws||u>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:c,k2neg:p,k2:u}}function bR(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function yR(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return bh(n.lowS,"lowS"),bh(n.prehash,"prehash"),n.format!==void 0&&bR(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 C7(e,t={}){let n=iM("weierstrass",e,t),{Fp:r,Fn:o}=n,s=n.CURVE,{h:i,n:a}=s;vh(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=mM(r,o);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(oe,F,z){let{x:_,y:N}=F.toAffine(),G=r.toBytes(_);if(bh(z,"isCompressed"),z){u();let ne=!r.isOdd(N);return(0,Qe.concatBytes)(pM(ne),G)}else return(0,Qe.concatBytes)(Uint8Array.of(4),G,r.toBytes(N))}function p(oe){Wi(oe,void 0,"Point");let{publicKey:F,publicKeyUncompressed:z}=c,_=oe.length,N=oe[0],G=oe.subarray(1);if(_===F&&(N===2||N===3)){let ne=r.fromBytes(G);if(!r.isValid(ne))throw new Error("bad point: is not on curve, wrong x");let Z=f(ne),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:ne,y:Q}}else if(_===z&&N===4){let ne=r.BYTES,Z=r.fromBytes(G.subarray(0,ne)),Q=r.fromBytes(G.subarray(ne,ne*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 ${_}, expected compressed=${F} or uncompressed=${z}`)}let m=t.toBytes||d,g=t.fromBytes||p;function f(oe){let F=r.sqr(oe),z=r.mul(F,oe);return r.add(r.add(z,r.mul(oe,s.a)),s.b)}function y(oe,F){let z=r.sqr(F),_=f(oe);return r.eql(z,_)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=r.mul(r.pow(s.a,jb),I7),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 A(oe,F,z=!1){if(!r.isValid(F)||z&&r.is0(F))throw new Error(`bad point coordinate ${oe}`);return F}function k(oe){if(!(oe instanceof Y))throw new Error("ProjectivePoint expected")}function T(oe){if(!l||!l.basises)throw new Error("no endo");return _7(oe,l.basises,o.ORDER)}let D=cR((oe,F)=>{let{X:z,Y:_,Z:N}=oe;if(r.eql(N,r.ONE))return{x:z,y:_};let G=oe.is0();F==null&&(F=G?r.ONE:r.inv(N));let ne=r.mul(z,F),Z=r.mul(_,F),Q=r.mul(N,F);if(G)return{x:r.ZERO,y:r.ZERO};if(!r.eql(Q,r.ONE))throw new Error("invZ was invalid");return{x:ne,y:Z}}),q=cR(oe=>{if(oe.is0()){if(t.allowInfinityPoint&&!r.is0(oe.Y))return;throw new Error("bad point: ZERO")}let{x:F,y:z}=oe.toAffine();if(!r.isValid(F)||!r.isValid(z))throw new Error("bad point: x or y not field elements");if(!y(F,z))throw new Error("bad point: equation left != right");if(!oe.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function V(oe,F,z,_,N){return z=new Y(r.mul(z.X,oe),z.Y,z.Z),F=xh(_,F),z=xh(N,z),F.add(z)}class Y{constructor(F,z,_){this.X=A("x",F),this.Y=A("y",z,!0),this.Z=A("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(F){let{x:z,y:_}=F||{};if(!F||!r.isValid(z)||!r.isValid(_))throw new Error("invalid affine point");if(F instanceof Y)throw new Error("projective point not allowed");return r.is0(z)&&r.is0(_)?Y.ZERO:new Y(z,_,r.ONE)}static fromBytes(F){let z=Y.fromAffine(g(Wi(F,void 0,"point")));return z.assertValidity(),z}static fromHex(F){return Y.fromBytes(Sn("pointHex",F))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(F=8,z=!0){return de.createCache(this,F),z||this.multiply(jb),this}assertValidity(){q(this)}hasEvenY(){let{y:F}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(F)}equals(F){k(F);let{X:z,Y:_,Z:N}=this,{X:G,Y:ne,Z}=F,Q=r.eql(r.mul(z,Z),r.mul(G,N)),ie=r.eql(r.mul(_,Z),r.mul(ne,N));return Q&&ie}negate(){return new Y(this.X,r.neg(this.Y),this.Z)}double(){let{a:F,b:z}=s,_=r.mul(z,jb),{X:N,Y:G,Z:ne}=this,Z=r.ZERO,Q=r.ZERO,ie=r.ZERO,me=r.mul(N,N),Ne=r.mul(G,G),ke=r.mul(ne,ne),be=r.mul(N,G);return be=r.add(be,be),ie=r.mul(N,ne),ie=r.add(ie,ie),Z=r.mul(F,ie),Q=r.mul(_,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(_,ie),ke=r.mul(F,ke),be=r.sub(me,ke),be=r.mul(F,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,ne),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(F){k(F);let{X:z,Y:_,Z:N}=this,{X:G,Y:ne,Z}=F,Q=r.ZERO,ie=r.ZERO,me=r.ZERO,Ne=s.a,ke=r.mul(s.b,jb),be=r.mul(z,G),qe=r.mul(_,ne),We=r.mul(N,Z),dt=r.add(z,_),He=r.add(G,ne);dt=r.mul(dt,He),He=r.add(be,qe),dt=r.sub(dt,He),He=r.add(z,N);let it=r.add(G,Z);return He=r.mul(He,it),it=r.add(be,We),He=r.sub(He,it),it=r.add(_,N),Q=r.add(ne,Z),it=r.mul(it,Q),Q=r.add(qe,We),it=r.sub(it,Q),me=r.mul(Ne,He),Q=r.mul(ke,We),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),We=r.mul(Ne,We),He=r.mul(ke,He),qe=r.add(qe,We),We=r.sub(be,We),We=r.mul(Ne,We),He=r.add(He,We),be=r.mul(qe,He),ie=r.add(ie,be),be=r.mul(it,He),Q=r.mul(dt,Q),Q=r.sub(Q,be),be=r.mul(dt,qe),me=r.mul(it,me),me=r.add(me,be),new Y(Q,ie,me)}subtract(F){return this.add(F.negate())}is0(){return this.equals(Y.ZERO)}multiply(F){let{endo:z}=t;if(!o.isValidNot0(F))throw new Error("invalid scalar: out of range");let _,N,G=ne=>de.cached(this,ne,Z=>Vb(Y,Z));if(z){let{k1neg:ne,k1:Z,k2neg:Q,k2:ie}=T(F),{p:me,f:Ne}=G(Z),{p:ke,f:be}=G(ie);N=Ne.add(be),_=V(z.beta,me,ke,ne,Q)}else{let{p:ne,f:Z}=G(F);_=ne,N=Z}return Vb(Y,[_,N])[0]}multiplyUnsafe(F){let{endo:z}=t,_=this;if(!o.isValid(F))throw new Error("invalid scalar: out of range");if(F===Ws||_.is0())return Y.ZERO;if(F===sd)return _;if(de.hasCache(this))return this.multiply(F);if(z){let{k1neg:N,k1:G,k2neg:ne,k2:Z}=T(F),{p1:Q,p2:ie}=oM(Y,_,G,Z);return V(z.beta,Q,ie,N,ne)}else return de.unsafe(_,F)}multiplyAndAddUnsafe(F,z,_){let N=this.multiplyUnsafe(z).add(F.multiplyUnsafe(_));return N.is0()?void 0:N}toAffine(F){return D(this,F)}isTorsionFree(){let{isTorsionFree:F}=t;return i===sd?!0:F?F(Y,this):de.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:F}=t;return i===sd?this:F?F(Y,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(F=!0){return bh(F,"isCompressed"),this.assertValidity(),m(Y,this,F)}toHex(F=!0){return(0,Qe.bytesToHex)(this.toBytes(F))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(F=!0){return this.toBytes(F)}_setWindowSize(F){this.precompute(F)}static normalizeZ(F){return Vb(Y,F)}static msm(F,z){return sM(Y,o,F,z)}static fromPrivateKey(F){return Y.BASE.multiply(od(o,F))}}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 te=o.BITS,de=new $b(Y,t.endo?Math.ceil(te/2):te);return Y.BASE.precompute(8),Y}function pM(e){return Uint8Array.of(e?2:3)}function mM(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function N7(e,t={}){let{Fn:n}=e,r=t.randomBytes||Qe.randomBytes,o=Object.assign(mM(e.Fp,n),{seed:pR(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 mR(Wi(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 O7(e,t,n={}){(0,uM.ahash)(t),vh(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=n.randomBytes||Qe.randomBytes,o=n.hmac||((z,..._)=>(0,cM.hmac)(t,z,(0,Qe.concatBytes)(..._))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:l}=i,{keygen:c,getPublicKey:u,getSharedSecret:d,utils:p,lengths:m}=N7(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},f="compact";function y(z){let _=a>>sd;return z>_}function w(z,_){if(!i.isValidNot0(_))throw new Error(`invalid signature ${z}: out of range 1..Point.Fn.ORDER`);return _}function v(z,_){bR(_);let N=m.signature,G=_==="compact"?N:_==="recovered"?N+1:void 0;return Wi(z,G,`${_} signature`)}class A{constructor(_,N,G){this.r=w("r",_),this.s=w("s",N),G!=null&&(this.recovery=G),Object.freeze(this)}static fromBytes(_,N=f){v(_,N);let G;if(N==="der"){let{r:ie,s:me}=js.toSig(Wi(_));return new A(ie,me)}N==="recovered"&&(G=_[0],N="compact",_=_.subarray(1));let ne=i.BYTES,Z=_.subarray(0,ne),Q=_.subarray(ne,ne*2);return new A(i.fromBytes(Z),i.fromBytes(Q),G)}static fromHex(_,N){return this.fromBytes((0,Qe.hexToBytes)(_),N)}addRecoveryBit(_){return new A(this.r,this.s,_)}recoverPublicKey(_){let N=s.ORDER,{r:G,s:ne,recovery:Z}=this;if(Z==null||![0,1,2,3].includes(Z))throw new Error("recovery id invalid");if(a*dM<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)(pM((Z&1)===0),me)),ke=i.inv(ie),be=T(Sn("msgHash",_)),qe=i.create(-be*ke),We=i.create(ne*ke),dt=e.BASE.multiplyUnsafe(qe).add(Ne.multiplyUnsafe(We));if(dt.is0())throw new Error("point at infinify");return dt.assertValidity(),dt}hasHighS(){return y(this.s)}toBytes(_=f){if(bR(_),_==="der")return(0,Qe.hexToBytes)(js.hexFromSig(this));let N=i.toBytes(this.r),G=i.toBytes(this.s);if(_==="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(_){return(0,Qe.bytesToHex)(this.toBytes(_))}assertValidity(){}static fromCompact(_){return A.fromBytes(Sn("sig",_),"compact")}static fromDER(_){return A.fromBytes(Sn("sig",_),"der")}normalizeS(){return this.hasHighS()?new A(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(_){if(_.length>8192)throw new Error("input is too large");let N=nd(_),G=_.length*8-l;return G>0?N>>BigInt(G):N},T=n.bits2int_modN||function(_){return i.create(k(_))},D=zi(l);function q(z){return HB("num < 2^"+l,z,Ws,D),i.toBytes(z)}function V(z,_){return Wi(z,void 0,"message"),_?Wi(t(z),void 0,"prehashed message"):z}function Y(z,_,N){if(["recovered","canonical"].some(qe=>qe in N))throw new Error("sign() legacy options not supported");let{lowS:G,prehash:ne,extraEntropy:Z}=yR(N,g);z=V(z,ne);let Q=T(z),ie=od(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 We=k(qe);if(!i.isValidNot0(We))return;let dt=i.inv(We),He=e.BASE.multiply(We).toAffine(),it=i.create(He.x);if(it===Ws)return;let je=i.create(dt*i.create(ke+it*ie));if(je===Ws)return;let Ss=(He.x===it?0:2)|Number(He.y&sd),Mr=je;return G&&y(je)&&(Mr=i.neg(je),Ss^=1),new A(it,Mr,Ss)}return{seed:Ne,k2sig:be}}function te(z,_,N={}){z=Sn("message",z);let{seed:G,k2sig:ne}=Y(z,_,N);return $B(t.outputLen,i.BYTES,o)(G,ne)}function de(z){let _,N=typeof z=="string"||(0,Qe.isBytes)(z),G=!N&&z!==null&&typeof z=="object"&&typeof z.r=="bigint"&&typeof z.s=="bigint";if(!N&&!G)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(G)_=new A(z.r,z.s);else if(N){try{_=A.fromBytes(Sn("sig",z),"der")}catch(ne){if(!(ne instanceof js.Err))throw ne}if(!_)try{_=A.fromBytes(Sn("sig",z),"compact")}catch{return!1}}return _||!1}function oe(z,_,N,G={}){let{lowS:ne,prehash:Z,format:Q}=yR(G,g);if(N=Sn("publicKey",N),_=V(Sn("message",_),Z),"strict"in G)throw new Error("options.strict was renamed to lowS");let ie=Q===void 0?de(z):A.fromBytes(Sn("sig",z),Q);if(ie===!1)return!1;try{let me=e.fromBytes(N);if(ne&&ie.hasHighS())return!1;let{r:Ne,s:ke}=ie,be=T(_),qe=i.inv(ke),We=i.create(be*qe),dt=i.create(Ne*qe),He=e.BASE.multiplyUnsafe(We).add(me.multiplyUnsafe(dt));return He.is0()?!1:i.create(He.x)===Ne}catch{return!1}}function F(z,_,N={}){let{prehash:G}=yR(N,g);return _=V(_,G),A.fromBytes(z,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:c,getPublicKey:u,getSharedSecret:d,utils:p,lengths:m,Point:e,sign:te,verify:oe,recoverPublicKey:F,Signature:A,hash:t})}function L7(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=Gi(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 D7(e){let{CURVE:t,curveOpts:n}=L7(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 U7(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Hb(n.Fn.ORDER,n.Fn.BITS))})}function hM(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=D7(e),s=C7(t,n),i=O7(s,r,o);return U7(e,i)}var cM,uM,lM,wR,js,Ws,sd,dM,jb,I7,fM=L(()=>{"use strict";cM=require("@noble/hashes/hmac.js"),uM=require("@noble/hashes/utils");Fb();aM();kh();lM=(e,t)=>(e+(e>=0?t:-t)/dM)/t;wR=class extends Error{constructor(t=""){super(t)}},js={Err:wR,_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=wh(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let s=r>127?wh(o.length/2|128):"";return wh(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<Ws)throw new t("integer: negative integers are not allowed");let n=wh(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)}},Ws=BigInt(0),sd=BigInt(1),dM=BigInt(2),jb=BigInt(3),I7=BigInt(4)});function gM(e,t){let n=r=>hM({...e,hash:r});return{...n(t),create:n}}var yM=L(()=>{"use strict";fM();});function F7(e){let t=kR.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,bM,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,A=kr(v,n,t)*u%t,k=kr(A,i,t)*g%t,T=kr(k,r,t)*c%t,D=kr(T,bM,t);if(!vR.eql(vR.sqr(D),e))throw new Error("Cannot find square root");return D}var wM,B7,kR,M7,bM,vR,Zo,vM=L(()=>{"use strict";wM=require("@noble/hashes/sha2.js"),B7=require("@noble/hashes/utils.js");yM();kh();kR={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},M7={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},bM=BigInt(2);vR=Gi(kR.p,{sqrt:F7}),Zo=gM({...kR,Fp:vR,lowS:!0,endo:M7},wM.sha256)});function kM(e){(0,It.abytes)(e);let t=e.length===0?"0":(0,It.bytesToHex)(e);return BigInt("0x"+t)}function q7(e){if(typeof e!="bigint")throw new Error("bigint expected");return(0,It.hexToBytes)(e.toString(16).padStart(64,"0"))}var SR,xM,id,It,Wb,xR,H7,AR,TR,$7,V7,zb,Gb,AM=L(()=>{"use strict";kh();vM();SR=require("@noble/hashes/hmac"),xM=require("@noble/hashes/legacy"),id=require("@noble/hashes/sha2"),It=require("@noble/hashes/utils");BB();Wb=Zo.ProjectivePoint,xR=UB(id.sha256);H7=(0,It.utf8ToBytes)("Bitcoin seed"),AR={private:76066276,public:76067358},TR=2147483648,$7=e=>(0,xM.ripemd160)((0,id.sha256)(e)),V7=e=>(0,It.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,It.createView)(t).setUint32(0,e,!1),t},Gb=class e{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return V7(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 xR.encode(this.serialize(this.versions.private,(0,It.concatBytes)(new Uint8Array([0]),t)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return xR.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(t,n=AR){if((0,It.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,SR.hmac)(id.sha512,H7,t);return new e({versions:n,chainCode:r.slice(32),privateKey:r.slice(0,32)})}static fromExtendedKey(t,n=AR){let r=xR.decode(t),o=(0,It.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||AR,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(!Zo.utils.isValidPrivateKey(t.privateKey))throw new Error("Invalid private key");this.privKey=typeof t.privateKey=="bigint"?t.privateKey:kM(t.privateKey),this.privKeyBytes=q7(this.privKey),this.pubKey=Zo.getPublicKey(t.privateKey,!0)}else if(t.publicKey)this.pubKey=Wb.fromHex(t.publicKey).toRawBytes(!0);else throw new Error("HDKey: no public or private key provided");this.pubHash=$7(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>=TR)throw new Error("Invalid index");s[2]==="'"&&(a+=TR),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>=TR){let a=this.privateKey;if(!a)throw new Error("Could not derive hardened child key");n=(0,It.concatBytes)(new Uint8Array([0]),a,n)}else n=(0,It.concatBytes)(this.pubKey,n);let r=(0,SR.hmac)(id.sha512,this.chainCode,n),o=kM(r.slice(0,32)),s=r.slice(32);if(!Zo.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,Zo.CURVE.n);if(!Zo.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=Wb.fromHex(this.pubKey).add(Wb.fromPrivateKey(o));if(a.equals(Wb.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,It.abytes)(t,32),Zo.sign(t,this.privKey).toCompactRawBytes()}verify(t,n){if((0,It.abytes)(t,32),(0,It.abytes)(n,64),!this.publicKey)throw new Error("No publicKey set!");let r;try{r=Zo.Signature.fromCompact(n)}catch{return!1}return Zo.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,It.abytes)(n,33),(0,It.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 Kb(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 _M(e,t){let n=(e.ORDER+Rn)/PM,r=e.pow(t,n);if(!e.eql(e.sqr(r),t))throw new Error("Cannot find square root");return r}function W7(e,t){let n=(e.ORDER-EM)/RM,r=e.mul(t,wl),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,wl),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 z7(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-Rn,n=0;for(;t%wl===$n;)t/=wl,n++;let r=wl,o=Ah(e);for(;TM(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return _M;let s=o.pow(r,t),i=(t+Rn)/wl;return function(l,c){if(l.is0(c))return c;if(TM(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 G7(e){return e%PM===j7?_M:e%RM===EM?W7:z7(e)}function PR(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=K7.reduce((r,o)=>(r[o]="function",r),t);return ol(e,n)}function Y7(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 ER(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 TM(e,t){let n=(e.ORDER-Rn)/wl,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 RR(e,t){t!==void 0&&(0,SM.anumber)(t);let n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Ah(e,t,n=!1,r={}){if(e<=$n)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=RR(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:rl(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)=>Y7(a,l,c),div:(l,c)=>En(l*Kb(c,e),e),sqrN:l=>l*l,addN:(l,c)=>l+c,subN:(l,c)=>l-c,mulN:(l,c)=>l*c,inv:l=>Kb(l,e),sqrt:r.sqrt||(l=>(i||(i=G7(e)),i(a,l))),toBytes:l=>n?hE(l,s):tl(l,s),fromBytes:l=>{if(l.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+l.length);return n?mE(l):qs(l)},invertBatch:l=>ER(a,l),cmov:(l,c,u)=>u?c:l});return Object.freeze(a)}function IM(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 _R(e){let t=IM(e);return t+Math.ceil(t/2)}function CM(e,t,n=!1){let r=e.length,o=IM(t),s=_R(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);let i=n?mE(e):qs(e),a=En(i,t-Rn)+Rn;return n?hE(a,o):tl(a,o)}var SM,$n,Rn,wl,j7,PM,EM,RM,K7,Yb=L(()=>{"use strict";SM=require("@noble/hashes/utils");Hu();$n=BigInt(0),Rn=BigInt(1),wl=BigInt(2),j7=BigInt(3),PM=BigInt(4),EM=BigInt(5),RM=BigInt(8);K7=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function IR(e,t){let n=t.negate();return e?n:t}function LM(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function CR(e,t){LM(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=rl(e),i=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function OM(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+=LR);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 Q7(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 X7(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 OR(e){return DM.get(e)||1}function UM(e,t){return{constTimeNegate:IR,hasPrecomputes(n){return OR(n)!==1},unsafeLadder(n,r,o=e.ZERO){let s=n;for(;r>NM;)r&LR&&(o=o.add(s)),s=s.double(),r>>=LR;return o},precomputeWindow(n,r){let{windows:o,windowSize:s}=CR(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=CR(n,t);for(let l=0;l<a.windows;l++){let{nextN:c,offset:u,isZero:d,isNeg:p,isNegF:m,offsetF:g}=OM(o,l,a);o=c,d?i=i.add(IR(m,r[g])):s=s.add(IR(p,r[u]))}return{p:s,f:i}},wNAFUnsafe(n,r,o,s=e.ZERO){let i=CR(n,t);for(let a=0;a<i.windows&&o!==NM;a++){let{nextN:l,offset:c,isZero:u,isNeg:d}=OM(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=NR.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&NR.set(r,o(s))),s},wNAFCached(n,r,o){let s=OR(n);return this.wNAF(s,this.getPrecomputes(s,n,o),r)},wNAFCachedUnsafe(n,r,o,s){let i=OR(n);return i===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(i,this.getPrecomputes(i,n,o),r,s)},setWindowSize(n,r){LM(r,t),DM.set(n,r),NR.delete(n)}}}function BM(e,t,n,r){Q7(n,e),X7(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=XU(BigInt(o)),l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);let c=rl(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 DR(e){return PR(e.Fp),ol(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...RR(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}var NM,LR,NR,DM,MM=L(()=>{"use strict";Yb();Hu();NM=BigInt(0),LR=BigInt(1);NR=new WeakMap,DM=new WeakMap});function FM(e){e.lowS!==void 0&&Fu("lowS",e.lowS),e.prehash!==void 0&&Fu("prehash",e.prehash)}function J7(e){let t=DR(e);ol(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 UR(e,t){return qu(tl(e,t))}function eQ(e){let t=J7(e),{Fp:n}=t,r=Ah(t.n,t.nBitLength),o=t.toBytes||((A,k,T)=>{let D=k.toAffine();return th(Uint8Array.from([4]),n.toBytes(D.x),n.toBytes(D.y))}),s=t.fromBytes||(A=>{let k=A.subarray(1),T=n.fromBytes(k.subarray(0,n.BYTES)),D=n.fromBytes(k.subarray(n.BYTES,2*n.BYTES));return{x:T,y:D}});function i(A){let{a:k,b:T}=t,D=n.sqr(A),q=n.mul(D,A);return n.add(n.add(q,n.mul(A,k)),T)}function a(A,k){let T=n.sqr(k),D=i(A);return n.eql(T,D)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let l=n.mul(n.pow(t.a,BR),Z7),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(A){return db(A,an,t.n)}function d(A){let{allowedPrivateKeyLengths:k,nByteLength:T,wrapPrivateKey:D,n:q}=t;if(k&&typeof A!="bigint"){if(Mu(A)&&(A=qu(A)),typeof A!="string"||!k.includes(A.length))throw new Error("invalid private key");A=A.padStart(T*2,"0")}let V;try{V=typeof A=="bigint"?A:qs(or("private key",A,T))}catch{throw new Error("invalid private key, expected hex or "+T+" bytes, got "+typeof A)}return D&&(V=En(V,q)),nl("private key",V,an,q),V}function p(A){if(!(A instanceof f))throw new Error("ProjectivePoint expected")}let m=fE((A,k)=>{let{px:T,py:D,pz:q}=A;if(n.eql(q,n.ONE))return{x:T,y:D};let V=A.is0();k==null&&(k=V?n.ONE:n.inv(q));let Y=n.mul(T,k),te=n.mul(D,k),de=n.mul(q,k);if(V)return{x:n.ZERO,y:n.ZERO};if(!n.eql(de,n.ONE))throw new Error("invZ was invalid");return{x:Y,y:te}}),g=fE(A=>{if(A.is0()){if(t.allowInfinityPoint&&!n.is0(A.py))return;throw new Error("bad point: ZERO")}let{x:k,y:T}=A.toAffine();if(!n.isValid(k)||!n.isValid(T))throw new Error("bad point: x or y not FE");if(!a(k,T))throw new Error("bad point: equation left != right");if(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(k,T,D){if(k==null||!n.isValid(k))throw new Error("x required");if(T==null||!n.isValid(T)||n.is0(T))throw new Error("y required");if(D==null||!n.isValid(D))throw new Error("z required");this.px=k,this.py=T,this.pz=D,Object.freeze(this)}static fromAffine(k){let{x:T,y:D}=k||{};if(!k||!n.isValid(T)||!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(T)&&q(D)?f.ZERO:new f(T,D,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(k){let T=ER(n,k.map(D=>D.pz));return k.map((D,q)=>D.toAffine(T[q])).map(f.fromAffine)}static fromHex(k){let T=f.fromAffine(s(or("pointHex",k)));return T.assertValidity(),T}static fromPrivateKey(k){return f.BASE.multiply(d(k))}static msm(k,T){return BM(f,r,k,T)}_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:T,py:D,pz:q}=this,{px:V,py:Y,pz:te}=k,de=n.eql(n.mul(T,te),n.mul(V,q)),oe=n.eql(n.mul(D,te),n.mul(Y,q));return de&&oe}negate(){return new f(this.px,n.neg(this.py),this.pz)}double(){let{a:k,b:T}=t,D=n.mul(T,BR),{px:q,py:V,pz:Y}=this,te=n.ZERO,de=n.ZERO,oe=n.ZERO,F=n.mul(q,q),z=n.mul(V,V),_=n.mul(Y,Y),N=n.mul(q,V);return N=n.add(N,N),oe=n.mul(q,Y),oe=n.add(oe,oe),te=n.mul(k,oe),de=n.mul(D,_),de=n.add(te,de),te=n.sub(z,de),de=n.add(z,de),de=n.mul(te,de),te=n.mul(N,te),oe=n.mul(D,oe),_=n.mul(k,_),N=n.sub(F,_),N=n.mul(k,N),N=n.add(N,oe),oe=n.add(F,F),F=n.add(oe,F),F=n.add(F,_),F=n.mul(F,N),de=n.add(de,F),_=n.mul(V,Y),_=n.add(_,_),F=n.mul(_,N),te=n.sub(te,F),oe=n.mul(_,z),oe=n.add(oe,oe),oe=n.add(oe,oe),new f(te,de,oe)}add(k){p(k);let{px:T,py:D,pz:q}=this,{px:V,py:Y,pz:te}=k,de=n.ZERO,oe=n.ZERO,F=n.ZERO,z=t.a,_=n.mul(t.b,BR),N=n.mul(T,V),G=n.mul(D,Y),ne=n.mul(q,te),Z=n.add(T,D),Q=n.add(V,Y);Z=n.mul(Z,Q),Q=n.add(N,G),Z=n.sub(Z,Q),Q=n.add(T,q);let ie=n.add(V,te);return Q=n.mul(Q,ie),ie=n.add(N,ne),Q=n.sub(Q,ie),ie=n.add(D,q),de=n.add(Y,te),ie=n.mul(ie,de),de=n.add(G,ne),ie=n.sub(ie,de),F=n.mul(z,Q),de=n.mul(_,ne),F=n.add(de,F),de=n.sub(G,F),F=n.add(G,F),oe=n.mul(de,F),G=n.add(N,N),G=n.add(G,N),ne=n.mul(z,ne),Q=n.mul(_,Q),G=n.add(G,ne),ne=n.sub(N,ne),ne=n.mul(z,ne),Q=n.add(Q,ne),N=n.mul(G,Q),oe=n.add(oe,N),N=n.mul(ie,Q),de=n.mul(Z,de),de=n.sub(de,N),N=n.mul(Z,G),F=n.mul(ie,F),F=n.add(F,N),new f(de,oe,F)}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:T,n:D}=t;nl("scalar",k,Gs,D);let q=f.ZERO;if(k===Gs)return q;if(this.is0()||k===an)return this;if(!T||v.hasPrecomputes(this))return v.wNAFCachedUnsafe(this,k,f.normalizeZ);let{k1neg:V,k1:Y,k2neg:te,k2:de}=T.splitScalar(k),oe=q,F=q,z=this;for(;Y>Gs||de>Gs;)Y&an&&(oe=oe.add(z)),de&an&&(F=F.add(z)),z=z.double(),Y>>=an,de>>=an;return V&&(oe=oe.negate()),te&&(F=F.negate()),F=new f(n.mul(F.px,T.beta),F.py,F.pz),oe.add(F)}multiply(k){let{endo:T,n:D}=t;nl("scalar",k,an,D);let q,V;if(T){let{k1neg:Y,k1:te,k2neg:de,k2:oe}=T.splitScalar(k),{p:F,f:z}=this.wNAF(te),{p:_,f:N}=this.wNAF(oe);F=v.constTimeNegate(Y,F),_=v.constTimeNegate(de,_),_=new f(n.mul(_.px,T.beta),_.py,_.pz),q=F.add(_),V=z.add(N)}else{let{p:Y,f:te}=this.wNAF(k);q=Y,V=te}return f.normalizeZ([q,V])[0]}multiplyAndAddUnsafe(k,T,D){let q=f.BASE,V=(te,de)=>de===Gs||de===an||!te.equals(q)?te.multiplyUnsafe(de):te.multiply(de),Y=V(this,T).add(V(k,D));return Y.is0()?void 0:Y}toAffine(k){return m(this,k)}isTorsionFree(){let{h:k,isTorsionFree:T}=t;if(k===an)return!0;if(T)return T(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:k,clearCofactor:T}=t;return k===an?this:T?T(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=UM(f,y?Math.ceil(w/2):w);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:d,weierstrassEquation:i,isWithinCurveOrder:u}}function tQ(e){let t=DR(e);return ol(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function qM(e){let t=tQ(e),{Fp:n,n:r,nByteLength:o,nBitLength:s}=t,i=n.BYTES+1,a=2*n.BYTES+1;function l(_){return En(_,r)}function c(_){return Kb(_,r)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:p,isWithinCurveOrder:m}=eQ({...t,toBytes(_,N,G){let ne=N.toAffine(),Z=n.toBytes(ne.x),Q=th;return Fu("isCompressed",G),G?Q(Uint8Array.from([N.hasEvenY()?2:3]),Z):Q(Uint8Array.from([4]),Z,n.toBytes(ne.y))},fromBytes(_){let N=_.length,G=_[0],ne=_.subarray(1);if(N===i&&(G===2||G===3)){let Z=qs(ne);if(!db(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(ne.subarray(0,n.BYTES)),Q=n.fromBytes(ne.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(_){let N=r>>an;return _>N}function f(_){return g(_)?l(-_):_}let y=(_,N,G)=>qs(_.slice(N,G));class w{constructor(N,G,ne){nl("r",N,an,r),nl("s",G,an,r),this.r=N,this.s=G,ne!=null&&(this.recovery=ne),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:ne}=zs.toSig(or("DER",N));return new w(G,ne)}assertValidity(){}addRecoveryBit(N){return new w(this.r,this.s,N)}recoverPublicKey(N){let{r:G,s:ne,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+UR(ie,n.BYTES)),ke=c(ie),be=l(-Q*ke),qe=l(ne*ke),We=u.BASE.multiplyAndAddUnsafe(Ne,be,qe);if(!We)throw new Error("point at infinify");return We.assertValidity(),We}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,l(-this.s),this.recovery):this}toDERRawBytes(){return eh(this.toDERHex())}toDERHex(){return zs.hexFromSig(this)}toCompactRawBytes(){return eh(this.toCompactHex())}toCompactHex(){let N=o;return UR(this.r,N)+UR(this.s,N)}}let v={isValidPrivateKey(_){try{return d(_),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let _=_R(t.n);return CM(t.randomBytes(_),t.n)},precompute(_=8,N=u.BASE){return N._setWindowSize(_),N.multiply(BigInt(3)),N}};function A(_,N=!0){return u.fromPrivateKey(_).toRawBytes(N)}function k(_){if(typeof _=="bigint")return!1;if(_ instanceof u)return!0;let G=or("key",_).length,ne=n.BYTES,Z=ne+1,Q=2*ne+1;if(!(t.allowedPrivateKeyLengths||o===Z))return G===Z||G===Q}function T(_,N,G=!0){if(k(_)===!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(_)).toRawBytes(G)}let D=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let N=qs(_),G=_.length*8-s;return G>0?N>>BigInt(G):N},q=t.bits2int_modN||function(_){return l(D(_))},V=rl(s);function Y(_){return nl("num < 2^"+s,_,Gs,V),tl(_,o)}function te(_,N,G=de){if(["recovered","canonical"].some(He=>He in G))throw new Error("sign() legacy options not supported");let{hash:ne,randomBytes:Z}=t,{lowS:Q,prehash:ie,extraEntropy:me}=G;Q==null&&(Q=!0),_=or("msgHash",_),FM(G),ie&&(_=or("prehashed msgHash",ne(_)));let Ne=q(_),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=th(...be),We=Ne;function dt(He){let it=D(He);if(!m(it))return;let je=c(it),Ss=u.BASE.multiply(it).toAffine(),Mr=l(Ss.x);if(Mr===Gs)return;let _a=l(je*l(We+Mr*ke));if(_a===Gs)return;let ze=(Ss.x===Mr?0:2)|Number(Ss.y&an),vc=_a;return Q&&g(_a)&&(vc=f(_a),ze^=1),new w(Mr,vc,ze)}return{seed:qe,k2sig:dt}}let de={lowS:t.lowS,prehash:!1},oe={lowS:t.lowS,prehash:!1};function F(_,N,G=de){let{seed:ne,k2sig:Z}=te(_,N,G),Q=t;return JU(Q.hash.outputLen,Q.nByteLength,Q.hmac)(ne,Z)}u.BASE._setWindowSize(8);function z(_,N,G,ne=oe){let Z=_;N=or("msgHash",N),G=or("publicKey",G);let{lowS:Q,prehash:ie,format:me}=ne;if(FM(ne),"strict"in ne)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(ze){if(!(ze instanceof zs.Err))throw ze}!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:We,s:dt}=be,He=q(N),it=c(dt),je=l(He*it),Ss=l(We*it),Mr=u.BASE.multiplyAndAddUnsafe(qe,je,Ss)?.toAffine();return Mr?l(Mr.x)===We:!1}return{CURVE:t,getPublicKey:A,getSharedSecret:T,sign:F,verify:z,ProjectivePoint:u,Signature:w,utils:v}}var MR,zs,Gs,an,z_e,BR,Z7,HM=L(()=>{"use strict";MM();Yb();Hu();MR=class extends Error{constructor(t=""){super(t)}},zs={Err:MR,_tlv:{encode:(e,t)=>{let{Err:n}=zs;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=Zm(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let s=r>127?Zm(o.length/2|128):"";return Zm(e)+s+o+t},decode(e,t){let{Err:n}=zs,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}=zs;if(e<Gs)throw new t("integer: negative integers are not allowed");let n=Zm(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}=zs;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}=zs,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}=zs,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),z_e=BigInt(2),BR=BigInt(3),Z7=BigInt(4)});function nQ(e){return{hash:e,hmac:(t,...n)=>(0,$M.hmac)(e,t,(0,Qb.concatBytes)(...n)),randomBytes:Qb.randomBytes}}function VM(e,t){let n=r=>qM({...e,...nQ(r)});return{...n(t),create:n}}var $M,Qb,jM=L(()=>{"use strict";$M=require("@noble/hashes/hmac"),Qb=require("@noble/hashes/utils");HM();});function iQ(e){let t=KM,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,FR,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,A=xr(v,n,t)*u%t,k=xr(A,i,t)*g%t,T=xr(k,r,t)*c%t,D=xr(T,FR,t);if(!qR.eql(qR.sqr(D),e))throw new Error("Cannot find square root");return D}var GM,rQ,KM,WM,oQ,sQ,FR,zM,qR,Ar,HR=L(()=>{"use strict";GM=require("@noble/hashes/sha2"),rQ=require("@noble/hashes/utils");jM();Yb();KM=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),WM=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),oQ=BigInt(0),sQ=BigInt(1),FR=BigInt(2),zM=(e,t)=>(e+t/FR)/t;qR=Ah(KM,void 0,void 0,{sqrt:iQ}),Ar=VM({a:oQ,b:BigInt(7),Fp:qR,n:WM,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=WM,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-sQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,i=BigInt("0x100000000000000000000000000000000"),a=zM(s*e,t),l=zM(-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}}}},GM.sha256)});var YM,QM=L(()=>{"use strict";YM=!1});function XM(e,t,n={}){let{validate:r}=n;for(let o=0;;o++){let s=RE(e,zu(t,Gu(o,{size:4})),{as:"Bytes"});if(!r||r(s))return s;s.fill(0)}}var JM=L(()=>{"use strict";Xt();cl()});function ZM(e,t={}){let{path:n="m/44'/60'/0'/0/0",passphrase:r}=t,o=Gb.fromMasterSeed(cQ(e,{passphrase:r})).derive(n).privateKey;return t.as==="Bytes"?o:Ke(o)}function cQ(e,t={}){return nR(e,t.passphrase)}var e2=L(()=>{"use strict";AM();rR();Tn()});var ad={};fr(ad,{InvalidSeedSizeError:()=>Xb,createKeyPair:()=>dQ,fromMnemonic:()=>pQ,fromSeed:()=>mQ,getPublicKey:()=>n2,getSharedSecret:()=>hQ,noble:()=>t2,randomPrivateKey:()=>r2,recoverAddress:()=>o2,recoverPublicKey:()=>s2,sign:()=>fQ,verify:()=>gQ});function dQ(e={}){let{as:t="Hex"}=e,n=r2({as:t}),r=n2({privateKey:n});return{privateKey:n,publicKey:r}}function pQ(e,t={}){let{as:n="Hex",passphrase:r,path:o}=t;return ZM(e,{as:n,passphrase:r,path:o})}function mQ(e,t={}){let{as:n="Hex"}=t,r=Fn(e);if(r.length<32)throw new Xb({size:r.length});let o=XM(r,yQ,{validate:t2.utils.isValidPrivateKey});if(n==="Hex"){let s=Ke(o);return o.fill(0),s}return o}function n2(e){let{privateKey:t}=e,n=Ar.ProjectivePoint.fromPrivateKey(uo(t).slice(2));return LE(n)}function hQ(e){let{as:t="Hex",privateKey:n,publicKey:r}=e,i=Ar.ProjectivePoint.fromHex(dh(r).slice(2)).multiply(Ar.utils.normPrivateKeyToScalar(uo(n).slice(2))).toRawBytes(!0);return t==="Hex"?Ke(i):i}function r2(e={}){let{as:t="Hex"}=e,n=Ar.utils.randomPrivateKey();return t==="Hex"?Ke(n):n}function o2(e){return UE(s2(e))}function s2(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 LE(a)}function fQ(e){let{extraEntropy:t=YM,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 gQ(e){let{hash:t,payload:n}=e;return e.address?BE(e.address,o2({payload:n,signature:e.signature})):Ar.verify(e.signature,Fn(n),gB(e.publicKey),...t?[{prehash:!0,lowS:!0}]:[])}var t2,Xb,yQ,i2=L(()=>{"use strict";HR();ji();Xt();An();Tn();QM();JM();e2();Ab();t2=Ar;Xb=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"})}},yQ=qn("ox.secp256k1.fromSeed.v1")});var a2=L(()=>{"use strict"});var l2=L(()=>{"use strict";rR()});var sIe,c2=L(()=>{"use strict";Xt();sIe=qn("ox.aesGcm.fromSeed.v1")});function kQ(e,t){let{as:n}=t,r=d2(e),o=Nb(new Uint8Array(r.length));return r.encode(o),n==="Hex"?Ke(o.bytes):o.bytes}function u2(e,t={}){let{as:n="Bytes"}=t;return kQ(e,{as:n})}function d2(e){return Array.isArray(e)?xQ(e.map(t=>d2(t))):AQ(e)}function xQ(e){let t=e.reduce((o,s)=>o+s.length,0),n=p2(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 AQ(e){let t=typeof e=="string"?wt(e):e,n=p2(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 p2(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 $R=L(()=>{"use strict";Xt();An();Tn();KE()});var ow={};fr(ow,{InvalidRError:()=>Zb,InvalidSError:()=>ew,InvalidSerializedSizeError:()=>Jb,InvalidVError:()=>tw,InvalidYParityError:()=>vl,MissingPropertiesError:()=>ld,assert:()=>nw,extract:()=>TQ,from:()=>jR,fromBytes:()=>h2,fromDerBytes:()=>SQ,fromDerHex:()=>f2,fromHex:()=>VR,fromLegacy:()=>g2,fromRpc:()=>y2,fromTuple:()=>PQ,toBytes:()=>EQ,toDerBytes:()=>RQ,toDerHex:()=>_Q,toHex:()=>b2,toLegacy:()=>IQ,toRpc:()=>CQ,toTuple:()=>NQ,vToYParity:()=>rw,validate:()=>OQ,yParityToV:()=>WR});function nw(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>$E)throw new Zb({value:e.r});if(e.s<0n||e.s>$E)throw new ew({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new vl({value:e.yParity})}function h2(e){return VR(Ke(e))}function VR(e){if(e.length!==130&&e.length!==132)throw new Jb({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 rw(o)}catch{throw new vl({value:o})}})();return typeof r>"u"?{r:t,s:n}:{r:t,s:n,yParity:r}}function TQ(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return jR(e)}function jR(e){let t=typeof e=="string"?VR(e):e instanceof Uint8Array?h2(e):typeof e.r=="string"?y2(e):e.v?g2(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return nw(t),t}function SQ(e){return f2(Ke(e))}function f2(e){let{r:t,s:n}=Ar.Signature.fromDER(uo(e).slice(2));return{r:t,s:n}}function g2(e){return{r:e.r,s:e.s,yParity:rw(e.v)}}function y2(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=rw(n)),typeof r!="number")throw new vl({value:e.yParity});return r})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function PQ(e){let[t,n,r]=e;return jR({r:n==="0x"?0n:BigInt(n),s:r==="0x"?0n:BigInt(r),yParity:t==="0x"?0:Number(t)})}function EQ(e){return wt(b2(e))}function b2(e){nw(e);let t=e.r,n=e.s;return Jt(mt(t,{size:32}),mt(n,{size:32}),typeof e.yParity=="number"?mt(WR(e.yParity),{size:1}):"0x")}function RQ(e){return new Ar.Signature(e.r,e.s).toDERRawBytes()}function _Q(e){return`0x${new Ar.Signature(e.r,e.s).toDERHex()}`}function IQ(e){return{r:e.r,s:e.s,v:WR(e.yParity)}}function CQ(e){let{r:t,s:n,yParity:r}=e;return{r:mt(t,{size:32}),s:mt(n,{size:32}),yParity:r===0?"0x0":"0x1"}}function NQ(e){let{r:t,s:n,yParity:r}=e;return[r?"0x01":"0x",t===0n?"0x":ch(mt(t)),n===0n?"0x":ch(mt(n))]}function OQ(e,t={}){try{return nw(e,t),!0}catch{return!1}}function rw(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 tw({value:e})}function WR(e){if(e===0)return 27;if(e===1)return 28;throw new vl({value:e})}var Jb,ld,Zb,ew,vl,tw,w2=L(()=>{"use strict";HR();Xt();An();Tn();il();Zu();Jb=class extends le{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${rt(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"})}},Zb=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"})}},ew=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"})}},vl=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"})}},tw=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 v2=L(()=>{"use strict"});var k2=L(()=>{"use strict"});var x2=L(()=>{"use strict"});var aIe,lIe,A2=L(()=>{"use strict";aIe=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),lIe={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var T2=L(()=>{"use strict"});var FQ,S2=L(()=>{"use strict";FQ=require("@noble/hashes/blake3")});var P2=L(()=>{"use strict"});var E2,$Q,R2,VQ,cIe,_2=L(()=>{"use strict";E2=6,$Q=32,R2=4096,VQ=$Q*R2,cIe=VQ*E2-1-1*R2*E2});var I2=L(()=>{"use strict"});var C2=L(()=>{"use strict"});var N2=L(()=>{"use strict"});var O2=L(()=>{"use strict"});var L2=L(()=>{"use strict"});var D2=L(()=>{"use strict"});var U2=L(()=>{"use strict"});var B2=L(()=>{"use strict"});var M2=L(()=>{"use strict"});function es(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 es.number(e);if(typeof e=="bigint")throw new QR;if(typeof e=="string")return es.string(e);if(Array.isArray(e))return es.array(e);if(e instanceof Uint8Array)return es.byteString(e);if(e instanceof ArrayBuffer)return es.byteString(new Uint8Array(e));if(ArrayBuffer.isView(e))return es.byteString(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(e instanceof Map)return es.map(e);if(typeof e=="object")return es.object(e);throw new XR({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 KR({tag:r});case 7:return Ks.readSimpleOrFloat(e,r);default:throw new zR({majorType:n})}}var zR,sw,GR,KR,iw,YR,QR,XR,aw,JR,ZR,lw,e_,F2=L(()=>{"use strict";Xt();An();zR=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"})}},sw=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"})}},GR=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"})}},KR=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"})}},iw=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"})}},YR=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"})}},QR=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"})}},XR=class extends le{constructor({token:t}){super(`Unexpected token: ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cbor.UnexpectedTokenError"})}},aw=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"})}},JR=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"})}},ZR=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"})}},lw=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"})}},e_=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 aw({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 aw({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 JR({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 ZR({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 e_({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 lw({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 lw({size:u})}e.map=i})(es||(es={}));(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 GR:new sw({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 iw({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 iw({type:"text string"});g.push(y)}return g.join("")}let p=t(u,d),m=u.readBytes(p);return uh(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 YR({value:p});return}throw new sw({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 q2=L(()=>{"use strict"});var ho={};fr(ho,{from:()=>nX,fromCreate:()=>H2,fromCreate2:()=>$2});function nX(e){return e.salt?$2(e):H2(e)}function H2(e){let t=wt(dl(e.from)),n=Gu(e.nonce);return n[0]===0&&(n=new Uint8Array([])),dl(`0x${sn(u2([t,n],{as:"Hex"})).slice(26)}`)}function $2(e){let t=wt(dl(e.from)),n=bb(Ku(e.salt)?e.salt:wt(e.salt),32),r="bytecodeHash"in e?Ku(e.bytecodeHash)?e.bytecodeHash:wt(e.bytecodeHash):sn(e.bytecode,{as:"Bytes"});return dl($t(sn(zu(wt("0xff"),t,n,r),{as:"Hex"}),12))}var V2=L(()=>{"use strict";ji();Xt();cl();Tn();$R()});var j2=L(()=>{"use strict"});var uIe,W2=L(()=>{"use strict";Xt();uIe=qn("ox.ed25519.fromSeed.v1")});var sX,iX,aX,lX,z2,G2,K2,cX,uX,dIe,pIe,mIe,hIe,Y2=L(()=>{"use strict";sX=44032,iX=4352,aX=4449,lX=4519,z2=19,G2=21,K2=28,cX=G2*K2,uX=z2*cX,dIe=sX+uX,pIe=iX+z2,mIe=aX+G2,hIe=lX+K2});var Q2=L(()=>{"use strict";Y2()});var X2=L(()=>{"use strict"});var J2=L(()=>{"use strict"});var Z2=L(()=>{"use strict"});var eF=L(()=>{"use strict"});var tF,nF,fX,rF=L(()=>{"use strict";tF=require("@noble/hashes/pbkdf2"),nF=require("@noble/hashes/scrypt"),fX=require("@noble/hashes/sha2")});var oF=L(()=>{"use strict"});var bIe,sF=L(()=>{"use strict";Xt();bIe=qn("ox.p256.fromSeed.v1")});var iF=L(()=>{"use strict"});var lF=oz((wIe,t_)=>{"use strict";var vX=Object.prototype.hasOwnProperty,Vn="~";function Th(){}Object.create&&(Th.prototype=Object.create(null),new Th().__proto__||(Vn=!1));function kX(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function aF(e,t,n,r,o){if(typeof n!="function")throw new TypeError("The listener must be a function");var s=new kX(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 cw(e,t){--e._eventsCount===0?e._events=new Th:delete e._events[t]}function _n(){this._events=new Th,this._eventsCount=0}_n.prototype.eventNames=function(){var t=[],n,r;if(this._eventsCount===0)return t;for(r in n=this._events)vX.call(n,r)&&t.push(Vn?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(n)):t};_n.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};_n.prototype.listenerCount=function(t){var n=Vn?Vn+t:t,r=this._events[n];return r?r.fn?1:r.length:0};_n.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};_n.prototype.on=function(t,n,r){return aF(this,t,n,r,!1)};_n.prototype.once=function(t,n,r){return aF(this,t,n,r,!0)};_n.prototype.removeListener=function(t,n,r,o){var s=Vn?Vn+t:t;if(!this._events[s])return this;if(!n)return cw(this,s),this;var i=this._events[s];if(i.fn)i.fn===n&&(!o||i.once)&&(!r||i.context===r)&&cw(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:cw(this,s)}return this};_n.prototype.removeAllListeners=function(t){var n;return t?(n=Vn?Vn+t:t,this._events[n]&&cw(this,n)):(this._events=new Th,this._eventsCount=0),this};_n.prototype.off=_n.prototype.removeListener;_n.prototype.addListener=_n.prototype.on;_n.prefixed=Vn;_n.EventEmitter=_n;typeof t_<"u"&&(t_.exports=_n)});var cF,uF=L(()=>{"use strict";cF=jL(lF(),1)});var ir,n_,r_,o_,s_,i_,a_,l_,c_,u_,d_,p_,m_,dF=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??""}},n_=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(n_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});r_=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(r_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});o_=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(o_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});s_=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(s_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});i_=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(i_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});a_=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(a_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});l_=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(l_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});c_=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(c_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});u_=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(u_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});d_=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(d_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});p_=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(p_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});m_=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(m_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700})});var jn,h_,f_,g_,y_,b_,w_,v_,k_,x_,A_,T_,S_,P_,pF=L(()=>{"use strict";uF();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}},h_=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(h_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});f_=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(f_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});g_=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(g_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});y_=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(y_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});b_=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(b_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});w_=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(w_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});v_=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(v_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});k_=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(k_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});x_=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(x_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});A_=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(A_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});T_=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(T_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});S_=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(S_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});P_=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(P_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760})});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 wF=L(()=>{"use strict"});var vF=L(()=>{"use strict"});var kF=L(()=>{"use strict"});var xF=L(()=>{"use strict"});var AF=L(()=>{"use strict"});var TF=L(()=>{"use strict"});var SF=L(()=>{"use strict"});var PF=L(()=>{"use strict"});var EF=L(()=>{"use strict"});var fo={};fr(fo,{BytesSizeMismatchError:()=>uw,InvalidDomainError:()=>dw,InvalidPrimaryTypeError:()=>pw,InvalidStructTypeError:()=>mw,assert:()=>E_,domainSeparator:()=>FX,encode:()=>RF,encodeData:()=>I_,encodeField:()=>C_,encodeType:()=>_F,extractEip712DomainTypes:()=>hw,findTypeDependencies:()=>N_,getSignPayload:()=>qX,hashDomain:()=>R_,hashStruct:()=>__,hashType:()=>IF,serialize:()=>HX,validate:()=>$X});function E_(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;mt(d,{signed:f==="int",size:Number.parseInt(y??"",10)/8})}if(u==="address"&&typeof d=="string"&&!pl(d))throw new ul({address:d,cause:new Yu});let m=u.match(Rb);if(m){let[,f]=m;if(f&&rt(d)!==Number.parseInt(f,10))throw new uw({expectedSize:Number.parseInt(f,10),givenSize:rt(d)})}let g=o[u];g&&(VX(u),s(g,d))}};if(o.EIP712Domain&&t){if(typeof t!="object")throw new dw({domain:t});s(o.EIP712Domain,t)}if(r!=="EIP712Domain")if(o[r])s(o[r],n);else throw new pw({primaryType:r,types:o})}function FX(e){return R_({domain:e})}function RF(e){let{domain:t={},message:n,primaryType:r}=e,o={EIP712Domain:hw(t),...e.types};E_({domain:t,message:n,primaryType:r,types:o});let s=["0x19","0x01"];return t&&s.push(R_({domain:t,types:o})),r!=="EIP712Domain"&&s.push(__({data:n,primaryType:r,types:o})),Jt(...s)}function _F(e){let{primaryType:t,types:n}=e,r="",o=N_({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 hw(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 qX(e){return sn(RF(e))}function R_(e){let{domain:t,types:n}=e;return __({data:t,primaryType:"EIP712Domain",types:{...n,EIP712Domain:n?.EIP712Domain||hw(t)}})}function __(e){let{data:t,primaryType:n,types:r}=e,o=I_({data:t,primaryType:n,types:r});return sn(o)}function HX(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??hw(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 $X(e){try{return E_(e),!0}catch{return!1}}function I_(e){let{data:t,primaryType:n,types:r}=e,o=[{type:"bytes32"}],s=[IF({primaryType:n,types:r})];for(let i of r[n]??[]){let[a,l]=C_({types:r,name:i.name,type:i.type,value:t[i.name]});o.push(a),s.push(l)}return fl(o,s)}function IF(e){let{primaryType:t,types:n}=e,r=Vs(_F({primaryType:t,types:n}));return sn(r)}function C_(e){let{types:t,name:n,type:r,value:o}=e;if(t[r]!==void 0)return[{type:"bytes32"},sn(I_({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=>C_({name:n,type:s,types:t,value:a}));return[{type:"bytes32"},sn(fl(i.map(([a])=>a),i.map(([,a])=>a)))]}return[{type:r},o]}function N_(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])N_({primaryType:i.type,types:r},t);return t}function VX(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new mw({type:e})}var uw,dw,pw,mw,CF=L(()=>{"use strict";gh();ji();Xt();An();cl();Tn();il();Zu();uw=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"})}},dw=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"})}},pw=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"})}},mw=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 NF=L(()=>{"use strict"});var OF=L(()=>{"use strict"});var LF=L(()=>{"use strict"});var DF=L(()=>{"use strict"});var fw=L(()=>{"use strict";HU();SB();PB();EB();_B();HE();gh();IB();CB();ji();c2();v2();k2();x2();A2();T2();S2();_2();L2();D2();U2();B2();M2();Xt();_E();F2();q2();V2();j2();W2();Q2();An();X2();J2();I2();Z2();eF();C2();cl();a2();Tn();il();rF();P2();oF();l2();sF();iF();pF();Ab();$R();mF();dF();hF();fF();i2();w2();gF();Zu();yF();N2();bF();wF();kF();xF();AF();TF();SF();PF();EF();CF();NF();vF();OF();LF();O2();DF()});function kl(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 QF(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 ns(e){return this instanceof ns?(this.v=e,this):new ns(e)}function XF(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 ns?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 AJ(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:ns(e[o](i)),done:!1}:s?s(i):i}:s}}function TJ(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 QF=="function"?QF(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 xl(e){return new In(Promise.resolve(new Tr(e)))}function go(e){return new Gr(e)}function Sr(e){return new Tr(e)}var xJ,JF,In,HIe,$Ie,VIe,ZF,SJ,eq,PJ,q_,Gr,Tr,jIe,H_=L(()=>{"use strict";xJ={withStackTrace:!1},JF=(e,t,n=xJ)=>{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}};In=class e{constructor(t){this._promise=t}static fromSafePromise(t){let n=t.then(r=>new Gr(r));return new e(n)}static fromPromise(t,n){let r=t.then(o=>new Gr(o)).catch(o=>new Tr(n(o)));return new e(r)}static fromThrowable(t,n){return(...r)=>new e(kl(this,void 0,void 0,function*(){try{return new Gr(yield t(...r))}catch(o){return new Tr(n?n(o):o)}}))}static combine(t){return SJ(t)}static combineWithAllErrors(t){return PJ(t)}map(t){return new e(this._promise.then(n=>kl(this,void 0,void 0,function*(){return n.isErr()?new Tr(n.error):new Gr(yield t(n.value))})))}andThrough(t){return new e(this._promise.then(n=>kl(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 Gr(n.value)})))}andTee(t){return new e(this._promise.then(n=>kl(this,void 0,void 0,function*(){if(n.isErr())return new Tr(n.error);try{yield t(n.value)}catch{}return new Gr(n.value)})))}orTee(t){return new e(this._promise.then(n=>kl(this,void 0,void 0,function*(){if(n.isOk())return new Gr(n.value);try{yield t(n.error)}catch{}return new Tr(n.error)})))}mapErr(t){return new e(this._promise.then(n=>kl(this,void 0,void 0,function*(){return n.isOk()?new Gr(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=>kl(this,void 0,void 0,function*(){return n.isErr()?t(n.error):new Gr(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 XF(this,arguments,function*(){return yield ns(yield ns(yield*AJ(TJ(yield ns(this._promise.then(n=>n.safeUnwrap()))))))})}then(t,n){return this._promise.then(t,n)}[Symbol.asyncIterator](){return XF(this,arguments,function*(){let n=yield ns(this._promise);return n.isErr()&&(yield yield ns(xl(n.error))),yield ns(n.value)})}};HIe=In.fromPromise,$Ie=In.fromSafePromise,VIe=In.fromThrowable,ZF=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},SJ=e=>In.fromSafePromise(Promise.all(e)).andThen(ZF),eq=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},PJ=e=>In.fromSafePromise(Promise.all(e)).andThen(eq);(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 ZF(o)}e.combine=n;function r(o){return eq(o)}e.combineWithAllErrors=r})(q_||(q_={}));Gr=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 In.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 JF("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 xl(this.error)}asyncAndThrough(t){return xl(this.error)}asyncMap(t){return xl(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 JF("Called `_unsafeUnwrap` on an Err",this,t)}_unsafeUnwrapErr(t){return this.error}*[Symbol.iterator](){let t=this;return yield t,t}},jIe=q_.fromThrowable});function EJ(e){return e==null}function Kr(e){return!EJ(e)}function fe(e,t){if(!e)throw new rq(t)}function oq(e="Unexpected call to never()"){throw new rq(e)}function os(e){return new Promise(t=>setTimeout(t,e))}function sq(e){let t=e.unref;typeof t=="function"&&t.call(e)}function ud(e,t){let n=setInterval(e,t);return sq(n),n}function yn(e,t){let n=setTimeout(e,t);return sq(n),n}function ln(e){return typeof e=="string"&&/^0x[a-fA-F0-9]+$/.test(e)}function zt(e,t){return e.toLowerCase()===t.toLowerCase()}function $_(e){return ln(e)&&e.length===66}function Qs(e,t="Expected value to be present"){return fe(e!=null,t),e}function iq(e,t="Expected a non-empty array"){return fe(e.length>0,t),e}function Wn(e,t="Expected a hex string"){return fe(ln(e),t),e}function aq(e,t="Expected a private key"){return fe($_(e),t),e}function Be(e,t="Expected an EVM address"){return fe(ln(e)&&e.length===42,t),e}function ss(e,t="Expected an EVM signature"){return fe(ln(e)&&e.length===132,t),e}function lq(e,t="Expected an ERC-1271 signature payload"){return fe(ln(e),t),e}function cq(e,t="Expected a session-signer signature envelope"){return fe(ln(e),t),e}function tq(e){throw e}function X(e){return e instanceof In?e.match(t=>t,tq):e.match(t=>t,tq)}var rs,Ct,rq,Al=L(()=>{"use strict";H_();H_();rs="0x0000000000000000000000000000000000000000",Ct=class nq extends Error{static isError(t){return t instanceof nq}},rq=class extends Ct{name="InvariantError"}});function dd(e){if(!Number.isInteger(e))throw new TypeError(`Expected an integer, received: ${e}`);return e}function j_(e){return e}function xw(e){if(!ln(e)||e.length!==66)throw new TypeError(`Expected a 32-byte hex string, received: ${e}`);return e}function uq(e){return e}function dq(e){return e}function W_(e){return e}function pq(e){return e}function mq(e){return e}function hq(e){return e}function Oh(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 V_(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 z_(e){let t=V_(e);if(t!==void 0)return t;throw new TypeError(`Expected a protocol v2 combo condition ID, received: ${e}`)}function G_(e){return e}function K_(e){return e}function Y_(e){return dd(e)}function pd(e){return dd(e)}function Q_(e){return e}function fq(e){return e}function gq(e){return e}function yq(e){return e}function X_(e){return e}function bq(e){return e}function Aw(e){return e}function wq(e){return dd(e)}function vq(e){return e}function J_(e){return dd(e)}function Tw(e){return e}function kq(e){return IJ(e)}function md(e){return e}function Sw(e){return e}function xq(e){return e}function Z_(e){return e}function eI(e){return dd(e)}function Aq(e){return e}function tI(e){return dd(e)}function nI(e){return e}function Tq(e){return e}function Sq(e){return e}function Lh(e){return e}function Tl(e){return e}function Gn(e){return e===""?null:e}function gd(e){return e===""?void 0:e}function _J(e){return e}function IJ(e){if(!ln(e)||e.length!==66)throw new TypeError(`Expected a 32-byte hex string, received: ${e}`);return e}var ue,Ch,Ue,cn,Ki,yo,Nh,rI,is,bo,oI,Xs,sI,Zt,xe,Dh,J,pe,wo,Pw,Ew,Pr,hd,Yi,RJ,iI,un,Gt,Sl,re,zn,aI,lI,cI,Qi,uI,Js,fd,Nt,Uh,Bh,ye,Xe,Me,vo,dI,ar,Xi,Rw,Mh,_w,Ji,et,R,bn,H,ko,as,dn,xo=L(()=>{"use strict";Al();ue=require("zod"),Ch=(e=>(e.Event="Event",e.Series="Series",e))(Ch||{}),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||{}),Ki=(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))(Ki||{}),yo=(e=>(e.ALL="ALL",e.CLOB="CLOB",e.COMBOSRFQ="COMBOSRFQ",e))(yo||{}),Nh=ue.z.string().min(1).transform(e=>e);rI=ue.z.string().transform(dq),is=ue.z.string().transform(uq),bo=ue.z.string().transform(xw),oI=ue.z.string().transform(pq),Xs=ue.z.string().transform(mq),sI=ue.z.string().transform(hq),Zt=ue.z.string().refine(e=>V_(e)!==void 0,"Expected a protocol v2 combo condition ID").transform(e=>V_(e)),xe=ue.z.string().refine(e=>ln(e)&&(e.length===64||e.length===66),"Expected a 31-byte or 32-byte hex string").transform(e=>e),Dh=ue.z.custom(ln,"Expected a hex-encoded market condition ID"),J=ue.z.string().refine(e=>ln(e)&&e.length===42,"Expected an EVM address").transform(_J),pe=ue.z.number().int().transform(pd),wo=ue.z.number().int().transform(e=>pd(e*1e3)),Pw=ue.z.union([ue.z.number().int(),ue.z.string().regex(/^\d+$/).transform(Number)]),Ew=ue.z.string().transform(e=>/^\d{4}-\d{2}-\d{2}$/.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString():e),Pr=ue.z.string().regex(/^\d+$/).transform(e=>pd(Number(e))),hd=ue.z.union([Pw.transform(e=>new Date(e).toISOString()),Ew]),Yi=ue.z.union([Pw.transform(e=>new Date(e<1e12?e*1e3:e).toISOString()),Ew]),RJ=ue.z.union([Pw.transform(e=>e===0?void 0:new Date(e).toISOString()),Ew]),iI=ue.z.union([Pw.transform(e=>e===0?void 0:new Date(e<1e12?e*1e3:e).toISOString()),Ew]),un=hd,Gt=ue.z.union([ue.z.string(),ue.z.number().int().transform(String)]).transform(Q_),Sl=ue.z.union([ue.z.literal(.1),ue.z.literal(.01),ue.z.literal(.005),ue.z.literal(.0025),ue.z.literal(.001),ue.z.literal(1e-4)]),re=ue.z.string().transform(X_).or(ue.z.date().transform(e=>e.toISOString())),zn=ue.z.string().transform(yq).or(ue.z.date().transform(e=>e.toISOString().slice(0,10))),aI=ue.z.string().transform(bq),lI=ue.z.string().transform(fq),cI=ue.z.string().transform(gq),Qi=ue.z.string().transform(Aw),uI=ue.z.number().int().transform(wq),Js=ue.z.enum(Ch),fd=ue.z.string().transform(vq),Nt=ue.z.enum(Ue),Uh=ue.z.enum(cn),Bh=ue.z.preprocess(e=>typeof e!="string"||e.startsWith("TRADE_STATUS_")?e:Object.values(Ki).find(t=>t.slice(13)===e)??e,ue.z.enum(Ki)),ye=ue.z.custom(e=>typeof e=="string"&&e.length>0,"Expected a non-empty pagination cursor"),Xe=ue.z.string().transform(Tw),Me=ue.z.string().transform(e=>e),vo=ue.z.string().refine(e=>ln(e)&&e.length===66,"Expected a 32-byte hex string").transform(e=>e),dI=ue.z.string().transform(kq),ar=ue.z.string().transform(md),Xi=ue.z.string().transform(Sw),Rw=ue.z.string().transform(xq),Mh=ue.z.string().transform(Aq),_w=ue.z.string().transform(Sq),Ji=ue.z.string().min(1).transform(Tq),et=ue.z.string().refine(e=>ln(e)&&e.length===66,"Expected a transaction hash").transform(e=>e),R=ue.z.string().transform(Lh),bn=ue.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=ue.z.union([R,ue.z.number().transform(e=>String(e))]),ko=ue.z.union([ue.z.number(),ue.z.string().transform(Number)]).pipe(ue.z.number().positive()),as=ue.z.string().transform(Tl);dn=ue.z.preprocess(Gn,R.nullish())});function Ow(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:$J(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 Fh(e){return e??null}function Lw(e){return typeof e=="string"?JSON.parse(e):e}function qh(e){return e.outcomes.length===2}function $J(e){if(!qh(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 nZ(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,CJ,Zs,Pq,NJ,Eq,Pl,Rq,_q,pI,OJ,LJ,DJ,UJ,BJ,Iw,MJ,Zi,FJ,mI,qJ,Cw,Nw,Iq,HJ,hI,fI,VJ,jJ,WJ,zJ,GJ,KJ,Cq,Hh,YJ,QJ,XJ,JJ,Dw,Uw,Bw,Nq,Oq,Lq,Dq,Uq,$h,gI,yI,bI,wI,vI,ZJ,eZ,Bq,ei,tZ,kI,xI,Mq,El,AI,Fq,yd,Mw,Vh,jh,TI,Wh=L(()=>{"use strict";xo();b=require("zod"),CJ=b.z.preprocess(e=>e===""?void 0:e,Dh.optional()),Zs=b.z.object({id:lI,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:re.nullish(),relID:b.z.number().int().nullish(),field:b.z.string().nullish(),relname:b.z.string().nullish()}),Pq=b.z.object({exponent:b.z.number(),rate:H,takerOnly:b.z.boolean(),rebateRate:H}),NJ=b.z.object({id:Gt}),Eq=b.z.object({id:rI,label:b.z.string().nullish(),parentCategory:b.z.string().nullish(),slug:b.z.string().nullish(),publishedAt:re.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.nullish()}),Pl=b.z.object({id:Mh,label:b.z.string().nullish(),slug:b.z.string().nullish(),forceShow:b.z.boolean().nullish(),publishedAt:re.nullish(),createdBy:b.z.number().int().nullish(),updatedBy:b.z.number().int().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),forceHide:b.z.boolean().nullish(),isCarousel:b.z.boolean().nullish(),activeEventsCount:b.z.number().int().nullish()}),Rq=b.z.object({id:Qi,conditionId:CJ,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:re.nullish(),eventSlug:b.z.string().nullish()}),_q=b.z.object({id:oI,conditionId:Dh,assetAddress:b.z.string(),rewardsAmount:H,rewardsDailyRate:H,startDate:zn,endDate:zn.nullish()}),pI=b.z.object({id:cI,username:b.z.string().nullish()}),OJ=b.z.object({id:Gt,slug:b.z.string().nullish(),title:b.z.string().nullish()}),LJ=b.z.preprocess(Lw,b.z.array(b.z.string()).nullish()).transform(e=>e??[]),DJ=b.z.preprocess(Lw,b.z.array(R).nullish()).transform(e=>e??[]),UJ=b.z.preprocess(Lw,b.z.array(_w).nullish()).transform(e=>e??[]),BJ=b.z.preprocess(Lw,b.z.array(Xe).nullish()).transform(e=>e??[]),Iw=(e=>(e.Pending="pending",e.Enabled="enabled",e.Disabled="disabled",e))(Iw||{}),MJ=b.z.string().transform(e=>e),Zi=(e=>(e.V1="v1",e.V2="v2",e))(Zi||{}),FJ=b.z.enum(Zi),mI=(e=>(e.Disputed="disputed",e.Proposed="proposed",e.Requested="requested",e.Resolved="resolved",e.Settled="settled",e))(mI||{}),qJ=b.z.enum(mI),Cw=b.z.object({id:Qi,version:FJ.nullish(),question:b.z.string().nullish(),conditionId:b.z.preprocess(Gn,Dh.nullish()).transform(Fh),slug:b.z.string().nullish(),twitterCardImage:b.z.string().nullish(),resolutionSource:b.z.string().nullish(),endDate:re.nullish(),category:b.z.string().nullish(),liquidity:R.nullish(),sponsorName:b.z.string().nullish(),sponsorImage:b.z.string().nullish(),startDate:re.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:LJ,outcomePrices:DJ,volume:R.nullish(),active:b.z.boolean().nullish(),marketType:b.z.string().nullish(),formatType:b.z.string().nullish(),lowerBoundDate:zn.nullish(),upperBoundDate:zn.nullish(),closed:b.z.boolean().nullish(),createdBy:b.z.number().int().nullish(),updatedBy:b.z.number().int().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),closedTime:re.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:re.nullish(),twitterCardLastValidated:re.nullish(),archived:b.z.boolean().nullish(),resolvedBy:b.z.preprocess(Gn,J.nullish()).transform(Fh),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(Fh),umaEndDate:aI.nullish(),enableOrderBook:b.z.boolean().nullish(),orderPriceMinTickSize:Sl.nullish(),orderMinSize:H.nullish(),umaResolutionStatus:b.z.preprocess(Gn,qJ.nullish()).transform(Fh),curationOrder:b.z.number().int().nullish(),volumeNum:H.nullish(),liquidityNum:H.nullish(),endDateIso:zn.nullish(),startDateIso:zn.nullish(),umaEndDateIso:zn.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:re.nullish(),secondsDelay:b.z.number().int().nullish(),clobTokenIds:UJ,comboStatus:MJ.nullish(),positionIds:BJ,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,dI.nullish()).transform(Fh),notificationsEnabled:b.z.boolean().nullish(),score:b.z.number().int().nullish(),imageOptimized:Zs.nullish(),iconOptimized:Zs.nullish(),events:b.z.array(OJ).nullish(),categories:b.z.array(b.z.unknown()).nullish(),markets:b.z.array(Rq).nullish(),creator:b.z.string().nullish(),ready:b.z.boolean().nullish(),funded:b.z.boolean().nullish(),pastSlugs:b.z.string().nullish(),readyTimestamp:re.nullish(),fundedTimestamp:re.nullish(),acceptingOrdersTimestamp:re.nullish(),tags:b.z.array(Pl).nullish(),cyom:b.z.boolean().nullish(),competitive:b.z.number().nullish(),approved:b.z.boolean().nullish(),clobRewards:b.z.array(_q).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:re.nullish(),scheduledDeploymentTimestamp:re.nullish(),rfqEnabled:b.z.boolean().nullish(),eventStartTime:re.nullish(),internalUsers:b.z.array(pI).nullish(),holdingRewardsEnabled:b.z.boolean().nullish(),feesEnabled:b.z.boolean().nullish(),makerRebatesFeeShareBps:b.z.number().nullish(),feeType:b.z.string().nullish(),feeSchedule:Pq.nullish()}),Nw=Cw.transform((e,t)=>qh(e)?Ow(e):(t.addIssue({code:"custom",message:`Expected binary market outcomes, received ${e.outcomes.length}`}),b.z.NEVER)),Iq=Cw.transform(e=>qh(e)?Ow(e):null),HJ=b.z.array(Iq).transform(e=>e.filter(t=>t!==null)),hI=b.z.object({markets:b.z.array(Iq),next_cursor:ye.optional()}).transform(({markets:e,next_cursor:t})=>({items:e.filter(n=>n!==null),nextCursor:t})),fI=b.z.array(Pl);VJ=b.z.string().transform(j_),jJ=b.z.string().transform(W_),WJ=b.z.string().transform(G_),zJ=b.z.string().transform(K_),GJ=b.z.number().int().transform(Y_),KJ=b.z.union([Gt,b.z.number().int().transform(e=>String(e))]),Cq=b.z.number().int().transform(J_),Hh=b.z.union([b.z.string(),b.z.number().int().transform(String)]).transform(Z_),YJ=b.z.number().int().transform(eI),QJ=b.z.number().int().transform(tI),XJ=b.z.string().transform(nI),JJ=b.z.enum(Zi),Dw=b.z.object({id:WJ,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:re.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),disqusThread:b.z.string().nullish(),commentsEnabled:b.z.boolean().nullish()}),Uw=b.z.object({id:Hh,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:re.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),commentsEnabled:b.z.boolean().nullish(),competitive:b.z.string().nullish(),volume24hr:H.nullish(),volume:H.nullish(),liquidity:H.nullish(),startDate:re.nullish(),pythTokenID:b.z.string().nullish(),cgAssetName:b.z.string().nullish(),score:b.z.number().int().nullish(),commentCount:b.z.number().int().nullish()}),Bw=b.z.object({id:XJ,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:re.nullish(),updatedAt:re.nullish()}),Nq=b.z.object({id:jJ,channelId:b.z.string().nullish(),channelName:b.z.string().nullish(),channelImage:b.z.string().nullish(),live:b.z.boolean().nullish(),startTime:re.nullish(),endTime:re.nullish()}),Oq=b.z.object({id:zJ,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:re.nullish(),updatedAt:re.nullish()}),Lq=b.z.object({id:Cq,slug:b.z.string(),name:b.z.string(),createdAt:re.nullish(),updatedAt:re.nullish()}),Dq=b.z.object({id:GJ,eventId:KJ,partnerId:Cq,externalId:b.z.string(),partner:Lq.nullish(),createdAt:re.nullish(),updatedAt:re.nullish()}),Uq=b.z.object({id:VJ,lineType:b.z.string().nullish(),line:b.z.number().nullish()}),$h=(e=>(e.Home="home",e.Away="away",e))($h||{}),gI=b.z.object({id:QJ,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:re.nullish(),updatedAt:re.nullish(),providerId:b.z.number().int().nullish(),color:b.z.string().nullish(),ordering:b.z.enum($h).nullish()}),yI=b.z.object({id:YJ,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:re.nullish(),updatedAt:re.nullish()}),bI=b.z.array(gI),wI=b.z.array(yI),vI=b.z.object({marketTypes:b.z.array(b.z.string()).nullish()}),ZJ=Cw.transform(e=>qh(e)?Ow(e):null),eZ=b.z.array(ZJ).transform(e=>e.filter(t=>t!==null)),Bq=b.z.object({id:Gt,version:JJ.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:re.nullish(),creationDate:re.nullish(),endDate:re.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:re.nullish(),createdBy:b.z.string().nullish(),updatedBy:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.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:eZ.nullish(),series:b.z.array(Uw).nullish(),categories:b.z.array(Eq).nullish(),collections:b.z.array(Dw).nullish(),tags:b.z.array(Pl).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:re.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:zn.nullish(),startTime:re.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:re.nullish(),gmpChartMode:b.z.string().nullish(),eventCreators:b.z.array(Oq).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(Nq).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(Bw).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:re.nullish(),scheduledDeploymentTimestamp:re.nullish(),gameStatus:b.z.string().nullish(),internalUsers:b.z.array(pI).nullish(),gameId:b.z.number().int().nullish(),rescheduledFromGameId:b.z.number().int().nullish(),sportsradarMatchId:b.z.string().nullish(),bestLines:b.z.array(Uq).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:re.nullish(),eventMetadata:b.z.record(b.z.string(),b.z.unknown()).nullish(),teams:b.z.array(gI).nullish(),sport:yI.nullish(),externalPartners:b.z.array(Dq).nullish()}),ei=Bq.transform(nZ),tZ=b.z.array(ei),kI=b.z.object({events:b.z.array(ei),next_cursor:ye.optional()}).transform(({events:e,next_cursor:t})=>({items:e,nextCursor:t})),xI=b.z.array(Pl);Mq=b.z.object({tokenId:_w.nullish(),positionSize:as.nullish()}),El=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(Mq).nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),AI=(e=>(e.Heart="HEART",e))(AI||{}),Fq=b.z.enum(AI),yd=b.z.object({id:b.z.string(),commentID:b.z.number().int().nullish(),reactionType:Fq.nullish(),icon:b.z.string().nullish(),userAddress:b.z.string().nullish(),createdAt:re.nullish(),profile:El.nullish()}),Mw=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:re.nullish()}),Vh=b.z.object({id:Xs,body:b.z.string().nullish(),parentEntityType:Js.nullish(),parentEntityID:b.z.union([Gt,Hh]).nullish(),parentCommentID:Xs.nullish(),userAddress:b.z.string().nullish(),replyAddress:b.z.string().nullish(),createdAt:re.nullish(),updatedAt:re.nullish(),media:b.z.array(Mw).nullish(),profile:El.nullish(),reactions:b.z.array(yd).nullish(),reportCount:b.z.number().int().nullish(),reactionCount:b.z.number().int().nullish(),tradeAsset:b.z.string().nullish()}),jh=b.z.array(Vh),TI=b.z.object({comments:b.z.array(Vh),next_cursor:ye.optional()}).transform(({comments:e,next_cursor:t})=>({items:e,nextCursor:t}))});function Rl(e){return e}function vH(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 AH(e){return e??"Perps command was rejected."}var P,Ae,Cn,Er,_l,qq,ea,SI,Fw,PI,Hq,$q,Ao,Gh,Kh,Yh,ti,ta,vd,Qh,qw,Hw,Xh,Jh,EI,Zh,RI,ef,ni,_I,Vq,jq,kd,xd,Wq,zq,$w,Vw,II,Kn,Il,To,jw,CI,Gq,NI,Kq,rZ,oZ,Ww,OI,Yq,LI,DI,Qq,UI,Xq,BI,Jq,MI,sZ,Zq,FI,qI,HI,Yr,wd,Ad,tf,zw,$I,nf,Gw,VI,iZ,jI,eH,WI,tH,zI,GI,nH,KI,YI,QI,rH,XI,JI,aZ,lZ,oH,ZI,sH,eC,tC,Td,iH,nC,rC,zh,oC,sC,cZ,iC,aH,aC,lC,lH,cC,cH,uH,dH,uC,dC,rf,pH,of,pC,sf,mH,hH,fH,gH,uZ,dZ,yH,bH,Kw,wH,pZ,mZ,mC,hC,fC,bd,af,gC,yC,kH,Sd,xH,hZ,lf,cf,Yw,bC,wC,vC,kC,xC,AC,TH,TC,SC,PC=L(()=>{"use strict";xo();P=require("zod");Ae=P.z.number().int().nonnegative().transform(Rl),Cn=P.z.number().int().nonnegative().transform(Rl),Er=P.z.string().regex(/^[0-9a-f]{32}$/).transform(e=>e),_l=P.z.uuid().transform(e=>e),qq=P.z.string().min(1).transform(e=>e),ea=P.z.number().int().nonnegative().transform(Rl),SI=P.z.number().int().nonnegative().transform(Rl),Fw=P.z.number().int().nonnegative().transform(Rl),PI=P.z.number().int().nonnegative().transform(Rl),Hq=P.z.number().int().positive().transform(Rl),$q=P.z.string().regex(/^[1-9]\d*h$/).transform(e=>e),Ao=H,Gh=(e=>(e.Perpetual="perpetual",e))(Gh||{}),Kh=(e=>(e.Equity="equity",e.Commodity="commodity",e.Index="index",e.Crypto="crypto",e))(Kh||{}),Yh=(e=>(e.Long="long",e.Short="short",e))(Yh||{}),ti=(e=>(e.GTC="gtc",e.IOC="ioc",e.FOK="fok",e))(ti||{}),ta=(e=>(e.TakeProfit="tp",e.StopLoss="sl",e))(ta||{}),vd=(e=>(e.Order="order",e.Position="position",e))(vd||{}),Qh=(e=>(e.Pending="pending",e.Confirmed="confirmed",e.Removed="removed",e))(Qh||{}),qw=(e=>(e.Pending="pending",e.Confirmed="confirmed",e.Removed="removed",e.Failed="failed",e))(qw||{}),Hw=(e=>(e.Transfer="transfer",e.ReferralPayout="referral_payout",e))(Hw||{}),Xh=(e=>(e.In="in",e.Out="out",e))(Xh||{}),Jh=(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))(Jh||{}),EI=(e=>(e.OneHour="1h",e.FourHours="4h",e.OneDay="1d",e.OneWeek="1w",e))(EI||{}),Zh=(e=>(e.Descending="desc",e.Ascending="asc",e))(Zh||{}),RI=P.z.enum(Gh),ef=P.z.enum(Kh),ni=P.z.enum(Yh),_I=P.z.enum(ti),Vq=P.z.enum(ta),jq=P.z.enum(vd),kd=P.z.enum(Qh),xd=P.z.string().transform(e=>e),Wq=P.z.string().min(1).transform(e=>e),zq=P.z.enum(Xh),$w=P.z.enum(Jh),Vw=P.z.enum(EI),II=P.z.enum(Zh),Kn=P.z.string().min(1),Il=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()}),jw=P.z.object({asset:Kn,balance:R,value:R}),CI=P.z.array(jw),Gq=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:Hq.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})),NI=Gq,Kq=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})),rZ=P.z.object({totalAccountValue:R,totalInitialMargin:R,totalMaintenanceMargin:R,totalPositionValue:R}),oZ=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})),Ww=P.z.object({positions:P.z.array(Kq),margin:oZ,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})),OI=Ww,Yq=P.z.object({id:SI,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})),LI=To(Yq),DI=P.z.object({id:SI,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})),Qq=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})),UI=P.z.array(Qq),Xq=P.z.tuple([pe,R]).transform(([e,t])=>({timestamp:e,equity:t})),BI=To(Xq),Jq=P.z.tuple([pe,R]).transform(([e,t])=>({timestamp:e,pnl:t})),MI=To(Jq),sZ=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),Zq=P.z.object({proxy:J,label:P.z.string().optional(),expiry:sZ}).transform(e=>({proxy:e.proxy,label:e.label,expiresAt:e.expiry})),FI=P.z.object({address:J,keys:P.z.array(Zq)}).transform(e=>({address:e.address,keys:e.keys})),qI=P.z.object({secret:P.z.string().min(1)}),HI=P.z.object({status:P.z.enum(["ok","err"]),error:P.z.string().optional()}),Yr=P.z.string().regex(/^-?\d+(?:\.\d+)?$/).pipe(R),wd=P.z.number().int().nonnegative(),Ad=P.z.object({address:J,fee_rate:Yr}).transform(e=>({address:e.address,feeRate:e.fee_rate})),tf=P.z.object({address:J,registered:P.z.boolean(),enabled:P.z.boolean(),admission_enabled:P.z.boolean(),max_fee_rate:Yr}).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:Yr,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})),$I=P.z.object({data:P.z.array(zw)}),nf=(e=>(e.Maker="maker",e.Taker="taker",e))(nf||{}),Gw=P.z.object({earning_id:qq,trade_id:ea,order_id:Cn,instrument_id:Ae,trader:J,buy:P.z.boolean(),price:Yr,quantity:Yr,client_order_id:Er.optional(),side:P.z.enum(nf),timestamp:pe,sequence:wd,notional:Yr,fee_asset:Kn,fee:Yr,builder_fee:Yr,total_fee:Yr,fee_rate:Yr}).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})),VI=P.z.object({start_timestamp:pe,end_timestamp:pe,as_of_sequence:wd}),iZ=VI.transform(e=>({start:e.start_timestamp,end:e.end_timestamp,asOfSequence:e.as_of_sequence})),jI=VI.extend({data:P.z.array(Gw),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}})),eH=P.z.object({fee_asset:Kn,fill_count:wd,notional:Yr,builder_fee:Yr}).transform(e=>({feeAsset:e.fee_asset,fillCount:e.fill_count,notional:e.notional,builderFee:e.builder_fee})),WI=VI.extend({data:P.z.array(eH),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}})),tH=P.z.object({hash:et,asset:Kn,amount:as,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})),zI=To(tH),GI=P.z.object({hash:Il,asset:Kn,amount:as,status:kd}).transform(e=>({hash:e.hash,asset:e.asset,amount:e.amount,status:e.status})),nH=P.z.object({withdraw_id:Fw,asset:Kn,amount:as,fee:R,status:xd,to:J,hash:Il,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})),KI=To(nH),YI=P.z.object({status:P.z.enum(["ok","err"]),withdraw_id:Fw.optional(),error:P.z.string().optional()}).transform(e=>({status:e.status,withdrawalId:e.withdraw_id,error:e.error})),QI=P.z.object({withdraw_id:Fw,asset:Kn,amount:as,fee:R,status:xd,to:J,hash:Il}).transform(e=>({withdrawalId:e.withdraw_id,asset:e.asset,amount:e.amount,fee:e.fee,status:e.status,to:e.to,hash:e.hash})),rH=P.z.object({transfer_id:PI,type:Wq,asset:Kn,amount:R,direction:zq,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})),XI=To(rH),JI=P.z.strictObject({status:P.z.literal("ok"),transfer_id:PI}).transform(e=>({status:e.status,transferId:e.transfer_id})),aZ=P.z.object({lowerBound:R,maxLeverage:P.z.number().int().positive()}),lZ=P.z.object({lower_bound:R,max_leverage:P.z.number().int().positive()}).transform(e=>({lowerBound:e.lower_bound,maxLeverage:e.max_leverage})),oH=P.z.object({instrument_id:Ae,instrument_type:RI,category:ef,symbol:P.z.string().min(1),base_asset:Kn,quote_asset:Kn,funding_interval:$q,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(lZ)}).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})),ZI=P.z.array(oH),sH=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})),eC=P.z.array(sH),tC=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})),iH=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})),nC=P.z.array(iH),rC=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})),zh=P.z.tuple([R,R]).transform(([e,t])=>({price:e,quantity:t})),oC=P.z.object({instrument_id:Ae,bids:P.z.array(zh),asks:P.z.array(zh),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})),sC=P.z.object({b:P.z.array(zh),a:P.z.array(zh)}).transform(e=>({bids:e.b,asks:e.a})),cZ=P.z.object({instrumentId:Ae,bidPrice:R,bidQuantity:R,askPrice:R,askQuantity:R,timestamp:pe.optional()}),iC=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})),aH=P.z.object({trade_id:ea,instrument_id:Ae,side:ni,price:R,quantity:R,timestamp:pe,hash:Il}).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})),aC=P.z.object({tid:ea,iid:Ae,side:ni,p:R,qty:R,ts:pe,hash:Il}).transform(e=>({tradeId:e.tid,instrumentId:e.iid,side:e.side,price:e.p,quantity:e.qty,timestamp:e.ts,hash:e.hash})),lC=To(aH),lH=P.z.object({funding_rate:R,timestamp:pe}).transform(e=>({fundingRate:e.funding_rate,timestamp:e.timestamp})),cC=To(lH),cH=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})),uH=P.z.object({instrument_type:RI,category:ef,taker_fee_rate:R,maker_fee_rate:R,tiers:P.z.array(cH)}).transform(e=>({category:e.category,takerFeeRate:e.taker_fee_rate,makerFeeRate:e.maker_fee_rate,tiers:e.tiers})),dH=P.z.object({fee_schedule:P.z.array(uH)}).transform(e=>({feeSchedule:e.fee_schedule})),uC=dH,dC=To(Td),rf=(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))(rf||{}),pH=P.z.enum(rf),of=(e=>(e.Market="market",e.Limit="limit",e.TakeProfit="take_profit",e.StopLoss="stop_loss",e))(of||{}),pC=P.z.enum(of),sf=(e=>(e.Cross="cross",e.Isolated="isolated",e))(sf||{}),mH=P.z.enum(sf),hH=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:pC.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})),fH=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:pC.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})),gH=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})),uZ=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})),dZ=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})),yH=P.z.discriminatedUnion("margin_type",[uZ,dZ]),bH=P.z.object({id:_l,type:P.z.literal("position_liquidated"),instrument_id:Ae,side:ni,size_closed:R,pnl:R.nullable(),margin_type:mH,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})),Kw=P.z.discriminatedUnion("type",[hH,fH,gH,yH,bH]),wH=P.z.object({notification:Kw,read_at:pe.nullable(),ts:pe}).transform(e=>({notification:e.notification,readAt:e.read_at,timestamp:e.ts})),pZ=P.z.object({notification:P.z.object({type:pH})}),mZ=P.z.array(P.z.unknown()).transform((e,t)=>{let n=[];return e.forEach((r,o)=>{if(!pZ.safeParse(r).success)return;let s=wH.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}),mC=P.z.object({items:mZ,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()}),hC=P.z.object({unread:P.z.number().int().nonnegative()}),fC=P.z.object({status:P.z.enum(["ok","err"]),error:P.z.string().optional()}),bd=P.z.string().regex(/^-?\d+(?:\.\d+)?$/).pipe(R);af=(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))(af||{}),gC=P.z.object({kind:Vq,scope:jq,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})),yC=P.z.enum(af),kH=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||{}),xH=P.z.string().min(1).transform(e=>e),hZ=P.z.string().min(1).optional().transform(AH),lf=P.z.discriminatedUnion("status",[P.z.object({status:P.z.literal("ok")}),P.z.object({status:P.z.literal("err"),error:hZ})]),cf=P.z.object({status:kH,oid:Cn.optional(),coid:Er.optional(),error:P.z.string().optional(),builder:Ad.optional()}).transform((e,t)=>e.status==="err"?{status:"err",error:AH(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}}),Yw=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:xH,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}),bC=P.z.object({status:P.z.literal("ok")}),wC=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}));vC=P.z.object({order_id:Cn,instrument_id:Ae,buy:P.z.boolean(),price:R,quantity:R,tif:_I,post_only:P.z.boolean(),ro:P.z.boolean(),status:yC,resting_quantity:R,filled_quantity:R,created_timestamp:pe,updated_timestamp:pe,client_order_id:P.z.string().optional(),tpsl:gC.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}})),kC=P.z.array(vC),xC=P.z.array(vC),AC=P.z.object({oid:Cn,iid:Ae,buy:P.z.boolean(),p:R,qty:R,tif:_I,po:P.z.boolean(),ro:P.z.boolean(),status:yC,rest:R,fill:R,cts:pe,uts:pe,coid:P.z.string().optional(),tpsl:gC.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}})),TH=P.z.object({trade_id:ea,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:Il}).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??vH(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})),TC=To(TH),SC=P.z.object({tid:ea,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??vH(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 na(e,t,n){return UZ.extend({ch:S.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 VH(e){let[,t]=e.split("::");return Ae.parse(Number(t))}function KZ(e){let[,,t]=e.split("::");return t}function KH(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 JZ.safeParse({...t,topic:"prices.crypto"}).data;case"price.crypto.twap":return ZZ.safeParse({...t,topic:"prices.crypto.twap"}).data;case"price.equity":return eee.safeParse({...t,topic:"prices.equity"}).data}}function bee(e){let t=BigInt(e),n=t<0n,r=n?-t:t,o=r/PH,s=(r%PH).toString().padStart(18,"0").replace(/0+$/,"");return`${n?"-":""}${o}${s===""?"":`.${s}`}`}function XH(e){return vee.extend({window_s:S.z.literal(e)}).transform(t=>({symbol:t.symbol,timestamp:t.timestamp,value:t.full_accuracy_value,windowSeconds:t.window_s}))}var S,uf,EH,fZ,SH,Qw,gZ,RH,yZ,_H,IH,CH,NH,OH,LH,DH,UH,bZ,wZ,vZ,kZ,sCe,iCe,BH,MH,FH,xZ,AZ,TZ,SZ,PZ,EZ,RZ,_Z,ri,IZ,CZ,NZ,OZ,LZ,DZ,qH,UZ,BZ,MZ,FZ,qZ,HZ,$Z,VZ,jZ,WZ,HH,zZ,GZ,$H,Ed,Rd,Cl,jH,WH,YZ,zH,EC,GH,QZ,XZ,Pd,JZ,ZZ,eee,tee,nee,ree,oee,see,YH,iee,aee,QH,lee,cee,uee,dee,pee,mee,hee,fee,gee,yee,PH,wee,vee,JH,ZH,aCe,kee,xee,Aee,Tee,See,Pee,e3,Eee,Ree,_ee,Iee,t3,Cee,n3,Xw=L(()=>{"use strict";Wh();PC();xo();S=require("zod"),uf=S.z.preprocess(e=>typeof e=="string"?e.toUpperCase():e,Nt),EH=(e=>(e.Live="LIVE",e.Matched="MATCHED",e.Delayed="DELAYED",e.Unmatched="UNMATCHED",e.Canceled="CANCELED",e))(EH||{}),fZ=S.z.enum(EH),SH=S.z.object({price:R,size:R}),Qw=S.z.string().regex(/^\d+$/).transform(e=>new Date(Number(e)*1e3).toISOString()),gZ=S.z.string().regex(/^\d+$/).transform(e=>e==="0"?void 0:new Date(Number(e)*1e3).toISOString()),RH=S.z.object({event_type:S.z.literal("book"),market:xe,asset_id:Me,bids:S.z.array(SH),asks:S.z.array(SH),hash:S.z.string().nullish(),timestamp:Pr.nullish(),min_order_size:dn,tick_size:dn,neg_risk:S.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}})),yZ=S.z.object({asset_id:Me,price:R,size:R,side:uf,hash:S.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})),_H=S.z.object({event_type:S.z.literal("price_change"),market:xe,price_changes:S.z.array(yZ),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}})),IH=S.z.object({event_type:S.z.literal("last_trade_price"),market:xe,asset_id:Me,price:R,size:dn,fee_rate_bps:dn,side:uf,timestamp:Pr.nullish(),transaction_hash:S.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}})),CH=S.z.object({event_type:S.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}})),NH=S.z.object({event_type:S.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}})),OH=S.z.object({id:S.z.string(),ticker:S.z.string().nullish(),slug:S.z.string().nullish(),title:S.z.string().nullish(),description:S.z.string().nullish()}),LH=S.z.object({event_type:S.z.literal("new_market"),id:S.z.string(),question:S.z.string().nullish(),market:S.z.string(),slug:S.z.string().nullish(),description:S.z.string().nullish(),assets_ids:S.z.array(Me).nullish(),outcomes:S.z.array(S.z.string()).nullish(),event_message:OH.nullish(),timestamp:Pr.nullish(),tags:S.z.array(S.z.string()).nullish(),condition_id:xe.nullish(),active:S.z.boolean().nullish(),clob_token_ids:S.z.array(S.z.string()).nullish(),sports_market_type:S.z.string().nullish(),line:dn,game_start_time:un.nullish(),order_price_min_tick_size:dn,group_item_title:S.z.string().nullish(),taker_base_fee:dn,fees_enabled:S.z.boolean().nullish(),fee_schedule:S.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}})),DH=S.z.object({event_type:S.z.literal("market_resolved"),id:S.z.string(),market:xe,assets_ids:S.z.array(Me).nullish(),winning_asset_id:Me.nullish(),winning_outcome:S.z.string().nullish(),event_message:OH.nullish(),timestamp:Pr.nullish(),tags:S.z.array(S.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}})),UH=(e=>(e.Placement="PLACEMENT",e.Update="UPDATE",e.Cancellation="CANCELLATION",e))(UH||{}),bZ=S.z.enum(UH),wZ=S.z.object({event_type:S.z.literal("order"),id:S.z.string(),owner:S.z.string(),market:xe,asset_id:Me,side:uf,order_owner:S.z.string().nullish(),original_size:R,size_matched:R,price:R,associate_trades:S.z.array(S.z.string()).nullish(),outcome:S.z.string().nullish(),type:bZ,created_at:Qw.nullish(),expiration:gZ.nullish(),order_type:Uh.nullish(),status:fZ.nullish(),maker_address:S.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}})),vZ=S.z.object({order_id:S.z.string(),owner:S.z.string(),maker_address:S.z.string().nullish(),matched_amount:R,price:R,fee_rate_bps:dn,asset_id:Me,outcome:S.z.string().nullish(),outcome_index:S.z.number().int().nullish(),side:uf}).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})),kZ=S.z.object({event_type:S.z.literal("trade"),type:S.z.literal("TRADE"),id:S.z.string(),taker_order_id:S.z.string(),market:xe,asset_id:Me,side:uf,size:R,fee_rate_bps:dn,price:R,status:Bh,match_time:Qw.nullish(),matchtime:Qw.nullish(),last_update:Qw.nullish(),outcome:S.z.string().nullish(),owner:S.z.string(),trade_owner:S.z.string().nullish(),maker_address:S.z.string().nullish(),transaction_hash:S.z.string().nullish(),bucket_index:S.z.number().int().nullish(),maker_orders:S.z.array(vZ).nullish(),trader_side:S.z.union([S.z.literal("TAKER"),S.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}})),sCe=S.z.discriminatedUnion("event_type",[RH,_H,IH,CH]),iCe=S.z.discriminatedUnion("event_type",[NH,LH,DH]),BH=S.z.discriminatedUnion("event_type",[RH,_H,IH,CH,NH,LH,DH]),MH=S.z.discriminatedUnion("event_type",[wZ,kZ]),FH=S.z.number().int().nonnegative(),xZ=S.z.string().regex(/^trades::\d+$/),AZ=S.z.string().regex(/^bbo::\d+$/),TZ=S.z.string().regex(/^book::\d+$/),SZ=S.z.string().regex(/^tickers::(all|\d+)$/),PZ=S.z.string().regex(/^statistics::(all|\d+)$/),EZ=S.z.string().regex(/^klines::\d+::(1m|5m|15m|1h|4h|1d|1w)$/),RZ=S.z.string().regex(/^tpsl::\d+$/),_Z=S.z.enum(["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications"]),ri=S.z.object({ts:pe,sq:FH}),IZ=ri.extend({ch:xZ,data:S.z.array(aC)}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.trades",type:"trade",channel:e,timestamp:t,sequence:n,payload:r})),CZ=ri.extend({ch:AZ,data:iC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.bbo",type:"bbo",channel:e,timestamp:t,sequence:n,payload:r})),NZ=ri.extend({ch:TZ,data:sC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.book",type:"book",channel:e,timestamp:t,sequence:n,payload:{instrumentId:VH(e),...r}})),OZ=ri.extend({ch:SZ,data:tC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.tickers",type:"ticker",channel:e,timestamp:t,sequence:n,payload:r})),LZ=ri.extend({ch:PZ,data:rC}).transform(({ch:e,ts:t,sq:n,data:r})=>({topic:"perps.statistics",type:"statistic",channel:e,timestamp:t,sequence:n,payload:r})),DZ=ri.extend({ch:EZ,data:S.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:VH(e),interval:KZ(e),candles:r}})),qH=S.z.union([IZ,CZ,NZ,OZ,LZ,DZ]),UZ=ri.extend({ch:_Z});BZ=na("balance","balances",jw),MZ=na("portfolio","portfolio",Ww),FZ=na("order","orders",AC),qZ=na("fill","fills",S.z.array(SC)),HZ=ri.extend({ch:S.z.literal("builderFills"),data:S.z.array(Gw)}).transform(({ch:e,ts:t,sq:n,data:r})=>({type:"builderFill",channel:e,timestamp:t,sequence:n,payload:r})),$Z=na("funding","funding",DI),VZ=na("deposit","deposits",GI),jZ=na("withdrawal","withdrawals",QI),WZ=na("notification","notifications",Kw),HH=S.z.object({ch:S.z.literal("notifications"),ts:pe,sq:FH,type:S.z.literal("resync")}).transform(({ch:e,ts:t,sq:n})=>({type:"resync",channel:e,timestamp:t,sequence:n})),zZ=S.z.object({oid:Cn,st:S.z.enum(["untriggered","armed","cancelled","expired"]),reason:S.z.string().optional()}),GZ=ri.extend({ch:RZ,data:zZ.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})),$H=S.z.union([BZ,MZ,FZ,qZ,HZ,$Z,VZ,jZ,WZ,GZ]);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||{}),Cl=(e=>(e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.Pong="pong",e.Authed="authed",e.Error="error",e))(Cl||{}),jH=S.z.object({op:S.z.enum(Cl),channel:S.z.string().optional(),rid:S.z.string().optional(),code:S.z.string().transform(e=>e).optional()}),WH=S.z.object({v:S.z.literal(1),channel:S.z.enum(Rd),seq:S.z.number().int().nonnegative(),ts:pe,snapshot:S.z.boolean().optional(),dropped:S.z.number().int().nonnegative().optional(),payload:S.z.unknown()}),YZ=S.z.object({timestamp:pe,value:H,full_accuracy_value:R}).transform(({timestamp:e,full_accuracy_value:t})=>({timestamp:e,value:t})),zH=S.z.object({symbol:S.z.string(),timestamp:pe,value:H,full_accuracy_value:R,received_at:pe.optional(),is_carried_forward:S.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})),EC=S.z.object({symbol:S.z.string(),data:S.z.array(YZ)}),GH=S.z.literal(60),QZ=S.z.object({symbol:S.z.string(),timestamp:pe,value:H,full_accuracy_value:R,window_seconds:GH}).transform(({symbol:e,timestamp:t,full_accuracy_value:n,window_seconds:r})=>({symbol:e,timestamp:t,value:n,windowSeconds:r})),XZ=EC.extend({window_seconds:GH}).transform(({symbol:e,data:t,window_seconds:n})=>({symbol:e,data:t,windowSeconds:n})),Pd=S.z.object({timestamp:pe,seq:S.z.number().optional(),dropped:S.z.number().optional()}),JZ=S.z.union([Pd.extend({topic:S.z.literal("prices.crypto"),type:S.z.literal("update"),payload:zH}),Pd.extend({topic:S.z.literal("prices.crypto"),type:S.z.literal("subscribe"),payload:EC})]),ZZ=S.z.union([Pd.extend({topic:S.z.literal("prices.crypto.twap"),type:S.z.literal("update"),payload:QZ}),Pd.extend({topic:S.z.literal("prices.crypto.twap"),type:S.z.literal("subscribe"),payload:XZ})]),eee=S.z.union([Pd.extend({topic:S.z.literal("prices.equity"),type:S.z.literal("update"),payload:zH}),Pd.extend({topic:S.z.literal("prices.equity"),type:S.z.literal("subscribe"),payload:EC})]);tee=S.z.object({id:S.z.string(),body:S.z.string().nullish(),parentEntityType:Js.nullish(),parentEntityID:S.z.number().int().nullish(),parentCommentID:S.z.string().nullish(),userAddress:S.z.string().nullish(),replyAddress:S.z.string().nullish(),createdAt:S.z.string().nullish(),updatedAt:S.z.string().nullish(),media:S.z.array(Mw).nullish(),profile:El.nullish(),reactions:S.z.array(yd).nullish(),reportCount:S.z.number().int().nullish(),reactionCount:S.z.number().int().nullish(),tradeAsset:S.z.string().nullish()}),nee=S.z.object({topic:S.z.literal("comments"),type:S.z.literal("comment_created"),timestamp:pe,payload:Vh}),ree=S.z.object({topic:S.z.literal("comments"),type:S.z.literal("comment_removed"),timestamp:pe,payload:tee}),oee=S.z.object({topic:S.z.literal("comments"),type:S.z.literal("reaction_created"),timestamp:pe,payload:yd}),see=S.z.object({topic:S.z.literal("comments"),type:S.z.literal("reaction_removed"),timestamp:pe,payload:yd}),YH=S.z.object({symbol:S.z.string(),timestamp:pe,value:H}),iee="prices.crypto.binance",aee="prices.crypto.chainlink",QH="prices.crypto.chainlink.twap",lee=S.z.literal("crypto_prices"),cee=S.z.literal("crypto_prices_chainlink"),uee=S.z.literal("crypto_prices_twap_thirty"),dee=S.z.literal("crypto_prices_twap_sixty"),pee=lee.transform(()=>iee),mee=cee.transform(()=>aee),hee=uee.transform(()=>QH),fee=dee.transform(()=>QH),gee=S.z.object({topic:pee,type:S.z.literal("update"),timestamp:pe,payload:YH}),yee=S.z.object({topic:mee,type:S.z.literal("update"),timestamp:pe,payload:YH}),PH=1000000000000000000n;wee=S.z.string().regex(/^-?\d+$/).transform(bee),vee=S.z.object({symbol:S.z.string(),value:H,full_accuracy_value:wee,timestamp:pe});JH=S.z.object({topic:hee,type:S.z.literal("update"),timestamp:pe,payload:XH(30)}),ZH=S.z.object({topic:fee,type:S.z.literal("update"),timestamp:pe,payload:XH(60)}),aCe=S.z.union([JH,ZH]),kee=S.z.discriminatedUnion("topic",[gee,yee,JH,ZH]),xee=S.z.object({symbol:S.z.string(),value:H,full_accuracy_value:R.nullish(),timestamp:pe,received_at:pe.nullish(),is_carried_forward:S.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})),Aee=S.z.object({timestamp:S.z.number(),value:H}),Tee=S.z.object({symbol:S.z.string(),data:S.z.array(Aee)}),See=S.z.literal("equity_prices"),Pee="prices.equity.pyth",e3=See.transform(()=>Pee),Eee=S.z.object({topic:e3,type:S.z.literal("update"),timestamp:pe,payload:xee}),Ree=S.z.object({topic:e3,type:S.z.literal("subscribe"),timestamp:pe,payload:Tee}),_ee=S.z.discriminatedUnion("type",[Eee,Ree]),Iee=S.z.discriminatedUnion("type",[nee,ree,oee,see]),t3=S.z.discriminatedUnion("topic",[Iee,kee,_ee]),Cee=S.z.object({gameId:S.z.number().int(),sportradarGameId:S.z.string().nullish(),slug:S.z.string().nullish(),leagueAbbreviation:S.z.string(),homeTeam:S.z.string().nullish(),awayTeam:S.z.string().nullish(),status:S.z.string(),live:S.z.boolean(),ended:S.z.boolean(),score:S.z.string(),period:S.z.string().nullish(),elapsed:S.z.string().nullish(),finishedTimestamp:un.nullish(),finished_timestamp:un.nullish(),turn:S.z.string().nullish()}).transform(({finishedTimestamp:e,finished_timestamp:t,...n})=>({...n,finishedAt:e??t})),n3=Cee.transform(e=>({topic:"sports",type:"sport_result",payload:e}))});function Oee(e){let t=o3(e.issues);return t.length===0?"It was not possible to determine a more specific reason.":["Fix the following issues:",r3(t)].join(`
|
|
5
5
|
`)}function Lee(e,t){let n=o3(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:",r3(n)].join(`
|
|
7
7
|
`)}function r3(e){return e.map(t=>t.path===null?`- ${t.message}`:`- ${t.path}: ${t.message}`).join(`
|
|
8
|
-
`)}function o3(e){return s3(e).slice(0,99)}function s3(e,t=[]){let n=e.flatMap(r=>{let o=[...t,...r.path];return r.code==="invalid_union"?r.errors.flatMap(s=>s3(s,o)):[{code:r.code,message:r.message,path:o.length===0?null:Bee(o)}]});return Dee(n)}function Dee(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(Uee)}function Uee(e,t){return e.path===null&&t.path!==null?-1:e.path!==null&&t.path===null?1:(e.path??"").localeCompare(t.path??"")}function Bee(e){return e.reduce((t,n)=>typeof n=="number"?`${t}[${n.toString()}]`:typeof n!="string"?t:n.includes('"')?`${t}["${n.replaceAll('"','\\"')}"]`:Nee.test(n)?t.length===0?n:`${t}.${n}`:`${t}["${n}"]`,"")}function B(...e){return{isError(t){return e.some(n=>t instanceof n)}}}var Nee,E,Nl,C,I,RC,Qr,_C,O,$,tt,Jw,en,vt,So,df,Zw,ce,e0=L(()=>{"use strict";Xw();Al();Nee=/^[$A-Z_a-z][$\w]*$/;E=class i3 extends Ct{name="UserInputError";constructor(t,n={}){super(t,n)}static fromZodError(t){return new i3(Oee(t),{cause:t})}},Nl=class extends Ct{name="PaginationLimitError";constructor(e,t={}){super(e,t)}},C=class a3 extends Ct{name="UnexpectedResponseError";constructor(t,n={}){super(t,n)}static fromZodError(t,n){return new a3(Lee(t,n),{cause:t})}},I=class l3 extends Ct{name="TransportError";constructor(t,n={}){super(t,n)}static fromError(t){return new l3(t instanceof Error?t.message:"Request failed",{cause:t})}},RC=(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))(RC||{}),Qr=class extends Ct{name="ConnectionLostError";code;reason;constructor(e,t){super(e,t),this.code=t.code,this.reason=t.reason}},_C=(e=>(e.RESTARTING="restarting",e.POST_ONLY="post_only",e))(_C||{}),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)}},Jw=class c3 extends Ct{name="OperationAbortedError";constructor(t,n={}){super(t,n)}static fromReason(t){return new c3("Operation was aborted.",{cause:t})}},en=class extends Ct{name="TransactionFailedError";constructor(e,t={}){super(e,t)}},vt=class u3 extends Ct{name="CancelledSigningError";constructor(t,n={}){super(t,n)}static fromError(t){return new u3(t.message,{cause:t})}},So=class extends Ct{name="InsufficientLiquidityError";constructor(e,t={}){super(e,t)}},df=class extends Ct{name="AutoCancelDailyLimitError";constructor(e,t={}){super(e,t)}},Zw=class extends Ct{name="PerpsCancelRetryError";results;pendingIndexes;constructor(e,t){super(e,t),this.results=[...t.results],this.pendingIndexes=[...t.pendingIndexes]}},ce=class d3 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 d3(r,{cause:t})}}});var pf=L(()=>{"use strict";xo()});var m3,Rr,IC,CC=L(()=>{"use strict";m3=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||{}),IC=m3.z.enum(Rr)});function t0(e){return x.z.object({count:x.z.number(),data:x.z.array(e),limit:x.z.number(),next_cursor:x.z.string()}).transform(({next_cursor:t,...n})=>({...n,nextCursor:t}))}function ls(e,t){return x.z.object({id:uI,owner:is,payload:t,timestamp:ute,type:x.z.literal(e)})}function Ite(e){return e.success&&e.errorMsg===""&&e.orderID!==""&&Lte(e.status)}function Cte(e){switch(e){case"live":return"live";case"matched":return"matched";case"delayed":return"delayed";default:oq(`Unexpected order post status: ${e}`)}}function Nte(e){return Ite(e)?Rte.parse({makingAmount:e.makingAmount,ok:!0,orderId:e.orderID,status:Cte(e.status),takingAmount:e.takingAmount,tradeIds:e.tradeIDs,transactionsHashes:e.transactionsHashes}):_te.parse({code:Ote(e),message:e.errorMsg||"Unknown order failure",ok:!1})}function Ote(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 Lte(e){return e==="live"||e==="matched"||e==="delayed"}var x,b3,NC,w3,Mee,Fee,v3,ra,k3,x3,A3,T3,qee,S3,Hee,P3,E3,$ee,Vee,jee,Wee,R3,OC,_3,I3,h3,C3,zee,N3,f3,Gee,O3,L3,D3,U3,B3,Kee,M3,F3,q3,Yee,H3,Qee,$3,Xee,V3,Jee,Zee,ete,j3,tte,W3,n0,nte,LC,rte,ote,z3,ste,ite,ate,lte,cte,ute,dte,pte,mte,hte,fte,gte,yte,bte,wte,vte,kte,xte,G3,g3,Ate,Tte,K3,Y3,Q3,y3,Ste,r0,Pte,o0,Ete,Rte,_te,DC,X3,Yn,Dte,Ute,J3,Bte,Mte,Fte,Z3,qte,e$,Hte,t$,UC=L(()=>{"use strict";CC();Wh();xo();x=require("zod");Al();b3=x.z.object({closed_only:x.z.boolean()}).transform(({closed_only:e})=>({closedOnly:e})),NC=x.z.object({asset_id:Me,associate_trades:x.z.array(x.z.string()),created_at:Yi,expiration:iI,id:x.z.string(),maker_address:x.z.string(),market:xe,order_type:x.z.string(),original_size:R,outcome:x.z.string(),owner:x.z.string(),price:R,side:x.z.string(),size_matched:R,status:x.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}}),w3=t0(NC),Mee=x.z.object({asset_id:Me,fee_rate_bps:x.z.preprocess(Gn,R.nullable()),maker_address:x.z.string(),matched_amount:R,order_id:x.z.string(),outcome:x.z.string(),owner:x.z.string(),price:R,side:x.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})),Fee=x.z.object({asset_id:Me,bucket_index:x.z.number(),fee_rate_bps:R,id:x.z.string(),last_update:Yi,maker_address:x.z.string(),maker_orders:x.z.array(Mee),market:xe,match_time:Yi,outcome:x.z.string(),owner:x.z.string(),price:R,side:x.z.string(),size:R,status:Bh,taker_order_id:x.z.string(),trader_side:x.z.enum(["TAKER","MAKER"]),transaction_hash:x.z.preprocess(gd,x.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})),v3=t0(Fee),ra=(e=>(e.COLLATERAL="COLLATERAL",e.CONDITIONAL="CONDITIONAL",e.CONDITIONAL_V2="CONDITIONAL-V2",e))(ra||{}),k3=x.z.enum(ra),x3=x.z.object({allowances:x.z.record(J,x.z.string().transform(BigInt)),balance:as}),A3=x.z.object({scoring:x.z.boolean()}),T3=x.z.record(x.z.string(),x.z.boolean()),qee=x.z.object({asset_address:x.z.string(),asset_rate:H,condition_id:xe,date:un,earnings:H,maker_address:x.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})),S3=t0(qee),Hee=x.z.object({asset_address:x.z.string(),asset_rate:H,date:un,earnings:H,maker_address:x.z.string()}).transform(({asset_address:e,asset_rate:t,maker_address:n,...r})=>({...r,assetAddress:e,assetRate:t,makerAddress:n})),P3=x.z.array(Hee),E3=x.z.record(xe,x.z.number()),$ee=x.z.object({outcome:x.z.string(),price:H,token_id:Me}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Vee=x.z.object({asset_address:x.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})),jee=x.z.object({asset_address:x.z.string(),asset_rate:H,earnings:H}).transform(({asset_address:e,asset_rate:t,...n})=>({...n,assetAddress:e,assetRate:t})),Wee=x.z.object({condition_id:xe,earning_percentage:x.z.number(),earnings:x.z.array(jee),event_slug:x.z.string(),image:x.z.string(),maker_address:x.z.string(),market_competitiveness:x.z.number(),market_slug:x.z.string(),question:x.z.string(),rewards_config:x.z.array(Vee),rewards_max_spread:x.z.number(),rewards_min_size:H,tokens:x.z.array($ee)}).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})),R3=t0(Wee),OC=x.z.object({apiKey:is,secret:x.z.string(),passphrase:x.z.string()}).transform(e=>({key:e.apiKey,passphrase:e.passphrase,secret:e.secret})),_3=x.z.object({apiKeys:x.z.array(is)}),I3=x.z.object({key:is,secret:x.z.string(),passphrase:x.z.string()}),h3=x.z.object({key:is,createdAt:un.optional(),revokedAt:un.nullable().optional()}),C3=x.z.array(x.z.union([is.transform(e=>({key:e})),h3])).transform(e=>e.map(t=>h3.parse(t))),zee=x.z.object({id:x.z.string(),tradeType:x.z.string(),takerOrderHash:x.z.string(),builder:x.z.string(),market:xe,assetId:Me,side:Nt,size:R,sizeUsdc:R,price:R,status:x.z.string(),outcome:x.z.string(),outcomeIndex:x.z.number().int(),owner:x.z.string(),maker:x.z.string(),transactionHash:x.z.string(),matchTime:Yi,bucketIndex:x.z.number().int(),fee:R,feeUsdc:R,err_msg:x.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})),N3=x.z.object({limit:x.z.number().int(),count:x.z.number().int(),next_cursor:x.z.string(),data:x.z.array(zee)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),f3=1e4,Gee=x.z.object({builder_maker_fee_rate_bps:x.z.number(),builder_taker_fee_rate_bps:x.z.number()}).transform(({builder_maker_fee_rate_bps:e,builder_taker_fee_rate_bps:t})=>({maker:e/f3,taker:t/f3})),O3=Gee,L3=x.z.object({canceled:x.z.array(fd),not_canceled:x.z.record(fd,x.z.string())}).transform(({canceled:e,not_canceled:t})=>({canceled:e,notCanceled:t})),D3=x.z.object({mid:R}),U3=x.z.record(Me,R),B3=x.z.object({price:R}),Kee=x.z.partialRecord(Nt,R),M3=x.z.record(Me,Kee),F3=x.z.object({spread:R}),q3=x.z.record(Me,R),Yee=x.z.object({price:R,side:Nt}),H3=Yee.extend({side:x.z.union([Nt,x.z.literal("")])}).transform(e=>e.side===""?null:{price:e.price,side:e.side}),Qee=x.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})),$3=x.z.array(Qee),Xee=x.z.object({condition_id:xe}).transform(({condition_id:e})=>e),V3=Xee,Jee=x.z.object({r:x.z.number().default(0),e:x.z.number().default(0)}).transform(({r:e,e:t})=>({rate:e,exponent:t})),Zee=x.z.object({t:Me,o:x.z.string()}).transform(({t:e,o:t})=>({assetId:e,tokenId:e,outcome:t})),ete=x.z.object({fd:Jee.nullish(),mts:Sl,nr:x.z.boolean().optional(),t:x.z.array(Zee)}).transform(({fd:e,mts:t,nr:n,t:r})=>({feeInfo:e??{rate:0,exponent:0},negRisk:n??!1,tickSize:t,tokens:r})),j3=ete,tte=x.z.object({neg_risk:x.z.boolean()}).transform(({neg_risk:e,...t})=>({...t,negRisk:e})),W3=tte,n0=(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))(n0||{}),nte=x.z.enum(n0),LC=x.z.object({asset_id:Me,eventSlug:x.z.string().optional(),icon:x.z.string().optional(),image:x.z.string().optional(),market:xe,market_slug:x.z.string().optional(),matched_size:R,order_id:fd,original_size:R,outcome:x.z.string(),outcome_index:x.z.number().int(),price:R,question:x.z.string().optional(),remaining_size:R,seriesSlug:x.z.string().optional(),side:Nt,trade_id:x.z.preprocess(gd,x.z.string().optional()),transaction_hash:x.z.preprocess(gd,et.optional()),type:x.z.preprocess(gd,Uh.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})),rte=x.z.object({outcome:x.z.string(),price:H.optional(),token_id:Me,winner:x.z.boolean()}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),ote=x.z.object({max_spread:x.z.number(),min_size:H,rates:x.z.array(x.z.object({asset_address:x.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})),z3=x.z.object({accepting_order_timestamp:hd.nullish(),accepting_orders:x.z.boolean(),active:x.z.boolean(),archived:x.z.boolean().optional(),closed:x.z.boolean(),condition_id:xe,description:x.z.string(),enable_order_book:x.z.boolean().optional(),end_date_iso:hd.nullish(),eventSlug:x.z.string().optional(),fpmm:x.z.string(),game_start_time:hd.nullish(),icon:x.z.string(),image:x.z.string(),is_50_50_outcome:x.z.boolean().optional(),maker_base_fee:x.z.number().nullable(),market_slug:x.z.string(),minimum_order_size:H,minimum_tick_size:H,neg_risk:x.z.boolean().optional(),neg_risk_market_id:x.z.string().optional(),neg_risk_request_id:x.z.string().optional(),notifications_enabled:x.z.boolean().optional(),question:x.z.string(),question_id:vo,rewards:ote.optional(),seconds_delay:x.z.number().int(),tags:x.z.array(x.z.string()).nullish(),taker_base_fee:x.z.number().nullable(),tokens:x.z.array(rte)}).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})),ste=x.z.object({proxyWallet:J,reward:H,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),ite=x.z.object({amount:H,proxyWallet:J,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),ate=x.z.object({body:x.z.string().nullish(),createdAt:re.nullish(),eventSlug:x.z.string().nullish(),eventTitle:x.z.string().nullish(),id:Xs,image:x.z.string().nullish(),parentCommentID:Xs.nullish(),parentEntityID:x.z.number().int().nullish(),parentEntityType:Js.nullish(),profile:El.nullish(),seriesSlug:x.z.string().nullish(),seriesTitle:x.z.string().nullish(),userAddress:x.z.string().nullish()}),lte=x.z.object({amount:H,conditionId:xe,image:x.z.string(),marketUrl:x.z.string().optional(),negRisk:x.z.boolean(),portfolioUrl:x.z.string().optional(),position:x.z.string().optional(),proxyWallet:J,question:x.z.string(),slug:x.z.string(),txnHash:et}).transform(({slug:e,txnHash:t,...n})=>({...n,marketSlug:e,transactionHash:t})),cte=x.z.object({amount:H,conditionId:Zt,legs:x.z.number().int(),outcomeIndex:x.z.number().int(),portfolioUrl:x.z.string().optional(),positionId:Xe,proxyWallet:J,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),ute=x.z.preprocess(e=>typeof e!="string"?e:/^\d+$/.test(e)?Number(e):Date.parse(e),pe);dte=ls(1,LC),pte=ls(2,LC),mte=ls(3,z3),hte=ls(4,z3),fte=ls(5,ste),gte=ls(6,ate),yte=ls(7,ite),bte=ls(8,LC),wte=ls(9,lte),vte=ls(10,cte),kte=x.z.discriminatedUnion("type",[dte,pte,mte,hte,fte,gte,yte,bte,wte,vte]),xte=x.z.object({type:x.z.number().int()}),G3=x.z.array(x.z.unknown()).transform((e,t)=>{let n=[];return e.forEach((r,o)=>{let s=xte.safeParse(r);if(!s.success){for(let a of s.error.issues)t.addIssue({...a,path:[o,...a.path]});return}if(!nte.safeParse(s.data.type).success)return;let i=kte.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}),g3=x.z.object({price:R,size:R}),Ate=x.z.string().regex(/^[a-f0-9]{40}$/).transform(e=>e),Tte=R.transform(Number).pipe(Sl),K3=x.z.object({market:xe,asset_id:Me,timestamp:Pr.nullish(),bids:x.z.array(g3),asks:x.z.array(g3),min_order_size:R,tick_size:Tte,neg_risk:x.z.boolean(),last_trade_price:R.nullish(),hash:Ate}).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})),Y3=K3,Q3=x.z.array(K3),y3=x.z.preprocess(e=>e===""?"0":e,R),Ste=x.z.object({errorMsg:x.z.string(),makingAmount:y3,orderID:x.z.string(),status:x.z.string(),success:x.z.boolean(),takingAmount:y3,tradeIDs:x.z.array(x.z.string()).default([]),transactionsHashes:x.z.array(x.z.string()).default([])}),r0=(e=>(e.LIVE="live",e.MATCHED="matched",e.DELAYED="delayed",e))(r0||{}),Pte=x.z.nativeEnum(r0),o0=(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))(o0||{}),Ete=x.z.nativeEnum(o0),Rte=x.z.object({ok:x.z.literal(!0),orderId:fd.refine(e=>e.length>0),status:Pte,makingAmount:R,takingAmount:R,tradeIds:x.z.array(x.z.string()),transactionsHashes:x.z.array(et)}),_te=x.z.object({ok:x.z.literal(!1),code:Ete,message:x.z.string().min(1)}),DC=Ste.transform(Nte),X3=x.z.array(DC);Yn="LTE=",Dte=x.z.object({id:x.z.number().int().optional(),asset_address:x.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})),Ute=x.z.object({condition_id:xe,rewards_max_spread:x.z.number().optional(),rewards_min_size:H.optional(),rewards_config:x.z.array(Dte).optional(),sponsored_daily_rate:H.optional(),sponsors_count:x.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})),J3=x.z.object({limit:x.z.number().int(),count:x.z.number().int(),next_cursor:x.z.string(),data:x.z.array(Ute)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),Bte=x.z.object({token_id:Me,outcome:x.z.string(),price:H}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Mte=x.z.object({asset_address:x.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})),Fte=x.z.object({condition_id:xe,question:x.z.string(),market_slug:x.z.string().optional(),event_slug:x.z.string().optional(),image:x.z.string().optional(),rewards_max_spread:x.z.number().optional(),rewards_min_size:H.optional(),market_competitiveness:x.z.number().optional(),tokens:x.z.array(Bte),rewards_config:x.z.array(Mte).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})),Z3=x.z.object({limit:x.z.number().int(),count:x.z.number().int(),next_cursor:x.z.string(),data:x.z.array(Fte)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),qte=x.z.object({address:J,scopes:x.z.array(Nh).min(1),valid_until:x.z.number().int().nonnegative()}).transform(({valid_until:e,...t})=>({...t,validUntil:e})),e$=x.z.object({signers:x.z.array(qte),wallet:J}),Hte=x.z.object({minimum_tick_size:Sl}).transform(({minimum_tick_size:e,...t})=>({...t,minimumTickSize:e})),t$=Hte});var ae,mf,$te,Vte,n$,BCe,jte,Wte,r$,zte,Gte,o$,_d,Kte,s$,BC,MC,FC,i$,Se,MCe,s0=L(()=>{"use strict";Wh();Wh();xo();ae=require("zod"),mf=(e=>(e.Pending="pending",e.Queued="queued",e.Success="success",e.Failed="failed",e.Cancelled="cancelled",e))(mf||{}),$te=ae.z.union([ae.z.string(),ae.z.number().int().transform(String)]).transform(Aw),Vte=ae.z.object({id:ae.z.number().int(),marketId:$te.nullish(),eventId:Gt.nullish(),questionId:vo.nullish(),content:ae.z.string().nullish(),state:ae.z.enum(mf).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:re.nullish(),queuedAt:re.nullish(),scheduledFor:re.nullish(),txTimestamp:re.nullish()}),n$=ae.z.array(Vte),BCe=ae.z.object({hasMore:ae.z.boolean().nullish(),totalResults:ae.z.number().int().nullish()}),jte=ae.z.object({id:ae.z.string(),communityMod:ae.z.boolean().nullish(),creator:ae.z.boolean().nullish(),mod:ae.z.boolean().nullish()}),Wte=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:re.nullish(),updatedAt:re.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:re.nullish(),discordUsername:ae.z.string().nullish(),xUsername:ae.z.string().nullish(),verifiedBadge:ae.z.boolean().nullish(),dubPartnerId:ae.z.string().nullish(),termsAcceptedAt:re.nullish(),viewOnlyAcknowledgedAt:re.nullish(),isReferralRestricted:ae.z.boolean().nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),r$=ae.z.object({createdAt:re.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(jte).nullish(),xUsername:ae.z.string().nullish(),verifiedBadge:ae.z.boolean().nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),zte=ae.z.object({id:Mh,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})),Gte=ae.z.object({hasMore:ae.z.boolean().nullish(),totalResults:ae.z.number().int().nullish()}),o$=ae.z.object({events:ae.z.array(ei).nullish(),tags:ae.z.array(zte).nullish(),profiles:ae.z.array(Wte).nullish(),pagination:Gte.nullish()}),_d=Pl.extend({templates:ae.z.array(Bw).nullish()}),Kte=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})),s$=ae.z.array(_d),BC=ae.z.array(Kte),MC=ae.z.array(_d),FC=Uw.extend({events:ae.z.array(ei).nullish(),collections:ae.z.array(Dw).nullish(),tags:ae.z.array(_d).nullish()}),i$=ae.z.array(FC),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||{}),MCe=ae.z.object({type:ae.z.enum(Se),typeName:ae.z.enum(["EOA","POLY_PROXY","GNOSIS_SAFE","DEPOSIT_WALLET"])})});var Ol,qC=L(()=>{"use strict";Ol=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 Id,HC=L(()=>{"use strict";Id=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,a$=L(()=>{"use strict";HC();Cd=class extends Error{name="ForceRetryError";customDelay;code;customRequest;constructor(t){let n=t?.cause?t.cause instanceof Error?t.cause:new Id(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 $C,l$,i0,c$,u$,a0,Yte,d$,l0,p$,c0,hf,m$,h$,f$,g$,Ll=L(()=>{"use strict";$C=(()=>{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})(),l$=typeof globalThis.AbortController=="function",i0=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",c$=typeof globalThis.ReadableStream=="function",u$=typeof globalThis.FormData=="function",a0=["get","post","put","patch","head","delete"],Yte=()=>{};Yte();d$={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},l0=2147483647,p$=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,c0=Symbol("stop"),hf=class{options;constructor(t){this.options=t}},m$=e=>new hf(e),h$={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},f$={next:!0},g$={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 Qte,y$,b$,w$,v$=L(()=>{"use strict";Ll();Qte=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=p$,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},y$=(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))}}))},b$=(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(y$(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},w$=(e,t,n)=>{if(!e.body)return e;let r=Qte(n??e.body);return new Request(e,{duplex:"half",body:y$(e.body,r,t)})}});var oa,k$=L(()=>{"use strict";oa=e=>e!==null&&typeof e=="object"});function u0(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:WC(e[n]??[],t[n]??[])}var ff,VC,jC,Xte,WC,zC=L(()=>{"use strict";Ll();k$();ff=(...e)=>{for(let t of e)if((!oa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return WC({},...e)},VC=(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};jC=(e={},t={})=>({beforeRequest:u0(e,t,"beforeRequest"),beforeRetry:u0(e,t,"beforeRetry"),afterResponse:u0(e,t,"afterResponse"),beforeError:u0(e,t,"beforeError")}),Xte=(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(oa(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},WC=(...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(oa(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&&(!oa(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:Xte(o,l);continue}oa(l)&&a in t&&(l=WC(t[a],l)),t={...t,[a]:l}}oa(i.hooks)&&(r=jC(r,i.hooks),t.hooks=r),oa(i.headers)&&(n=VC(n,i.headers),t.headers=n)}return o!==void 0&&(t.searchParams=o),s.length>0&&(s.length===1?t.signal=s[0]:i0?t.signal=AbortSignal.any(s):t.signal=s.at(-1)),t}});var A$,Jte,Zte,ene,x$,T$,S$=L(()=>{"use strict";Ll();A$=e=>a0.includes(e)?e.toUpperCase():e,Jte=["get","put","head","delete","options","trace"],Zte=[408,413,429,500,502,503,504],ene=[413,429,503],x$={limit:2,methods:Jte,statusCodes:Zte,afterStatusCodes:ene,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},T$=(e={})=>{if(typeof e=="number")return{...x$,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{...x$,...t}}});var Dl,GC=L(()=>{"use strict";Dl=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}}});async function KC(e,t,n,r){return new Promise((o,s)=>{let i=setTimeout(()=>{n&&n.abort(),s(new Dl(e))},r.timeout);r.fetch(e,t).then(o).catch(s).then(()=>{clearTimeout(i)})})}var P$=L(()=>{"use strict";GC()});async function YC(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 E$=L(()=>{"use strict"});var R$,_$,I$=L(()=>{"use strict";Ll();R$=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in g$)&&!(r in h$)&&(!(r in e)||r in f$)&&(n[r]=t[r]);return n},_$=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 C$(e){return e instanceof Ol||e?.name===Ol.name}function N$(e){return e instanceof Dl||e?.name===Dl.name}var O$=L(()=>{"use strict";qC();GC()});var gf,L$=L(()=>{"use strict";qC();HC();a$();v$();zC();S$();P$();E$();I$();O$();Ll();gf=class e{static create(t,n){let r=new e(t,n),o=async()=>{if(typeof r.#n.timeout=="number"&&r.#n.timeout>l0)throw new RangeError(`The \`timeout\` option cannot be greater than ${l0}`);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 hf)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 Ol(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(!c$)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");let a=i.clone();return r.#d(i),b$(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(d$))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:VC(this.#s.headers,n.headers),hooks:jC({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:A$(n.method??this.#s.method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:T$(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}l$&&i0&&(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),$C&&(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&&(u$&&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),_$(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(!$C)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 Id(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(N$(t)&&!this.#n.retry.retryOnTimeout)throw t;if(C$(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),l0);if(this.#r<1)throw n;if(await YC(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===c0)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=R$(this.request,this.#n);return this.#o=this.request,this.request=this.#o.clone(),this.#n.timeout===!1?this.#n.fetch(this.#o,t):KC(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:w$(t,this.#n.onUploadProgress,n??this.#n.body??void 0)}}});var QC,tne,d0,D$=L(()=>{"use strict";L$();Ll();zC();QC=e=>{let t=(n,r)=>gf.create(n,ff(e,r));for(let n of a0)t[n]=(r,o)=>gf.create(r,ff(e,o,{method:n}));return t.create=n=>QC(ff(n)),t.extend=n=>(typeof n=="function"&&(n=n(e??{})),QC(ff(e,n))),t.stop=c0,t.retry=m$,t},tne=QC(),d0=tne});function nne(e){let t=e.length===64?`${e}00`:e;return Oh(t.toLowerCase())}function rne(e){if(e.length===66)return!0;let t=e.toLowerCase();return t.startsWith("0x01")||t.startsWith("0x02")}function us(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 vne(e){let t=kne(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 kne(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 xne(e){let t=Tne(e);switch(e.type){case"TRADE":return Ane(e,t);case"SPLIT":case"MERGE":case"REDEEM":case"CONVERSION":return{...t,type:e.type,conditionId:_r(e.condition_id,"condition_id"),amount:e.usdc_size,title:_r(e.title,"title"),slug:_r(e.slug,"slug"),icon:e.icon??null,eventSlug:_r(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:B$.parse(e.side)}}}function Ane(e,t){let n={...t,type:"TRADE",side:Nt.parse(_r(e.side,"side")),shares:e.size,amount:e.usdc_size,price:e.price,title:_r(e.title,"title"),icon:e.icon??null};if(e.is_combo===!0)return{...n,isCombo:!0,conditionId:Zt.parse(_r(e.condition_id,"condition_id")),positionId:Xe.parse(_r(e.token_id,"token_id"))};let r=_r(e.token_id,"token_id");return{...n,isCombo:!1,conditionId:_r(e.condition_id,"condition_id"),assetId:r,tokenId:r,outcome:_r(e.outcome,"outcome"),outcomeIndex:e.outcome_index,slug:_r(e.slug,"slug"),eventSlug:_r(e.event_slug,"event_slug")}}function Tne(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 _r(e,t){if(e==null)throw new TypeError(`Expected activity.${t} to be present`);return e}var U,m0,XC,Ul,B$,Bl,h0,Ml,M$,Fl,ii,Nd,ai,F$,one,ql,q$,Hl,H$,$l,$$,oi,sne,ine,ane,Vl,JC,jl,p0,pn,V$,lne,cne,une,dne,pne,j$,mne,W$,z$,G$,K$,Y$,Q$,Wl,hne,fne,gne,Kt,X$,yne,bne,wne,J$,Z$,e4,Po,t4,Sne,n4,yf,Pne,Ene,Rne,_ne,Ine,r4,o4,s4,zl,bf,Gl,i4,Kl,a4,Yl,PNe,Cne,Nne,cs,One,Lne,Dne,Une,Bne,l4,c4,u4,d4,p4,Ql,Mne,Xl,Fne,Jl,qne,Zl,Hne,U$,$ne,m4,f0=L(()=>{"use strict";xo();U=require("zod"),m0=(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))(m0||{}),XC=U.z.enum(m0),Ul=(e=>(e.In="IN",e.Out="OUT",e))(Ul||{}),B$=U.z.enum(Ul),Bl=(e=>(e.Asc="ASC",e.Desc="DESC",e))(Bl||{}),h0=U.z.enum(Bl),Ml=(e=>(e.Cash="CASH",e.Tokens="TOKENS",e))(Ml||{}),M$=U.z.enum(Ml);Fl=xe.refine(rne,"Expected a 32-byte condition ID or a 31-byte protocol v2 market condition ID").transform(nne);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||{}),F$=U.z.enum(ai),one=U.z.enum(["OPEN","REDEEMABLE","CLOSED"]),ql=(e=>(e.CurrentValue="CURRENT_VALUE",e.Tokens="TOKENS",e.UnrealizedPnl="UNREALIZED_PNL",e.RealizedPnl="REALIZED_PNL",e.TotalPnl="TOTAL_PNL",e.Timestamp="TIMESTAMP",e))(ql||{}),q$=U.z.enum(ql),Hl=(e=>(e.Cash="CASH",e.Tokens="TOKENS",e))(Hl||{}),H$=U.z.enum(Hl),$l=(e=>(e.FirstEntry="FIRST_ENTRY",e.EntryCost="ENTRY_COST",e.CurrentValue="CURRENT_VALUE",e.Updated="UPDATED",e))($l||{}),$$=U.z.enum($l),oi=U.z.preprocess(e=>e===""?void 0:e,U.z.string().optional()),sne=U.z.preprocess(e=>e===999?void 0:e,U.z.number().int().optional()),ine=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:one,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:sne,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,zn.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})),ane=U.z.object({proxy_wallet:J,value:H}).transform(({proxy_wallet:e,value:t})=>({wallet:e,value:t})),Vl=(e=>(e.Max="max",e.OneMonth="1m",e.OneWeek="1w",e.OneDay="1d",e.TwelveHours="12h",e.SixHours="6h",e))(Vl||{}),JC=U.z.enum(Vl),jl=(e=>(e.OneDay="1d",e.EighteenHours="18h",e.TwelveHours="12h",e.ThreeHours="3h",e.OneHour="1h",e))(jl||{}),p0=U.z.enum(jl),pn=H.nullish().transform(e=>e??null),V$=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:A,volume_usdc:k,trade_count:T,...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:A,volumeUsdc:k,tradeCount:T})),lne=U.z.object({proxy_wallet:J,interval:JC,fidelity:p0,source_fidelity:p0,points:U.z.array(V$)}).transform(({proxy_wallet:e,source_fidelity:t,...n})=>({...n,wallet:e,sourceFidelity:t})),cne=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})),une=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:V$.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})),dne=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})),pne=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:re.nullish(),event:dne.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})),j$=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:re.nullish(),leg_current_price:H.nullish(),market:pne.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})),mne=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:re,resolved_at:re.nullish(),legs_total:U.z.number().int(),legs_resolved:U.z.number().int(),legs_pending:U.z.number().int(),legs:U.z.array(j$),updated_at:re}).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})),W$=us(ine),z$=si(ane),G$=si(une.nullable()),K$=si(lne),Y$=si(cne),Q$=us(mne),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||{}),hne=U.z.enum(Wl),fne=U.z.object({id:sI,type:hne,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(j$)}),gne=fne.transform(vne),Kt=U.z.preprocess(e=>e===""?void 0:e,U.z.string().optional()),X$=U.z.preprocess(e=>e===999?void 0:e,U.z.number().int().optional()),yne=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:X$,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})),bne=U.z.object({proxy_wallet:J,timestamp:wo,condition_id:U.z.preprocess(e=>e===""?void 0:e,xe.optional()),type:XC,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,B$]).optional()),is_combo:U.z.boolean().optional(),outcome_index:X$,title:Kt,slug:Kt,icon:Kt,event_slug:Kt,outcome:Kt,name:Kt,pseudonym:Kt,bio:Kt,profile_image:Kt,profile_image_optimized:Kt}),wne=bne.transform(xne),J$=us(yne),Z$=us(wne),e4=us(gne);Po=(e=>(e.Max="max",e.OneMonth="1m",e.OneWeek="1w",e.OneDay="1d",e.SixHours="6h",e.OneHour="1h",e))(Po||{}),t4=U.z.enum(Po),Sne=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})),n4=us(Sne),yf=U.z.preprocess(e=>e===""?null:e,U.z.string().nullable()),Pne=U.z.object({proxy_wallet:J,bio:yf,token_id:Me,pseudonym:yf,amount:H,display_username_public:U.z.boolean(),outcome_index:U.z.preprocess(e=>e===999?null:e,U.z.number().int().nullable()),name:yf,profile_image:yf,profile_image_optimized:yf,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})),Ene=U.z.object({token_id:Me,holders:U.z.array(Pne)}).transform(({holders:e,token_id:t})=>({assetId:t,token:t,holders:e})),Rne=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})),_ne=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})),Ine=U.z.object({taker_volume_total:H,conditions:U.z.array(_ne)}).transform(({conditions:e,taker_volume_total:t})=>({markets:e,takerVolumeTotal:t})),r4=us(Ene),o4=si(U.z.array(Rne)),s4=si(Ine),zl=(e=>(e.Day="day",e.Week="week",e.Month="month",e.All="all",e))(zl||{}),bf=U.z.enum(zl),Gl=(e=>(e.Day="day",e.Week="week",e.Month="month",e.Year="all",e))(Gl||{}),i4=U.z.enum(Gl),Kl=(e=>(e.Pnl="PNL",e.Volume="VOLUME",e))(Kl||{}),a4=U.z.enum(Kl),Yl=(e=>(e.Market="market",e.Combo="combo",e))(Yl||{}),PNe=U.z.enum(Yl),Cne=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}})),Nne=U.z.object({date:zn,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}})),cs=U.z.preprocess(Gn,U.z.string().nullable()),One=U.z.object({rank:U.z.number().int().min(0),user_id:J,pnl:H,volume:H,user_name:cs,profile_image:cs,x_username:cs,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})),Lne=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:cs,profile_image:cs,x_username:cs,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})),Dne=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:cs,profile_image:cs}),Une=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:cs,profile_image:cs}),Bne=U.z.discriminatedUnion("kind",[Dne,Une]).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}),l4=us(Cne),c4=si(U.z.array(Nne)),u4=us(One),d4=si(Lne.nullable()),p4=us(Bne),Ql=(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))(Ql||{}),Mne=U.z.enum(Ql),Xl=(e=>(e.Binary="BINARY",e.IncrementalNegRisk="INCREMENTAL_NEGRISK",e.AtomicNegRisk="ATOMIC_NEGRISK",e))(Xl||{}),Fne=U.z.enum(Xl),Jl=(e=>(e.Reported="reported",e.Derived="derived",e))(Jl||{}),qne=U.z.enum(Jl),Zl=(e=>(e.UmaOptimisticOracle="UMA_OO",e.Chainlink="CHAINLINK",e.Eoa="EOA",e))(Zl||{}),Hne=U.z.enum(Zl),U$=U.z.number().int().min(0).transform(String).pipe(bn),$ne=U.z.object({question_id:vo.optional(),condition_id:xe.optional(),status:Mne,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:Yi,market_type:Fne.optional(),payouts:U.z.tuple([U$,U$]).optional(),resolution_source:qne.optional(),reporter:Hne.optional(),was_arbitrated:U.z.boolean().optional(),resolved_block:U.z.number().int().min(0).optional(),resolved_at:re.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}),m4=si(U.z.array($ne))});var Pe,Od,h4,g0,f4,Ir,_Ne,Vne,Ld,g4,jne,y4,Wne,zne,Gne,Kne,Yne,b4,ZC,w4,v4,k4=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||{}),h4=Pe.z.object({status:Pe.z.enum(Od),transactionHash:et.nullish().transform(e=>e??null),transactionId:Ji}),g0=(e=>(e.PENDING="PENDING",e.FENCED="FENCED",e.SWEPT="SWEPT",e.CHAIN_SUBMITTED="CHAIN_SUBMITTED",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED",e))(g0||{}),f4=Pe.z.object({status:Pe.z.enum(g0),transactionId:Ji}),Ir=(e=>(e.SAFE="SAFE",e.PROXY="PROXY",e.SAFE_CREATE="SAFE-CREATE",e.WALLET="WALLET",e.WALLET_CREATE="WALLET-CREATE",e))(Ir||{}),_Ne=Pe.z.enum(Ir),Vne=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||{}),g4=Pe.z.enum(Ld),jne=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()}),y4=Pe.z.object({address:J,nonce:Pe.z.string().min(1)}),Wne=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:jne,to:J,type:Vne,value:Pe.z.string().optional()}),zne=Pe.z.object({data:Pe.z.string().min(1),target:J,value:Pe.z.string().min(1)}),Gne=Pe.z.object({calls:Pe.z.array(zne).min(1),deadline:Pe.z.string().min(1),depositWallet:J}),Kne=Pe.z.object({depositWalletParams:Gne,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")}),Yne=Pe.z.object({from:J,metadata:Pe.z.string().optional(),to:J,type:Pe.z.literal("WALLET-CREATE")}),b4=Pe.z.union([Wne,Kne,Yne]),ZC=Pe.z.object({state:g4,transactionHash:et.nullish().transform(e=>e??null),transactionID:Ji}).transform(({transactionHash:e,transactionID:t,...n})=>({...n,transactionHash:e??null,transactionId:t})),w4=Pe.z.object({deployed:Pe.z.boolean()}),v4=Pe.z.object({error_msg:Pe.z.string().nullish(),state:g4,transaction_hash:Pe.z.union([Pe.z.literal(""),et]).transform(e=>e===""?null:e),transaction_id:Ji}).transform(({error_msg:e,transaction_hash:t,transaction_id:n,...r})=>({...r,errorMsg:e??null,transactionHash:t??null,transactionId:n}))});var ee,Nn,Eo,ds,ps,Xr,Cr,tN,nN,Qne,Xne,Jne,Zne,x4,ere,tre,nre,rre,ore,sre,ire,are,lre,cre,ure,A4,mn,li,ci,Ro,T4,dre,pre,mre,hre,fre,S4,rN,oN,Dd,gre,yre,eN,bre,P4,E4,R4,y0=L(()=>{"use strict";CC();xo();ee=require("zod");Al();Nn=(e=>(e.Buy="BUY",e.Sell="SELL",e))(Nn||{}),Eo=(e=>(e.Yes="YES",e.No="NO",e))(Eo||{}),ds=(e=>(e.Confirm="CONFIRM",e.Decline="DECLINE",e))(ds||{}),ps=(e=>(e.Matched="MATCHED",e.Mined="MINED",e.Confirmed="CONFIRMED",e.Retrying="RETRYING",e.Failed="FAILED",e))(ps||{}),Xr=(e=>(e.Notional="notional",e.Shares="shares",e))(Xr||{}),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||{}),tN=ee.z.enum(Nn),nN=ee.z.literal("YES"),Qne=ee.z.enum(ds),Xne=ee.z.enum(ps),Jne=ee.z.string().transform(e=>e),Zne=ee.z.object({id:Qi,condition_id:xe,position_ids:ee.z.array(Xe),pending:ee.z.boolean(),slug:ee.z.string(),title:ee.z.string(),outcomes:ee.z.array(ee.z.string()),outcome_prices:ee.z.array(R),image:ee.z.string(),volume:ee.z.number(),tags:ee.z.array(ee.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})),x4=ee.z.object({markets:ee.z.array(Zne),next_cursor:ye.nullish()}).transform(e=>({markets:e.markets,nextCursor:e.next_cursor??void 0})),ere=ee.z.discriminatedUnion("unit",[ee.z.object({unit:ee.z.literal("notional"),value_e6:bn}),ee.z.object({unit:ee.z.literal("shares"),value_e6:bn})]).transform(e=>({unit:e.unit,value:e.value_e6})),tre=(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))(tre||{}),nre=ee.z.object({type:ee.z.literal("auth"),success:ee.z.boolean(),address:J.optional(),role:ee.z.string().optional(),error:ee.z.string().optional()}),rre=ee.z.object({type:ee.z.literal("RFQ_REQUEST"),rfq_id:ar,requestor_public_id:Rw,leg_position_ids:ee.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:tN,side:nN,requested_size:ere,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})),ore=ee.z.object({type:ee.z.literal("ACK_RFQ_QUOTE"),rfq_id:ar,quote_id:Xi}).transform(e=>({quoteId:e.quote_id,rfqId:e.rfq_id,type:"quote_ack"})),sre=ee.z.object({type:ee.z.literal("ACK_RFQ_QUOTE_CANCEL"),rfq_id:ar,quote_id:Xi}).transform(e=>({quoteId:e.quote_id,rfqId:e.rfq_id,type:"quote_cancel_ack"})),ire=ee.z.object({type:ee.z.literal("RFQ_CONFIRMATION_REQUEST"),rfq_id:ar,quote_id:Xi,signer_address:J,maker_address:J,signature_type:IC,leg_position_ids:ee.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:tN,side:nN,fill_size_e6:bn,price_e6:bn,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})),are=ee.z.object({type:ee.z.literal("ACK_RFQ_CONFIRMATION_RESPONSE"),rfq_id:ar,quote_id:Xi,decision:Qne}).transform(e=>({decision:e.decision,quoteId:e.quote_id,rfqId:e.rfq_id,type:"confirmation_ack"})),lre=ee.z.object({type:ee.z.literal("RFQ_EXECUTION_UPDATE"),rfq_id:ar,status:Xne,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"})),cre=ee.z.object({type:ee.z.literal("RFQ_TRADE"),rfq_id:ar,requester_id:Rw,condition_id:Zt,leg_position_ids:ee.z.array(Xe),direction:tN,side:nN,price_e6:bn,size_e6:bn,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"})),ure=ee.z.object({type:ee.z.literal("RFQ_ERROR"),error_id:ee.z.string().optional(),request_type:ee.z.string().optional(),rfq_id:ar.optional(),quote_id:Xi.optional(),code:Jne,error:ee.z.string(),request:ee.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"})),A4=ee.z.discriminatedUnion("type",[nre,rre,ore,sre,ire,are,lre,cre,ure]),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||{}),T4=ee.z.object({code:ee.z.string().transform(e=>e),message:ee.z.string()}).transform(e=>({code:e.code,message:e.message})),dre=ee.z.object({quote_id:Xi,blended_price_e6:bn,maker_amount_e6:bn,taker_amount_e6:bn,total_required_e6:bn,net_receive_e6:bn.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}})),pre=ee.z.object({unit:ee.z.enum(Xr),value_e6:ee.z.string().regex(/^\d+$/).transform(e=>BigInt(e).toString())}).transform(e=>({unit:e.unit,valueE6:e.value_e6})),mre=ee.z.object({rfq_id:ar,leg_position_ids:ee.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:ee.z.enum(Nn),side:ee.z.enum(Eo),requested_size:pre}).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})),hre=ee.z.object({rfq_id:ar,status:ee.z.literal("AWAITING_REQUESTER_ACCEPTANCE"),expires_at:pe,builder_code:bo,request:mre,quote:dre}).transform(e=>({builderCode:e.builder_code,expiresAt:e.expires_at,quote:e.quote,request:e.request,rfqId:e.rfq_id,status:e.status})),fre=ee.z.object({rfq_id:ar,status:ee.z.enum(["FAILED","EXPIRED","CANCELED"]),error:T4.optional()}).transform(e=>({rfqId:e.rfq_id,status:e.status,...e.error===void 0?{}:{error:e.error}})),S4=ee.z.union([hre,fre]),rN=ee.z.object({rfq_id:ar,status:ee.z.union([ee.z.enum(mn),ee.z.enum(ps)]),taker_order_hash:ee.z.string().optional(),tx_hash:et.optional(),error:T4.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}})),oN=ee.z.string().transform(e=>Wn(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||{}),gre=ee.z.string().transform(e=>e),yre=ee.z.object({kind:gre,condition_id:Zt.optional(),event_id:Gt.optional(),position_id:Xe.optional(),condition_index:ee.z.number().int().nonnegative().optional().default(0),amount:bn}).transform(e=>({amount:e.amount,conditionId:e.condition_id,conditionIndex:e.condition_index,eventId:e.event_id,kind:e.kind,positionId:e.position_id})),eN=ee.z.object({position_id:Xe,amount:bn}).transform(e=>({amount:e.amount,positionId:e.position_id})),bre=ee.z.object({consumed:ee.z.array(eN),created:ee.z.array(eN)}).transform(e=>({consumed:e.consumed,created:e.created})),P4=ee.z.object({to:J,data:oN}).transform(e=>({data:e.data,to:e.to})),E4=ee.z.looseObject({planHash:oN,chainId:ee.z.number().int(),wallet:J,routerCall:P4}),R4=ee.z.object({plan_hash:oN,chain_id:ee.z.number().int(),wallet:J,block_number:ee.z.string().regex(/^\d+$/).transform(BigInt),starting_pusd:R,net_pusd_out:R,final_pusd:R,operations:ee.z.array(yre),operation_count:ee.z.number().int(),truncated:ee.z.boolean(),estimated_cost:ee.z.number(),required_pusd_input:R,required_positions:ee.z.array(eN),position_summary:bre.optional(),candidate_position_ids:ee.z.array(Xe),router_call:P4}).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 ec,_4,sN,wre,I4,iN=L(()=>{"use strict";PC();xo();ec=require("zod"),_4=ec.z.number().int().transform(e=>e===0?null:pd(e)),sN=ec.z.object({status:ec.z.literal("ok"),deadline:_4}),wre=ec.z.object({deadline:_4,triggered:ec.z.number().int().nonnegative(),daily_limit:ec.z.number().int().nonnegative(),next_reset:pe}).transform(e=>({deadline:e.deadline,triggered:e.triggered,dailyLimit:e.daily_limit,nextReset:e.next_reset})),I4=wre});function C4(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 vre(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 Are(e,t,n){kre.encodeInto(e,t.subarray(n))}function N4(e,t,n){e.length>xre?Are(e,t,n):vre(e,t,n)}var kre,xre,HNe,O4=L(()=>{"use strict";kre=new TextEncoder,xre=50;HNe=new TextDecoder});var tc,L4=L(()=>{"use strict";tc=class{type;data;constructor(t,n){this.type=t,this.data=n}}});var b0,D4=L(()=>{"use strict";b0=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 U4(e,t,n){let r=n/4294967296,o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function w0(e,t,n){let r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function B4(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}var aN=L(()=>{"use strict"});function Ere({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=Pre)if(t===0&&e<=Sre){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),w0(r,4,e),n}}function Rre(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 _re(e){if(e instanceof Date){let t=Rre(e);return Ere(t)}else return null}function Ire(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=B4(t,4),r=t.getUint32(0);return{sec:n,nsec:r}}default:throw new b0(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function Cre(e){let t=Ire(e);return new Date(t.sec*1e3+t.nsec/1e6)}var Tre,Sre,Pre,M4,F4=L(()=>{"use strict";D4();aN();Tre=-1,Sre=4294967296-1,Pre=17179869184-1;M4={type:Tre,encode:_re,decode:Cre}});var v0,q4=L(()=>{"use strict";L4();F4();v0=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(M4)}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 tc(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 tc(i,s)}}}return t instanceof tc?t:null}decode(t,n,r){let o=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return o?o(t,n,r):new tc(n,t)}}});function Nre(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function H4(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Nre(e)?new Uint8Array(e):Uint8Array.from(e)}var $4=L(()=>{"use strict"});var Ore,Lre,k0,V4=L(()=>{"use strict";O4();q4();aN();$4();Ore=100,Lre=2048,k0=class e{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??v0.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??Ore,this.initialBufferSize=t?.initialBufferSize??Lre,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=C4(t);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),N4(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=H4(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),U4(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),w0(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 lN(e,t){return new k0(t).encodeSharedRef(e)}var j4=L(()=>{"use strict";V4()});var W4=L(()=>{"use strict";j4()});function ui(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}var cN=L(()=>{"use strict"});var x0,Ud,z4=L(()=>{"use strict";x0=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 x0(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 x0(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 Dre(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 Dre(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(A){w(A)}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,A;w!=null&&(v=new Promise((k,T)=>{A=()=>{T(new uN)},w.addEventListener("abort",A)}));try{await Promise.race([a.promise,v])}finally{A!=null&&w!=null&&w?.removeEventListener("abort",A)}}},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 uN,dN=L(()=>{"use strict";cN();z4();uN=class extends Error{type;code;constructor(t,n){super(t??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}});function Ure(e){return e.reason}function G4(e,t,n){if(t==null||e==null)return e;let r=n?.translateError??Ure;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 K4=L(()=>{"use strict"});function Y4(){return new pN}var pN,Q4=L(()=>{"use strict";cN();K4();pN=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 G4(this.readNext.promise,n?.signal,n)}}});function X4(e){return e[Symbol.asyncIterator]!=null}async function Bre(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*Mre(e){let t=new AbortController,n=Y4(),r=e.map(o=>X4(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());Bre(r,n,t.signal).catch(()=>{});try{yield*n}finally{t.abort();for(let o of r)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*Fre(e){for(let t of e)yield*t}function qre(...e){let t=[];for(let n of e)X4(n)||t.push(n);return t.length===e.length?Fre(t):Mre(e)}var J4,Z4=L(()=>{"use strict";Q4();J4=qre});function M(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 Hre(JSON.stringify(e))}function _o(e,t,n="Invalid pagination cursor"){try{return t.parse(JSON.parse(I6(e)))}catch(r){throw new E(n,{cause:r})}}function _6(e){try{return JSON.parse(I6(e))}catch{return}}function Hre(e){return btoa(String.fromCharCode(...new TextEncoder().encode(e)))}function I6(e){return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}function sa(e){return di(C6.parse(e))}function Md(e,t,n={}){return e===void 0?{offset:0,pageSize:t}:N6(_o(e,h.z.unknown()),n)}function N6(e,t={}){let n=C6.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 Nl(`Pagination reached this listing's supported depth limit (${t.maxOffset}); whether more items exist cannot be established.`);return r}function O6(e,t){return di({kind:"keyset",fingerprint:D6(t),cursor:e})}function L6(e,t){if(!Vre(e))return;let n=$re.safeParse(e);if(!n.success)throw new E("Invalid pagination cursor",{cause:n.error});if(t===void 0||n.data.fingerprint!==D6(t))throw new E("Pagination cursor was created for a different query");return n.data.cursor}function Vre(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="keyset"}function D6(e){return JSON.stringify(wN(e))}function wN(e){return Array.isArray(e)?e.map(wN):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,wN(n)])):e}function W(e){return function(t){return In.fromPromise(t.json(),()=>new C(`Received non-JSON response from ${t.url}`)).andThen(n=>Wre(t.url,e,n))}}function jre(e){return In.fromPromise(e.blob(),()=>new C(`Received unreadable binary response from ${e.url}`))}function Wre(e,t,n){let r=t.safeParse(n);return r.success?go(r.data):Sr(C.fromZodError(r.error,{endpoint:e}))}function zre(e){if(!(e instanceof O)||!U6(e.cause))return!1;let t=[e.cause.message,Gre(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 e6(e){return!B6(e)||e.jsonrpc!=="2.0"?!1:"error"in e?U6(e.error):"result"in e}function U6(e){return B6(e)&&typeof e.code=="number"&&typeof e.message=="string"}function B6(e){return typeof e=="object"&&e!==null}function M6(e){return/^0x[a-fA-F0-9]*$/.test(e)}function t6(e,t="eth_call"){if(typeof e!="string"||!M6(e))throw new C(`Expected JSON-RPC ${t} result to be a hex string`);return e}function n6(e){return`0x${e.toString(16)}`}function Gre(e){if(e===void 0)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function F6(e,t,n){let r=foe(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 rc(e){let t=pi(e.walletType);return{maker:e.wallet,signatureType:t,signer:t===Rr.POLY_1271?e.wallet:e.signer}}function O0(e,t){return e.signerType==="OWNER"?t:Qre(e.signer,t)}function Qre(e,t){let n=Wn(`0x${e.slice(2).padStart(64,"0")}`),r=Wt.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes"}],[n,Kre,t]);return cq(`${r}${Yre.slice(2)}`)}function Jre(e){let t=Xre.replace("%s",e.proxyFactory.slice(2).toLowerCase()).replace("%s",e.proxyImplementation.slice(2).toLowerCase());return Wn(Je.keccak256(`0x${t}`))}function Zre(e,t){return Be(ho.fromCreate2({bytecodeHash:Jre(t),from:t.proxyFactory,salt:Je.keccak256(Wt.encodePacked(["address"],[e]))}))}function eoe(e,t){return Be(ho.fromCreate2({bytecodeHash:t.safeInitCodeHash,from:t.safeFactory,salt:Je.keccak256(Wt.encode([{name:"address",type:"address"}],[e]))}))}function L0(e,t){let n=Wn(`0x${e.slice(2).padStart(64,"0")}`),r=Wt.encode([{type:"address"},{type:"bytes32"}],[t.depositWalletFactory,n]);return Be(ho.fromCreate2({bytecodeHash:coe(t.depositWalletImplementation,r),from:t.depositWalletFactory,salt:Je.keccak256(r)}))}function Pf(e,t){let n=Wn(`0x${e.slice(2).padStart(64,"0")}`),r=Wt.encode([{type:"address"},{type:"bytes32"}],[t.depositWalletFactory,n]);return Be(ho.fromCreate2({bytecodeHash:uoe(t.depositWalletBeacon,r),from:t.depositWalletFactory,salt:Je.keccak256(r)}))}function coe(e,t){let n=BigInt((t.length-2)/2),r=roe+(n<<56n);return Wn(Je.keccak256(we.concat(we.fromNumber(r,{size:10}),we.fromHex(e),we.fromHex("0x6009"),we.fromHex(noe),we.fromHex(toe),we.fromHex(t)),{as:"Hex"}))}function uoe(e,t){let n=BigInt((t.length-2)/2),r=aoe+(n<<56n);return Wn(Je.keccak256(we.concat(we.fromNumber(r,{size:10}),we.fromHex(e),we.fromHex(ioe),we.fromHex(soe),we.fromHex(ooe),we.fromHex(t)),{as:"Hex"}))}async function doe(e,t){try{let n=await e.ethCall({to:t,data:loe});return hoe(n)}catch(n){if(zre(n))return rs;throw n}}async function poe(e,t){let n=await doe(e,t);return!zt(n,rs)}async function moe(e,t,n){return await poe(e,n.depositWalletFactory)?Pf(t,n):L0(t,n)}function hoe(e){return e.length<66?rs:Be(`0x${e.slice(-40)}`)}function foe(e,t,n){if(zt(n,t))return{signerType:"OWNER",walletType:Se.EOA};let r=e.walletDerivation;return zt(n,Pf(t,r))?{signerType:"OWNER",walletType:Se.DEPOSIT_WALLET}:zt(n,L0(t,r))?{signerType:"OWNER",walletType:Se.DEPOSIT_WALLET}:zt(n,eoe(t,r))?{signerType:"OWNER",walletType:Se.GNOSIS_SAFE}:zt(n,Zre(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:q6,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:q6.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(yoe(t))return boe(e,t.exceptions);let n=new URLSearchParams;for(let[r,o]of Object.entries(t)){let s=e[r];if(s!==void 0){if(DN(s)){for(let i of s)n.append(o,ia(i));continue}n.append(o,ia(s))}}return n}function Ee(e={}){return{format:"snake_case",exceptions:e}}function goe(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(ia).join(","));continue}t.append(n,ia(r))}return t}function aa(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=$6(n);if(DN(r)){t.append(o,r.map(ia).join(","));continue}t.append(o,ia(r))}return t}function yoe(e){return"format"in e}function boe(e,t){let n=new URLSearchParams;for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=t[r]??$6(r);if(DN(o)){for(let i of o)n.append(s,ia(i));continue}n.append(s,ia(o))}return n}function DN(e){return Array.isArray(e)}function $6(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ia(e){return String(e)}async function B0(e){return(await X(e.secureClob.get("/auth/ban-status/closed-only").andThen(W(b3)))).closedOnly}function F0(e,t){let n=M(t,voe),{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(W(w3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function H0(e,t){let n=M(t,koe);return X(e.secureClob.get(`/data/order/${n.orderId}`).andThen(W(NC)))}function Ef(e,t){let n=M(t,Aoe),{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(W(v3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function j0(e){let t=pi(e.account.walletType);return X(e.secureClob.get("/notifications",{params:ve({signatureType:t},Ee())}).andThen(W(G3)))}async function z0(e,t){let n=M(t,Toe),r=pi(e.account.walletType),o=ve({ids:n.ids.join(","),signatureType:r},Ee());await X(e.secureClob.del("/notifications",{params:o}))}async function G0(e,t){let n=M(t,Soe),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(W(x3)))}async function UN(e,t){let n=M(t,Poe),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})),G0(e,n)}async function Y0(e,t){let n=M(t,Eoe);return(await X(e.secureClob.get("/order-scoring",{params:ve(n,Ee())}).andThen(W(A3)))).scoring}async function X0(e,t){let n=M(t,Roe).orderIds;return X(e.secureClob.post("/orders-scoring",{json:n}).andThen(W(T3)))}function Z0(e,t){let{cursor:n,...r}=M(t,z6),o=pi(e.account.walletType);return Fe(s=>e.secureClob.get("/rewards/user",{params:ve({...r,nextCursor:s,signatureType:o},Ee())}).andThen(W(S3)).map(i=>({items:i.data,hasMore:i.nextCursor!==Yn,nextCursor:i.nextCursor===Yn?void 0:i.nextCursor})),n)}async function tv(e,t){let n=M(t,z6),r=pi(e.account.walletType);return X(e.secureClob.get("/rewards/user/total",{params:ve({...n,signatureType:r},Ee())}).andThen(W(P3)))}function rv(e,t){let{cursor:n,...r}=M(t,_oe),o=pi(e.account.walletType);return Fe(s=>e.secureClob.get("/rewards/user/markets",{params:ve({...r,nextCursor:s,signatureType:o},Ee())}).andThen(W(R3)).map(i=>({items:i.data,hasMore:i.nextCursor!==Yn,nextCursor:i.nextCursor===Yn?void 0:i.nextCursor})),n)}async function sv(e){let t=pi(e.account.walletType);return X(e.secureClob.get("/rewards/user/percentages",{params:ve({signatureType:t},Ee())}).andThen(W(E3)))}function nn(e,t={}){let{retries:n=2,maxDelaySeconds:r=5,sleep:o=os}=t;function s(i){return e().orElse(a=>{if(!(a instanceof $)||i<=0)return xl(a);let l=a.retryAfter??1;return l>r?xl(a):In.fromSafePromise(o(l*1e3).catch(()=>{})).andThen(()=>s(i-1))})}return s(n)}function av(e,t={}){let{cursor:n,pageSize:r,window:o,...s}=M(t,Ioe);return Fe(i=>nn(()=>e.data.get("/v2/trades",{params:tn({...s,...o,limit:r,cursor:i})})).andThen(W(J$)),n)}function Rf(e,t){let{cursor:n,pageSize:r,window:o,...s}=M(t,Coe);return Fe(i=>nn(()=>e.data.get("/v2/activity",{params:tn({...s,...o,excludeDepositsWithdrawals:!1,limit:r,cursor:i})})).andThen(W(Z$)),n)}function _f(e,t){let{cursor:n,pageSize:r,...o}=M(t,Noe);return Fe(s=>nn(()=>e.data.get("/v2/activity/combos",{params:tn({...o,limit:r,cursor:s})})).andThen(W(e4)),n)}function vf(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:Joe(t,n),to:e}}function MN(e,t,n){return{data:Ie.encodeData(G6,[t,n]),to:e}}function FN(e){return Ie.decodeResult(G6,e)}function kf(e,t,n){return{data:Zoe(t,n),to:e}}function qN(e,t,n){return{data:Ie.encodeData(K6,[t,n]),to:e}}function HN(e){return Ie.decodeResult(K6,e)}function $N(e,t,n){return{data:Ie.encodeData(Y6,[t,hs(BigInt(n),"Position ID")]),to:e}}function VN(e){return Ie.decodeResult(Y6,e)}function If(e,t,n){return{data:Ie.encodeData(Q6,[n.map(()=>t),n.map(r=>hs(BigInt(r),"id"))]),to:e}}function Cf(e){return Ie.decodeResult(Q6,e)}function P0(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:ese(t,n),to:e}}function jN(e,t,n){return{data:Ie.encodeData(Moe,[t,hs(n,"Session key expiry")]),to:e}}function WN(e,t){return{data:Ie.encodeData(Foe,[t]),to:e}}function zN(e,t,n,r){if(n<=0n)throw new E("Perps deposit amount must be positive");return{data:Ie.encodeData(qoe,[t,hs(n,"Perps deposit amount"),r]),to:e}}function GN(e,t,n,r){return{data:tse(t,n,r),to:e}}function KN(e,t,n,r){return{data:nse(t,n,r),to:e}}function YN(e,t,n){return{data:rse(t,n),to:e}}function uv(e,t,n){return{data:Ie.encodeData(Woe,[QN(t),hs(n,"Split amount")]),to:e}}function dv(e,t,n){return{data:Ie.encodeData(zoe,[QN(t),hs(n,"Merge amount")]),to:e}}function xf(e,t,n,r){return{data:Ie.encodeData(Goe,[QN(t),BigInt(ose(n)),hs(r,"Redeem amount")]),to:e}}function pv(e,t){return{data:Ie.encodeData(Koe,[t.map(n=>hs(n,"Leg position ID"))]),to:e}}function Joe(e,t){return fe(t>=0n,"Approval amount must be non-negative"),Ie.encodeData(Uoe,[e,t])}function Zoe(e,t){return Ie.encodeData(Hoe,[e,t])}function ese(e,t){return Ie.encodeData(Boe,[e,t])}function tse(e,t,n){return Ie.encodeData($oe,[e,BN,t,X6,hs(n,"Split amount")])}function nse(e,t,n){return Ie.encodeData(Voe,[e,BN,t,X6,hs(n,"Merge amount")])}function rse(e,t){return Ie.encodeData(joe,[e,BN,t,Xoe])}function hs(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 QN(e){if(Loe.test(e))return e.toLowerCase();if(Doe.test(e)){let t=e.toLowerCase();if(t.endsWith("00")||t.endsWith("01"))return t.slice(0,Ooe)}throw new E("Protocol v2 condition ID must be bytes31, or bytes32 with a binary outcome byte")}function ose(e){if(e!==0&&e!==1)throw new E("Protocol v2 outcome index must be 0 or 1");return e}function XN(e){return Ie.encodeData(Qoe,[e.map(t=>({typeCode:1,to:t.to,value:t.value??0n,data:t.data}))])}function JN(e){let t=e.map(n=>sse(n));return Ie.encodeData(Yoe,[t.length===0?"0x":Wt.encodePacked(Array.from({length:t.length},()=>"bytes"),t)])}function sse(e){let t=e.value??0n;return Wt.encodePacked(["uint8","address","uint256","uint256","bytes"],[0,e.to,t,BigInt((e.data.length-2)/2),e.data])}function wn(e,t="Expected a TransactionHandle"){return fe(typeof e=="object"&&e!==null&&"transactionHash"in e&&"transactionId"in e&&"wait"in e&&typeof e.wait=="function",t),e}function c8(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 vn(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 ZN(){return{kind:"requestAddress"}}function Qn(e,t){return{chainId:e,...t}}async function Nf(e,t){let n=M(t,mse);return X(e.relayer.get("/v1/account/transactions/params",{params:ve(n,{address:"address",type:"type"})}).andThen(W(y4)))}async function Of(e,t){let n=await gse(e,t);return n.type===Se.EOA?!1:X(e.relayer.get("/deployed",{params:ve({address:n.wallet,type:n.type===Se.DEPOSIT_WALLET?Ir.WALLET:void 0},{address:"address",type:"type"})}).andThen(W(w4)).map(({deployed:r})=>r))}async function gse(e,t){if(t!==void 0)return M(t,fse);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 moe(e.rpc,e.account.signer,e.environment.walletDerivation),type:Se.DEPOSIT_WALLET}}async function mv(e){return fe(e.supportsGasless,"Deposit Wallet deployment requires a Relayer API Key or Builder API Key in the client configuration."),Af(e,{from:e.account.signer,metadata:"Deploy Deposit Wallet",to:e.environment.walletDerivation.depositWalletFactory,type:Ir.WALLET_CREATE})}async function eO(e,t){let n=M(t,hse);return X(e.relayer.get(`/v1/account/transactions/${n.transactionId}`).andThen(W(v4)))}async function Or(e,t){let n=M(t,bse);return fe(e.supportsGasless,"Gasless transactions require a Relayer API Key or Builder API Key in the client configuration."),fe(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 ZN());fe(r===e.account.signer,"Wallet client address does not match the authenticated signer");for(let o=0;o<=r6;o+=1)try{switch(e.account.walletType){case Se.POLY_PROXY:return yield*wse(e,n);case Se.DEPOSIT_WALLET:return yield*vse(e,n);case Se.GNOSIS_SAFE:return yield*kse(e,n)}fe(!1,"Unsupported wallet type for gasless transaction")}catch(s){if(!bv(s)||o===r6)throw s;await os(e.environment.relayerPollFrequencyMs)}fe(!1,"Expected gasless transaction retry loop to return")}.call(null)}async function*wse(e,t){let n=yield*hv(e,t.calls,t.metadata);return Af(e,n)}async function*hv(e,t,n){let r=await Nf(e,{address:e.account.signer,type:Ir.PROXY}),o=e.environment.walletDerivation.proxyFactory,s=XN(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=Sse(e.account.signer,o,s,i,a,l,r.nonce,c,u),p=ss(yield g8(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:Ir.PROXY}}function fv(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*vse(e,t){let n=yield*qd(e,t.calls,t.metadata);try{return await Af(e,n)}catch(r){let o=fv(r);if(o===void 0)throw r;let s=yield*gv(e,n,t.calls,o);return Af(e,s)}}async function*qd(e,t,n){let r=await Nf(e,{address:e.account.signer,type:Ir.WALLET}),o=t.map(h8),s=`${Math.floor(Date.now()/1e3)+use}`,i=O0(e.account,ss(yield y8(f8({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:Ir.WALLET}}async function*gv(e,t,n,r){let o=O0(e.account,ss(yield y8(f8({calls:n.map(h8),chainId:e.environment.chainId,deadline:t.depositWalletParams.deadline,nonce:r,wallet:e.account.wallet}))));return{...t,nonce:r,signature:o}}async function*kse(e,t){let n=yield*yv(e,t.calls,t.metadata);return Af(e,n)}async function*yv(e,t,n){let r=await Nf(e,{address:e.account.signer,type:Ir.SAFE}),o=xse(t,e.environment.contracts.safeMultisend),s=Tse({chainId:e.environment.chainId,data:o.data,nonce:r.nonce,operation:o.operation,safeAddress:e.account.wallet,to:o.to,value:o.value}),i=ss(yield g8(Wn(fo.getSignPayload(s))));return{data:o.data,from:e.account.signer,...n!==void 0&&{metadata:n},nonce:r.nonce,proxyWallet:e.account.wallet,signature:Pse(i),signatureParams:Ase(o.operation),to:o.to,type:Ir.SAFE,value:o.value>0n?`${o.value}`:void 0}}async function Af(e,t){let n=M(t,b4),r=await X(e.relayer.post("/submit",{json:n}).andThen(W(ZC)));return new Lf(e,r)}function bv(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 h8(e){return{data:e.data,target:e.to,value:`${e.value??0n}`}}function f8(e){let t={chainId:e.chainId,name:lse,verifyingContract:e.wallet,version:cse};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:pse,Call:dse,EIP712Domain:fo.extractEip712DomainTypes(t)}}}function xse(e,t){if(e.length===1){let[n]=e;return{data:n.data,operation:0,to:n.to,value:n.value??0n}}return{data:JN(e),operation:1,to:t,value:0n}}function Ase(e){return{baseGas:"0",gasPrice:"0",gasToken:rs,operation:`${e}`,refundReceiver:rs,safeTxnGas:"0"}}function Tse(e){return{domain:{chainId:e.chainId,verifyingContract:e.safeAddress},message:{baseGas:0n,data:e.data,gasPrice:0n,gasToken:rs,nonce:BigInt(e.nonce),operation:e.operation,refundReceiver:rs,safeTxGas:0n,to:e.to,value:e.value},primaryType:"SafeTx",types:{EIP712Domain:ise,SafeTx:ase}}}function g8(e){return{kind:"signGaslessMessage",payload:e}}function y8(e){return{kind:"signGaslessTypedData",payload:e}}function Sse(e,t,n,r,o,s,i,a,l){return Wn(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 Pse(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 Wn(`0x${t.slice(0,128)}${r.toString(16).padStart(2,"0")}`)}async function tO(e,t){let n=M(t,Ese),r=n.amount==="max"?lr:n.amount;return async function*(){return e.account.walletType===Se.EOA?wn(yield A8(Qn(e.environment.chainId,vf(n.tokenAddress,n.spenderAddress,r)))):yield*await Or(e,{calls:[vf(n.tokenAddress,n.spenderAddress,r)],metadata:n.metadata??`Approve ${n.amount} of ${n.tokenAddress} to ${n.spenderAddress}`})}.call(null)}function Df(e,t){return tO(e,t).then(vn(e.signer))}async function nO(e,t){let n=M(t,Rse);return async function*(){return e.account.walletType===Se.EOA?wn(yield T8(Qn(e.environment.chainId,kf(n.tokenAddress,n.operatorAddress,n.approved)))):yield*await Or(e,{calls:[kf(n.tokenAddress,n.operatorAddress,n.approved)],metadata:n.metadata??`${n.approved?"Approve":"Revoke"} ${n.operatorAddress} on ${n.tokenAddress}`})}.call(null)}function Uf(e,t){return nO(e,t).then(vn(e.signer))}async function Bf(e,t){let{user:n}=M(t,_se),r=await x8(e,n);return{isFullyApproved:r.erc20.length===0&&r.erc1155.length===0,missing:r}}async function rO(e){let t=await x8(e,e.account.wallet),n=t.erc20.map(o=>vf(o.tokenAddress,o.spenderAddress,o.amount)),r=t.erc1155.map(o=>kf(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 wn(yield A8(Qn(e.environment.chainId,o))).wait();for(let o of r)await wn(yield T8(Qn(e.environment.chainId,o))).wait();return}await(yield*await Or(e,{calls:[...n,...r],metadata:"Trading setup approvals"})).wait()}}.call(null)}function Av(e){return rO(e).then(vn(e.signer)).then(()=>{})}async function x8(e,t){let n=Ise(e),r=[...n.erc20.map(a=>MN(a.tokenAddress,t,a.spenderAddress)),...n.erc1155.map(a=>qN(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)=>FN(s[l])<a.amount),erc1155:n.erc1155.filter((a,l)=>!HN(i[l]))}}catch(a){throw new C("Expected JSON-RPC approval checks to return ABI-encoded values",{cause:a})}}function Ise(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 A8(e){return{kind:"sendErc20ApprovalTransaction",request:e}}function T8(e){return{kind:"sendErc1155ApprovalForAllTransaction",request:e}}async function oO(e,t){return X(e.clob.post("/auth/api-key",{headers:U8(t)}).andThen(W(OC)))}async function sO(e,t){return X(e.clob.get("/auth/derive-api-key",{headers:U8(t)}).andThen(W(OC)))}async function Tv(e,t){try{return await oO(e,t)}catch(n){if(!(n instanceof O)||n.status!==400)throw n}return sO(e,t)}async function Sv(e){return(await X(e.secureClob.get("/auth/api-keys").andThen(W(_3)))).apiKeys}async function Pv(e){await X(e.secureClob.del("/auth/api-key").andThen(W(h.z.literal("OK"))))}async function C8(e){return X(e.secureClob.post("/auth/builder-api-key").andThen(W(I3)))}async function O8(e){return X(e.secureClob.get("/auth/builder-api-key").andThen(W(C3)))}async function D8(e){await X(e.clob.del("/auth/builder-api-key").andThen(W(h.z.literal("OK"))))}function U8(e){return{POLY_ADDRESS:e.address,POLY_NONCE:`${e.nonce}`,POLY_SIGNATURE:e.signature,POLY_TIMESTAMP:`${e.timestamp}`}}function Rv(e,t){let n=M(t,Nse),{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(W(N3)).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=M(t,Ose);return(await X(e.clob.get("/midpoint",{params:oc(n)}).andThen(W(D3)))).mid}async function Nv(e,t){let n=M(t,Lse);return X(e.clob.post("midpoints",{json:Jv(n)}).andThen(W(U3)))}async function M8(e,t){let n=M(t,Dse);return(await X(e.clob.get("/tick-size",{params:oc(n)}).andThen(W(t$)))).minimumTickSize}async function q8(e,t){let n=M(t,Use);return(await X(e.clob.get("/neg-risk",{params:oc(n)}).andThen(W(W3)))).negRisk}async function iO(e,t){let n=M(t,Bse);return X(e.clob.get(`/markets-by-token/${n.assetId??n.tokenId}`).andThen(W(V3)))}async function aO(e,t){let n=M(t,Mse);return X(e.clob.get(`/clob-markets/${n.conditionId}`).andThen(W(j3)))}async function lO(e,t){let n=M(t,Fse);return X(e.clob.get(`/fees/builder-fees/${n.builderCode}`).andThen(W(O3)).mapErr(r=>r instanceof O&&r.status===404?new E(`Unknown builder code: ${n.builderCode}`,{cause:r}):r))}async function Lv(e,t){let n=M(t,qse);return(await X(e.clob.get("/price",{params:oc(n)}).andThen(W(B3)))).price}async function Uv(e,t){let n=M(t,Hse);return X(e.clob.post("prices",{json:Qse(n)}).andThen(W(M3)))}async function Hd(e,t){let n=M(t,$se);return X(e.clob.get("/book",{params:oc(n)}).andThen(W(Y3)))}async function Fv(e,t){let n=M(t,Vse);return X(e.clob.post("books",{json:Jv(n)}).andThen(W(Q3)))}async function Hv(e,t){let n=M(t,jse);return(await X(e.clob.get("/spread",{params:oc(n)}).andThen(W(F3)))).spread}async function Vv(e,t){let n=M(t,Wse);return X(e.clob.post("spreads",{json:Jv(n)}).andThen(W(q3)))}async function Wv(e,t){let n=M(t,zse);return X(e.clob.get("/last-trade-price",{params:oc(n)}).andThen(W(H3)))}async function Gv(e,t){let n=M(t,Gse);return X(e.clob.post("last-trades-prices",{json:Jv(n)}).andThen(W($3)))}function Yv(e,t={}){let{cursor:n,...r}=M(t,Kse);return Fe(o=>e.clob.get("/rewards/markets/current",{params:ve({...r,nextCursor:o},Ee())}).andThen(W(J3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),n)}function Xv(e,t){let{cursor:n,...r}=M(t,Yse);return Fe(o=>e.clob.get(`rewards/markets/${r.conditionId}`,{params:ve({nextCursor:o,sponsored:r.sponsored},Ee())}).andThen(W(Z3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),n)}function Jv(e){return e.map(t=>({token_id:t.assetId??t.tokenId}))}function Qse(e){return e.map(t=>({token_id:t.assetId??t.tokenId,side:t.side}))}function oc(e){let{assetId:t,tokenId:n,...r}=e;return ve({...r,tokenId:e.assetId??e.tokenId},Ee())}async function ek(e){return z8(e),X(e.combos.post("/v1/collateral-return/plan",{json:{wallet:e.account.wallet},timeout:j8}).andThen(W(R4)))}async function cO(e,t){let{plan:n}=M(t,Xse);if(fe(e.supportsGasless,"Collateral return execution requires a Relayer API Key or Builder API Key in the client configuration."),z8(e),!zt(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<=o6;o+=1)try{let s=yield*Jse(e,r);try{return await s6(e,n.planHash,s)}catch(i){let a=fv(i);if(a===void 0||s.type!==Ir.WALLET)throw i;let l=yield*gv(e,s,r,a);return await s6(e,n.planHash,l)}}catch(s){if(!bv(s)||o===o6)throw s;await os(e.environment.relayerPollFrequencyMs)}fe(!1,"Expected collateral return submit retry loop to return")}.call(null)}function nk(e,t){return cO(e,t).then(vn(e.signer))}function z8(e){fe(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 Jse(e,t){switch(e.account.walletType){case Se.GNOSIS_SAFE:return yv(e,t,mN);case Se.POLY_PROXY:return hv(e,t,mN);default:return qd(e,t,mN)}}async function s6(e,t,n){let r=await X(e.combos.post("/v1/collateral-return/submit",{json:{envelope:n,plan_hash:t},timeout:j8}).andThen(W(ZC)));return new Lf(e,r)}function rie(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=nie.safeParse(e.order);if(t.success)return{ascending:e.ascending??!0,order:t.data,parentEntityId:e.parentEntityId,parentEntityType:e.parentEntityType}}function ok(e,t){let{cursor:n,pageSize:r,...o}=M(t,Zse),s=rie(o);return Fe(i=>{if(i===void 0)return s===void 0?i6(e,o,{offset:0,pageSize:r}):a6(e,s,r);let a=_6(i);if(a===void 0)throw new E("Invalid pagination cursor");let l=L6(a,s);return l===void 0||s===void 0?i6(e,o,N6(a,G8)):a6(e,s,r,l)},n)}function i6(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(W(jh)).map(r=>{let o=r.filter(s=>s.parentCommentID==null).length>=n.pageSize;return{items:r,hasMore:o,limitReached:o&&n.offset+n.pageSize>dO,nextCursor:o?sa({offset:n.offset+n.pageSize,pageSize:n.pageSize}):void 0}})}function a6(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(W(TI)).map(o=>({items:o.items,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor===void 0?void 0:O6(o.nextCursor,t)}))}async function ik(e,t){let n=M(t,eie);return X(e.gamma.get(`comments/${n.id}`,{params:ve({getPositions:n.getPositions},Ee())}).andThen(W(jh)))}function lk(e,t){let{address:n,cursor:r,pageSize:o,...s}=M(t,tie);return Fe(i=>{let a=Md(i,o,G8);return e.gamma.get(`comments/user_address/${n}`,{params:ve({ascending:s.ascending,limit:a.pageSize,offset:a.offset,order:s.order},Ee())}).andThen(W(jh)).map(l=>{let c=l.length>=a.pageSize;return{items:l,hasMore:c,limitReached:c&&a.offset+a.pageSize>dO,nextCursor:c?sa({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},r)}function K8(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 uk(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,oie);return Fe(s=>e.gamma.get("/events/keyset",{params:pie({...o,pageSize:r,cursor:s===void 0?void 0:aie(s,o)})}).andThen(W(kI)).map(i=>({items:i.items,hasMore:i.nextCursor!==void 0,nextCursor:i.nextCursor===void 0?void 0:O6(i.nextCursor,o)})),n)}function aie(e,t){let n=_6(e);return n===void 0?e:L6(n,t)??e}async function pk(e,t){let n=M(t,sie);if("id"in n)return X(e.gamma.get(`events/${n.id}`,{params:mie(n)}).andThen(W(ei)));let r="url"in n?K8(n.url,"event"):n.slug;return X(e.gamma.get(`events/slug/${r}`,{params:hie(n)}).andThen(W(ei)))}async function hk(e,t){let n=M(t,iie);return X(e.gamma.get(`events/${n.id}/tags`).andThen(W(xI)))}async function gk(e,t){let{conditionIds:n,eventIds:r,questionId:o}=M(t,uie);return X(nn(()=>e.data.get("/v2/resolutions",{params:tn({questionId:o,condition:n,eventId:r})})).andThen(W(m4)))}async function bk(e,t){let{eventIds:n}=M(t,die);return X(nn(()=>e.data.get("/v2/live-volume",{params:tn({eventId:n})})).andThen(W(s4)))}function pie(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 mie(e){return ve({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},Ee())}function hie(e){return ve({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},Ee())}function vk(e,t={}){let{cursor:n,pageSize:r,window:o}=M(t,fie);return Fe(s=>nn(()=>e.data.get("/v2/builders/leaderboard",{params:tn({timePeriod:o,limit:r,cursor:s})})).andThen(W(l4)),n)}async function xk(e,t={}){let{interval:n,bucketLimit:r}=M(t,gie);return X(nn(()=>e.data.get("/v2/builders/volume",{params:tn({interval:n,limit:r})})).andThen(W(c4)))}function Tk(e,t={}){let{category:n,cursor:r,pageSize:o,sortBy:s,window:i}=M(t,yie);return Fe(a=>nn(()=>e.data.get("/v2/leaderboard",{params:tn({category:n,cursor:a,limit:o,sortBy:s,timePeriod:i})})).andThen(W(u4)),r)}async function Mf(e,t){let{category:n,user:r,window:o}=M(t,bie);return X(nn(()=>e.data.get("/v2/leaderboard",{params:tn({category:n,timePeriod:o,user:r})})).andThen(W(d4)))}function Ek(e,t={}){let{category:n,cursor:r,pageSize:o,window:s}=M(t,wie);return Fe(i=>nn(()=>e.data.get("/v2/biggest-winners",{params:tn({category:n,cursor:i,limit:o,timePeriod:s})})).andThen(W(p4)),r)}function Rk(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,vie);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(W(n$)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?sa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}function Ff(e,t={}){let n=M(t,kie);return Fe(r=>e.gamma.get("/markets/keyset",{params:Uie({...n,cursor:r??n.cursor})}).andThen(W(hI)).map(o=>({items:o.items,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor})),n.cursor)}function Ck(e,t={}){let n=M(t,Eie);return Fe(r=>e.rfq.get("/v1/rfq/combo-markets",{params:Bie({...n,cursor:r??n.cursor})}).andThen(W(x4)).map(o=>({items:o.markets,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor})),n.cursor)}async function Ok(e,t){let n=M(t,Sie);return"id"in n?Mie(e,n):"url"in n?l6(e,{includeTag:n.includeTag,locale:n.locale,slug:K8(n.url,"market")}):l6(e,n)}async function Dk(e,t){let n=M(t,Pie);return X(e.gamma.get(`markets/${n.id}/tags`).andThen(W(fI)))}function Bk(e,t){let{conditionIds:n,cursor:r,includePnl:o,minBalance:s,pageSize:i}=M(t,Rie);return Fe(a=>nn(()=>e.data.get("/v2/holders",{params:tn({condition:n,limit:i,cursor:a,includePnl:o,minBalance:s})})).andThen(W(r4)),r)}function Fk(e,t){let{assetId:n,cursor:r,pageSize:o,...s}=M(t,Lie);return Fe(i=>nn(()=>e.data.get("/v2/prices-history",{params:tn({...s,tokenId:n,limit:o,cursor:i})})).andThen(W(n4)),r)}async function Hk(e,t={}){let{conditionIds:n}=M(t,Die);return X(nn(()=>e.data.get("/v2/oi",{params:tn({condition:n})})).andThen(W(o4)))}function Uie(e){return ve(e,Ee({cursor:"after_cursor",ids:"id",pageSize:"limit"}))}function Bie(e){return ve({cursor:e.cursor,exclude:e.exclude?.join(","),pageSize:e.pageSize},{cursor:"cursor",exclude:"exclude",pageSize:"limit"})}async function l6(e,t){return X(e.gamma.get(`markets/slug/${t.slug}`,{params:ve({includeTag:t.includeTag,locale:t.locale},Ee())}).andThen(W(Nw)))}async function Mie(e,t){return X(e.gamma.get(`markets/${t.id}`,{params:ve({includeTag:t.includeTag,locale:t.locale},Ee())}).andThen(W(Nw)))}function mO(e){if(!(e instanceof O))return e;let t=Fie(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 Fie(e){if(e.status===425)return"restarting";if(e.status===503&&e.code==="post_only_mode")return"post_only"}async function Vk(e,t){let n=M(t,qie);return Qk(e,"/order",{orderID:n.orderId})}async function Wk(e,t){let n=M(t,Hie);return Qk(e,"/orders",n.orderIds)}async function Gk(e){return Qk(e,"/cancel-all")}async function Yk(e,t){let n=M(t,Vie);return Qk(e,"/cancel-market-orders",{asset_id:n.assetId??n.tokenId,market:n.market})}async function Qk(e,t,n){return X(e.secureClob.del(t,{json:n,rateLimitBucket:"cancel"}).mapErr(mO).andThen(W(L3)))}async function Jk(e,t){let n=M(t,jie),r=n.side===Ue.BUY?n.amount:n.shares;return hO(e,{amount:r,assetId:n.assetId,orderType:n.orderType,side:n.side})}async function hO(e,t){let n=await Hd(e,{assetId:t.assetId});return Zk({amount:t.amount,orderBook:n,orderType:t.orderType,side:t.side})}function Zk(e){let{orderBook:t}=e,n=e.side===Ue.BUY?zie(t.asks,e.amount,e.orderType):Gie(t.bids,e.amount,e.orderType);return fe(Wie(n,t.tickSize),`Resolved market price fell outside the valid range for tick size ${t.tickSize}.`),n}function Wie(e,t){return e>=t&&e<=1-t}function zie(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 Gie(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){M(t,Z8);let n=e5(e,t);return X(e.secureClob.post("/order",{json:n,rateLimitBucket:"order"}).mapErr(mO).andThen(W(DC)))}}function nx(e){return async function(t){M(t,Qie);let n=t.map(r=>e5(e,r));return X(e.secureClob.post("/orders",{json:n,rateLimitBucket:"order"}).mapErr(mO).andThen(W(X3)))}}function e5(e,t){return fe(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 Xie(e){try{let t=BigInt(e);return t>=0n&&t<=Kie}catch{return!1}}function r5(e){let t=Wt.encode([{name:"legs",type:"uint256[]"}],[e]),n=Je.keccak256(Wt.encode([{name:"moduleId",type:"uint256"},{name:"data",type:"bytes"}],[n5,t])),r=z_(`0x03${n.slice(34)}0000000000000000000000000000`);return{conditionId:r,positionIds:[BigInt(`${r}00`).toString(),BigInt(`${r}01`).toString()]}}function o5(e){if(e.length===0||e.length>d6)throw new E(`Combo legs must include 1 to ${d6} position IDs`);let t=e.map(n=>{let r=fO(n),o=r.toString(16).padStart(t5*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 rx(e){try{return(fO(e)&tae)===0n}catch{return!1}}function nae(e){let t=fO(e).toString(16).padStart(t5*2,"0"),n=BigInt(`0x${t.slice(0,2)}`),r=Number.parseInt(t.slice(-2),16);if(n!==Jie&&n!==Zie&&n!==n5)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:Oh(`0x${t.slice(0,-2)}`),outcomeIndex:r}}function fO(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>eae)throw new E("Position ID must be a uint256 value");return n}function s5(e){let t=e*Number(nc),n=Math.round(t),r=oae*Math.max(1,Math.abs(t)),o=Math.abs(t-n)<=r?n:Math.trunc(t);return BigInt(o)}function kN(e){let t=Math.round(e*Number(nc)),n=t/Number(nc);if(!Number.isSafeInteger(t)||Math.abs(e-n)>rae)throw new E("has unsupported precision.");return BigInt(t)}function i5(e){return Number(e)/Number(nc)}function gO(e){return fe(Number.isInteger(e)&&e>=0&&e<=hN,`Decimal places must be an integer between 0 and ${hN}.`),10n**BigInt(hN-e)}function yO(e,t,n,r){fe(e>=0n,"Value must be non-negative."),fe(t>=0n,"Multiplier must be non-negative."),fe(n>0n,"Denominator must be positive.");let o=e*t,s=o/n;return r==="up"&&o%n!==0n?s+1n:s}function a5(e,t,n){let r=gO(t);return yO(e,1n,r,n)*r}function l5(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}}fe(!1,`Unsupported tick size: ${e}`)}function c5(e,t){let n=kN(e),r=kN(t);if(n<r||n>nc-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 sae(e,t){return t?e.environment.contracts.negRiskExchange:e.environment.contracts.standardExchange}function qf(e,t,n){return rx(t)?e.environment.contracts.exchangeV3:sae(e,n)}function xN(e,t,n,r){let o=gO(n);return yO(e,t,nc*o,r)*o}function iae(e,t,n,r){let o=gO(n);return yO(e,nc,t*o,r)*o}function aae(e){let t=l5(e.tickSize),n=a5(s5(e.size),t.size,"down");return e.side===Ue.BUY?{offeredAmount:xN(n,e.price,t.amount,"down"),requestedAmount:n}:{offeredAmount:n,requestedAmount:xN(n,e.price,t.amount,"down")}}function lae(e){let t=l5(e.tickSize),n=a5(s5(e.amount),t.size,"down"),r=e.protectPrice?"up":"down";return e.side===Ue.BUY?{offeredAmount:n,requestedAmount:iae(n,e.price,t.amount,r)}:{offeredAmount:n,requestedAmount:xN(n,e.price,t.amount,r)}}function A0(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 p6(e,t=AN){return{expiresAt:Date.now()+t,promise:Promise.resolve(e)}}function ox(e,t){return bO(e).resolveMarket(t)}function TN(e,t){return bO(e).fetchCurrentMarket(t)}function uae(e,t){return bO(e).resolveBuilderTakerFeeRate(t)}function bO(e){let t=m6.get(e);if(t!==void 0)return t;let n=new cae({fetchBuilderTakerFeeRate:async r=>(await lO(e,{builderCode:r})).taker,fetchMarket:r=>aO(e,{conditionId:r}),resolveCondition:r=>iO(e,{assetId:r})});return m6.set(e,n),n}async function mae(e,t){let n=await hae(e,{assetId:t.assetId,price:t.price}),r=aae({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 hae(e,t){let n=await ox(e,t.assetId);try{return f6(e,t,n)}catch(r){if(!(r instanceof E))throw r;let o=await TN(e,t.assetId);return f6(e,t,o)}}function f6(e,t,n){let r=fae(t.price,n.tickSize);return{exchangeAddress:qf(e,t.assetId,n.negRisk),funderAddress:e.account.wallet,price:r,signerAddress:e.account.signer,tickSize:n.tickSize}}function fae(e,t){try{return c5(e,t)}catch(n){throw n instanceof E?new E(`Price ${n.message}`,{cause:n}):n}}async function yae(e,t){let n=await bae(e,t,t.assetId),r=lae({amount:n.resolvedAmount,price:n.price,protectPrice:p5(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 bae(e,t,n){return p5(t)?wae(e,t,n):vae(e,t,n)}async function wae(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 m5(e,n,t.builderCode);try{return b6(e,t,n,r,s,t.maxSpend,i)}catch(a){if(!(a instanceof E))throw a;let l=await TN(e,n);return b6(e,t,n,r,s,t.maxSpend,l)}}let o=await ox(e,n);try{return w6(e,t,n,r,o)}catch(s){if(!(s instanceof E))throw s;let i=await TN(e,n);return w6(e,t,n,r,i)}}function b6(e,t,n,r,o,s,i){let a=d5(t,i.tickSize),l=i5(a);return{exchangeAddress:qf(e,n,i.negRisk),funderAddress:e.account.wallet,price:a,resolvedAmount:h5({amount:r,builderTakerFeeRate:o,maxSpend:s,platformFeeExponent:i.feeInfo.exponent,platformFeeRate:i.feeInfo.rate,price:l}),signerAddress:e.account.signer,tickSize:i.tickSize}}function w6(e,t,n,r,o){let s=d5(t,o.tickSize);return{exchangeAddress:qf(e,n,o.negRisk),funderAddress:e.account.wallet,price:s,resolvedAmount:r,signerAddress:e.account.signer,tickSize:o.tickSize}}async function vae(e,t,n){let r=t.side===Ue.BUY?t.amount:t.shares,o=t.side===Ue.BUY&&t.maxSpend!==void 0?m5(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=kN(Zk({amount:r,orderBook:s,orderType:t.orderType,side:t.side}));return{exchangeAddress:qf(e,n,s.negRisk),funderAddress:e.account.wallet,price:a,resolvedAmount:kae(t,r,i5(a),i),signerAddress:e.account.signer,tickSize:s.tickSize}}function kae(e,t,n,r){return e.side!==Ue.BUY||e.maxSpend===void 0||r===void 0?t:h5({amount:t,builderTakerFeeRate:r.builderTakerFeeRate,maxSpend:e.maxSpend,platformFeeExponent:r.market.feeInfo.exponent,platformFeeRate:r.market.feeInfo.rate,price:n})}function d5(e,t){return e.side===Ue.BUY?(fe(e.maxPrice!==void 0,"Protected BUY market order requires maxPrice."),v6("maxPrice",e.maxPrice,t)):(fe(e.minPrice!==void 0,"Protected SELL market order requires minPrice."),v6("minPrice",e.minPrice,t))}function v6(e,t,n){try{return c5(t,n)}catch(r){throw r instanceof E?new E(`${e} ${r.message}`,{cause:r}):r}}function p5(e){return e.side===Ue.BUY&&e.maxPrice!==void 0||e.side===Ue.SELL&&e.minPrice!==void 0}async function m5(e,t,n){let[r,o]=await Promise.all([ox(e,t),uae(e,n)]);return{builderTakerFeeRate:o,market:r}}function h5(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 sx(e){let t=Rae(e.domain,e.order);return e.order.signatureType!==Rr.POLY_1271?t:{domain:k5(e.domain),message:{chainId:e.domain.chainId,contents:t.message,name:xae,salt:SN,verifyingContract:e.order.signer,version:Aae},primaryType:"TypedDataSign",types:{EIP712Domain:g5,Order:y5,TypedDataSign:Eae}}}function ix(e){if(e.order.signatureType!==Rr.POLY_1271)return e.signature;let t=we.toHex(we.fromString(PN)),n=PN.length.toString(16).padStart(4,"0");return lq(`0x${e.signature.slice(2)}${_ae(e.domain).slice(2)}${Iae(e.order).slice(2)}${t.slice(2)}${n}`)}function wO(e){return{chainId:e.chainId,exchange:e.exchange,protocolVersion:"3"}}function b5(e,t,n){return e===Ue.SELL?n.toString():((t*n+999999n)/1000000n).toString()}function w5(e,t,n){return e===Ue.SELL?(t*n/1000000n).toString():n.toString()}function v5(e){return{builder:e.builder??SN,maker:e.maker,makerAmount:BigInt(e.makerAmount),metadata:e.metadata??SN,salt:BigInt(e.salt),side:ax(e.side),signatureType:e.signatureType,signer:e.signer,takerAmount:BigInt(e.takerAmount),timestamp:BigInt(e.timestamp),tokenId:BigInt(e.tokenId)}}function Rae(e,t){return{domain:k5(e),message:v5(t),primaryType:"Order",types:{EIP712Domain:g5,Order:y5}}}function k5(e){return{chainId:e.chainId,name:f5,verifyingContract:e.exchange,version:e.protocolVersion}}function _ae(e){return Wn(Je.keccak256(Wt.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"address"}],[Sae,Pae,Cae(e.protocolVersion),BigInt(e.chainId),e.exchange]),{as:"Hex"}))}function Iae(e){let t=v5(e);return Wn(Je.keccak256(Wt.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"}],[Tae,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 Cae(e){return Wn(Je.keccak256(we.fromString(e),{as:"Hex"}))}function ax(e){return e===0||e===1?e:e===Ue.BUY?0:1}function x5(e,t){let n=rc(t);return{builder:e.builderCode??k6,chainId:e.chainId,exchangeAddress:e.exchangeAddress,expiration:e.expiration,maker:n.maker,makerAmount:e.offeredAmount.toString(),metadata:k6,orderType:e.orderType,protocolVersion:rx(e.assetId)?"3":"2",salt:Nae().toString(),side:e.side,signatureType:n.signatureType,signer:n.signer,takerAmount:e.requestedAmount.toString(),timestamp:Date.now().toString(),tokenId:e.assetId}}function A5(e,t){let{chainId:n,exchangeAddress:r,protocolVersion:o,...s}=e;return{...s,signature:t}}function Nae(){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 T5(e){return sx({domain:P5(e),order:e})}function S5(e,t){return ix({domain:P5(e),order:e,signature:t})}function P5(e){return{chainId:e.chainId,exchange:e.exchangeAddress,protocolVersion:e.protocolVersion}}function lx(e){return{kind:"signOrder",payload:e}}async function cx(e,t){let n=M(t,gae);return async function*(){let r=await yae(e,n),o=x5(r,e.account),s=ss(yield lx(T5(o)));return A5(o,O0(e.account,S5(o,s)))}.call(null)}async function ux(e,t){let n=M(t,pae);return async function*(){let r=await mae(e,n),o=x5(r,e.account),s=ss(yield lx(T5(o))),i=A5(o,O0(e.account,S5(o,s)));return n.postOnly===!0?{...i,postOnly:!0}:i}.call(null)}async function R5(e,t){return C5(e,cx(e,t))}async function I5(e,t){return C5(e,ux(e,t))}async function C5(e,t){let n=await t;return async function*(){let r=yield*n;return $d(e)(r)}.call(null)}function Bae(e){return e.status===Ki.Confirmed||e.status===Ki.Failed}function x6(e){return e.status===Ki.Failed}async function px(e,t,n){let{timeoutMs:r=Lae}=M(n,Uae),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=>Ef(e,{id:u}).firstPage()));for(let u of c)for(let d of u.items)o.includes(d.id)&&Bae(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 os(Oae)}let a=[...s.values()];if(a.every(x6))throw new en(`Every fill of order ${t.orderId} failed execution: ${o.join(", ")}`);return[...new Set(a.filter(l=>!x6(l)).map(l=>l.transactionHash))].map(l=>et.parse(l))}function N5(e,t){return e===Ue.BUY?ra.COLLATERAL:rx(t)?ra.CONDITIONAL_V2:ra.CONDITIONAL}async function Mae(e,t){let n=N5(t.side,t.assetId),{allowances:r}=await G0(e,t.side===Ue.BUY?{assetType:n}:{assetType:n,assetId:t.assetId});return Fae(r,t.spenderAddress)}function Fae(e,t){return Object.entries(e).find(([n])=>zt(n,t))?.[1]??0n}function Hf(e,t){return cx(e,t).then(vn(e.signer))}function fx(e,t){return Hf(e,t).then(n=>O5(e,n))}function $f(e,t){return ux(e,t).then(vn(e.signer))}function bx(e,t){return $f(e,t).then(n=>O5(e,n))}async function O5(e,t){let n=$d(e);try{return await n(t)}catch(r){if(!Hae(r))throw r;let o=await qae(e,t,n);if(o===void 0)throw r;return o}}async function qae(e,t,n){return await $ae(e,t)?n(t):void 0}function Hae(e){return e instanceof O&&e.status===400&&e.message.includes("allowance is not enough")}async function $ae(e,t){let n=t.tokenId,r=await ox(e,n),o=qf(e,n,r.negRisk),s=BigInt(t.makerAmount);return await Mae(e,{assetId:n,spenderAddress:o,side:t.side})>=s?!1:(await(t.side===Ue.BUY?await Df(e,{amount:"max",spenderAddress:o,tokenAddress:e.environment.contracts.collateralToken}):await Uf(e,{operatorAddress:o,tokenAddress:rx(n)?e.environment.contracts.positionManager:e.environment.contracts.conditionalTokens})).wait(),await UN(e,{assetType:N5(t.side,n),tokenId:t.side===Ue.SELL?n:void 0}),!0)}function Vae(e){let t=fo.getSignPayload(xO(e));return ss(ow.toHex(ad.sign({payload:t,privateKey:e.privateKey})))}function xO(e){let t={chainId:e.chainId,name:"Polymarket",version:"1"};return{domain:t,message:{data:Je.keccak256(lN(L5(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 L5(e){return Array.isArray(e)?e.filter(t=>t!==void 0).map(L5):e}function Vf(){let[e]=crypto.getRandomValues(new Uint32Array(1));return fe(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}function A6(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 vx(e,t){let n=M(t,Wae);return X(e.perps.get("/v1/info/builder",{params:ve(n,Ee())}).andThen(W(tf)))}async function Gae(e,t,n){let r=M(n,D5);if(r.builderAddress===void 0)throw new E("A builder address is required when the session has no builder attribution.");let o=Kae(await t.fetchBuilderApprovals({builder:r.builderAddress}),r.builderAddress),s={...M({builder:r.builderAddress,maxFeeRate:r.maxFeeRate,approvalVersion:o},zae),chainId:e.environment.chainId,salt:Vf(),timestamp:Date.now()},i;try{i=await e.signer.signTypedData(Yae(s))}catch(a){throw ce.fromError(a,"Could not sign builder consent")}return X(e.perps.post("/v1/account/builder-approvals",{json:Qae(s,i)}).andThen(W(zw)))}function Kae(e,t){return(e.find(n=>n.builder.toLowerCase()===t.toLowerCase())?.approvalVersion??0)+1}function Yae(e){return xO({chainId:e.chainId,op:["approveBuilder",[e.builder,e.maxFeeRate,e.approvalVersion]],salt:e.salt,timestamp:e.timestamp})}function Qae(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 Xae(e,t){let n=T6(e.get("Poly-RateLimit-Remaining"),/^-?\d+$/),r=T6(e.get("Poly-RateLimit-Reset"),/^\d+$/),o=Jae(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 T6(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 Jae(e){if(!(e===null||e.trim()===""))return e}function cle(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 I("WebSocket headers require a header-capable WebSocket implementation.",{cause:n})}throw new I("WebSocket headers require a header-capable WebSocket implementation.")}function ule(e,t){let n=Math.min(t.baseMs*2**e,t.maxMs);return Math.random()*n}function dle(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 hle(e){return await X(e.get("/v1/account/balances").andThen(W(CI)))}async function fle(e){return await X(e.get("/v1/account/portfolio").andThen(W(OI)))}async function gle(e){return await X(e.get("/v1/account/stats").andThen(W(NI)))}async function yle(e){return await X(e.get("/v1/account/auto-cancel").andThen(W(I4)))}async function wle(e,t){let n=M(t,ble);return await X(e.get("/v1/account/config",{params:Jr(n)}).andThen(W(UI)))}async function kle(e,t){let n=M(t,vle);return await X(e.get("/v1/account/open-orders",{params:Jr(n)}).andThen(W(xC)))}async function Tle(e,t){let n=M(t,Ale);return await X(e.get("/v1/account/orders",{params:Jr(n)}).andThen(W(kC)))}function Ple(e,t={}){let n=M(t,Sle);return Fe(r=>e.get("/v1/account/fills",{params:Jr({startTimestamp:n.start,endTimestamp:n.end,sort:n.sort,cursor:r??n.cursor})}).andThen(W(TC)).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 Ile(e,t={}){let{cursor:n,params:r}=M(t,_le);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps funding payment params."),s={kind:"perpsFundingPayments",seenKeys:[],...r}):s=_o(o,EO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/funding",{params:Jr(l)}).andThen(W(LI)).map(u=>{let d=u.data.filter(p=>!c.has(`${p.instrumentId}:${p.timestamp}:${p.funding}`));return RO({getKey:p=>`${p.instrumentId}:${p.timestamp}:${p.funding}`,getTimestamp:p=>p.timestamp,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Lle(e,t={}){let{cursor:n,params:r}=M(t,Ole);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps deposit params."),s={kind:"perpsDeposits",seenKeys:[],...r}):s=_o(o,EO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/deposits",{params:Jr(l)}).andThen(W(zI)).map(u=>{let d=u.data.filter(p=>!c.has(p.hash));return RO({getKey:p=>p.hash,getTimestamp:cce,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Mle(e,t={}){let{cursor:n,params:r}=M(t,Ble);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps withdrawal params."),s={kind:"perpsWithdrawals",seenKeys:[],...r}):s=_o(o,EO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/withdrawals",{params:Jr(l)}).andThen(W(KI)).map(u=>{let d=u.data.filter(p=>!c.has(String(p.withdrawalId)));return RO({getKey:p=>String(p.withdrawalId),getTimestamp:uce,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Vle(e,t={}){let{cursor:n,params:r}=M(t,$le);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps internal-transfer params."),s={kind:"perpsInternalTransfers",seenKeys:[],...r}):s=_o(o,qle,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s;return e.get("/v1/account/internal-transfers",{params:Jr(l)}).andThen(W(XI)).map(c=>dle(c.data,c.more,s))},n)}function Gle(e,t){let{cursor:n,params:r}=M(t,zle);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps equity history params."),s={kind:"perpsEquityHistory",...r}):s=_o(o,q5,"Invalid Perps account pagination cursor");let{kind:i,...a}=s;return e.get("/v1/account/equity",{params:Jr(a)}).andThen(W(BI)).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+$5(s.interval)}):void 0}})},n)}function Xle(e,t){let{cursor:n,params:r}=M(t,Qle);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps PnL history params."),s={kind:"perpsPnlHistory",...r}):s=_o(o,q5,"Invalid Perps account pagination cursor");let{kind:i,...a}=s;return e.get("/v1/account/pnl",{params:Jr(a)}).andThen(W(MI)).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+$5(s.interval)}):void 0}})},n)}function nce(e,t={}){let{cursor:n,params:r}=M(t,tce);return Fe(o=>{let s;o===void 0?fe(r!==void 0,"Expected initial Perps notifications params."):s=_o(o,Jle,"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:Jr({cursor:s?.cursor,limit:a,sinceSeq:i})}).andThen(W(mC)).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 rce(e){return(await X(e.get("/v1/account/notifications",{params:Jr({limit:1})}).andThen(W(hC)))).unread}async function ace(e,t){let n=M(t,ice),r=await X(e.post("/v1/account/notifications/read",{json:n}).andThen(W(fC)));if(r.status==="err")throw new O(r.error??"Perps notifications read request was rejected.",{status:200})}function lce(e){return btoa(JSON.stringify({ts:e.timestamp,id:e.id})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ax(e,t){let n=Date.now(),{end:r,start:o,...s}=e;return{...s,endTimestamp:r??n,startTimestamp:o??n-t}}function H5(e){return{endTimestamp:e.end??Date.now(),interval:e.interval,startTimestamp:e.start}}function Jr(e){return ve(e,Ee())}function cce(e){return e.confirmedTimestamp??e.createdTimestamp}function uce(e){return e.confirmedTimestamp??e.createdTimestamp}function RO(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 $5(e){switch(e){case"1h":return 3600*1e3;case"4h":return 14400*1e3;case"1d":return E0;case"1w":return 7*E0}fe(!1,`Unsupported Perps account history interval: ${String(e)}`)}async function pce(e,t){let n=M(t,dce);return(await X(e.get("/v1/account/builder-approvals",{params:ve(n,Ee())}).andThen(W($I)))).data}function hce(e,t){let n=M(t,V5);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(W(jI)).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 fce(e,t){let n=M(t,V5);return X(e.get("/v1/account/builder-earnings-summary",{params:ve(n,{start:"start_timestamp",end:"end_timestamp",asOfSequence:"as_of_sequence"})}).andThen(W(WI)))}async function kce(e,t){let n=M(t,vce),r=e.builderAttribution;return await e.executeCommand({op:["createOrders",n.orders.map(o=>CO(o,r))],expiresAt:n.expiresAt},h.z.array(cf))}function Tce(e){return e.takeProfit!==void 0||e.stopLoss!==void 0}async function Sce(e,t){if(Tce(t))return await Pce(e,t);let n=M(t,Ace),r=e.builderAttribution,[,o]=await e.executeCommandWithEvent({op:["createOrders",[CO(n,r)]],expiresAt:n.expiresAt},j5,z5(n.clientOrderId));return{order:o.payload}}async function Pce(e,t){let n=M(t,xce),r=e.builderAttribution,o=[CO(n,r)],s=n.side===Ue.SELL;n.takeProfit!==void 0&&o.push(I0({buy:s,instrumentId:n.instrumentId,kind:ta.TakeProfit,quantity:n.quantity,builderAttribution:r,trigger:n.takeProfit})),n.stopLoss!==void 0&&o.push(I0({buy:s,instrumentId:n.instrumentId,kind:ta.StopLoss,quantity:n.quantity,builderAttribution:r,trigger:n.stopLoss}));let[i,a]=await e.executeCommandWithEvent({op:["createOrders",o,vd.Order],expiresAt:n.expiresAt},j5,z5(n.clientOrderId)),l=1,c={};return n.takeProfit!==void 0&&(c.takeProfit=_0(Qs(i[l++],"Expected Perps take-profit acknowledgement."))),n.stopLoss!==void 0&&(c.stopLoss=_0(Qs(i[l],"Expected Perps stop-loss acknowledgement."))),{order:a.payload,tpSl:c}}async function _ce(e,t){let n=M(t,Rce),r=e.builderAttribution,o=Jce(await e.fetchPortfolio(),n.instrumentId),s=[];n.takeProfit!==void 0&&s.push(I0({buy:o,instrumentId:n.instrumentId,kind:ta.TakeProfit,quantity:"0",builderAttribution:r,trigger:n.takeProfit})),n.stopLoss!==void 0&&s.push(I0({buy:o,instrumentId:n.instrumentId,kind:ta.StopLoss,quantity:"0",builderAttribution:r,trigger:n.stopLoss}));let i=await e.executeCommand({op:["createOrders",s,vd.Position],expiresAt:n.expiresAt},h.z.array(cf));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=_0(Qs(i[a++],"Expected Perps take-profit acknowledgement."))),n.stopLoss!==void 0&&(l.stopLoss=_0(Qs(i[a],"Expected Perps stop-loss acknowledgement."))),{tpSl:l}}async function Lce(e,t){let n=M(t,Oce),[r]=n.orderId!==void 0?await _N(e,{orderIds:[n.orderId],expiresAt:n.expiresAt,retry:n.retry,signal:n.signal}):await _N(e,{clientOrderIds:[n.clientOrderId],expiresAt:n.expiresAt,retry:n.retry,signal:n.signal});return Qs(r,"Expected Perps cancel order result.")}async function _N(e,t){let n=M(t,Dce);return n.orderIds!==void 0?await S6(n.orderIds,n,async r=>await e.executeCommand({op:["cancelOrders",r],expiresAt:n.expiresAt},h.z.array(Yw))):await S6(n.clientOrderIds,n,async r=>await e.executeCommand({op:["cancelOrdersCOID",r],expiresAt:n.expiresAt},h.z.array(Yw)))}async function S6(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(Fce(t.signal);i.length>0;){if(a>0){let u=o-Date.now(),d=Bce(a);if(u<=0||d>=u||!await Mce(d,t.signal)||t.signal?.aborted||Date.now()>=o)break}let l;try{l=await n(i.map(({identifier:d})=>d));let u=Uce(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 Zw("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 Uce(e){let[t]=e;if(!(e.length!==1||t?.status!=="err"||t.orderId!==void 0||t.clientOrderId!==void 0))return t.error}function Bce(e){let t=Math.min(Ice*2**(e-1),Cce);return Math.random()*t}function Mce(e,t){if(t?.aborted)return Promise.resolve(!1);if(e<=0)return Promise.resolve(!0);if(t===void 0)return new Promise(r=>yn(()=>r(!0),e));let n=t;return new Promise(r=>{let o=yn(()=>{n.removeEventListener("abort",s),r(!0)},e);function s(){clearTimeout(o),r(!1)}n.addEventListener("abort",s,{once:!0})})}function Fce(e){if(e?.aborted)throw Jw.fromReason(e.reason)}async function Hce(e,t){let n=M(t,qce),r=["cancelAll",n.instrumentId===void 0?[]:[n.instrumentId]];await e.executeDeleteCommand({path:"/v1/trade/orders/all",op:r,responseSchema:bC,expiresAt:n.expiresAt})}async function Wce(e,t,n){let r=M(n,Vce),o=["autoCancel",[r.cancelAt]],s=t(o,r.expiresAt);await X(e.patch("/v1/trade/auto-cancel",{json:{...s,op:C0(o)}}).andThen(W(sN)).mapErr(i=>i instanceof O&&i.message.startsWith(`${jce} (`)?new df("Auto-cancel daily trigger limit reached.",{cause:i}):i))}async function Gce(e,t,n){let r=M(n,zce),o=["autoCancel",[0]],s=t(o,r.expiresAt);await X(e.patch("/v1/trade/auto-cancel",{json:{...s,op:C0(o)}}).andThen(W(sN)))}async function Yce(e,t){let n=M(t,Kce);return await e.executeCommand({op:["updateLeverage",[n.instrumentId,n.leverage,n.crossMargin]]},wC)}async function Xce(e,t){let n=M(t,Qce),r=n.amount,o=await e.executeCommand({op:["updateMargin",[n.instrumentId,r]]},lf);if(o.status==="err")throw new O(o.error,{status:200})}function W5(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16));return Er.parse(Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""))}function z5(e){return t=>t.type==="order"&&t.payload.clientOrderId===e}function _0(e){if(e.status==="err")throw new O(e.error,{status:200});return{orderId:e.orderId}}function Jce(e,t){let n=e.positions.find(o=>o.instrumentId===t),r=n===void 0?0:Zce(n.size);if(r===0)throw new E(`No open Perps position for instrument ${t}.`);return r<0}function Zce(e){let t=e.trim(),n=t.replace(/^[+-]/,"").replace(".","");return/^0*$/.test(n)?0:t.startsWith("-")?-1:1}function CO(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 C0(e){let[t,n,r]=e;switch(t){case"createOrders":return nue({args:n.map(eue),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:fe(!1,`Unsupported Perps command: ${String(t)}`)}}function eue(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=tue(e[8])),e[10]!==void 0&&(t.builder={address:e[10][0],fee_rate:e[10][1]}),t}function tue(e){let t={tpsl:e[2],trp:e[1]};return e[0]!==void 0&&(t.market=e[0]),t}function nue(e,t){return t!==void 0&&(e.grp=t),e}function lue(e){let t,n;return{promise:new Promise((r,o)=>{t=r,n=o}),reject:n,resolve:t,schema:e}}function cue(e){return Array.isArray(e)?!1:NO(e)!==void 0}function NO(e){if(Array.isArray(e)){for(let n of e){let r=NO(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 uue(){let[e]=globalThis.crypto.getRandomValues(new Uint32Array(1));return fe(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}async function due(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 Nx(e,t){let n=M(t,pue);return X(e.perps.get("/v1/info/instruments",{params:ve(n,Ee())}).andThen(W(ZI)))}async function Lx(e,t){let n=M(t,mue),[r]=await jf(e,n);if(r===void 0)throw new C(`Perps ticker ${n.instrumentId} was not returned by the API`);return r}async function jf(e,t){let n=M(t,hue),r=ve(n,Ee()),[o,s]=await Promise.all([X(e.perps.get("/v1/info/tickers",{params:r}).andThen(W(eC))),X(e.perps.get("/v1/info/statistics",{params:r}).andThen(W(nC)))]),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 Bx(e,t){let n=M(t,gue);return X(e.perps.get("/v1/info/book",{params:ve(n,Ee())}).andThen(W(oC)))}function Fx(e,t){let{cursor:n,params:r}=M(t,wue);return Fe(o=>{let s=o===void 0?Iue(r):Oue(o);return e.perps.get("/v1/info/klines",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,interval:s.interval,startTimestamp:s.startTimestamp},Ee())}).andThen(W(dC)).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+Uue(s.interval)}):void 0}})},n)}function Hx(e,t){let{cursor:n,params:r}=M(t,xue);return Fe(o=>{let s=o===void 0?Cue(r):Lue(o);return e.perps.get("/v1/info/funding",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},Ee())}).andThen(W(cC)).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 Vx(e,t){let{cursor:n,params:r}=M(t,Sue);return Fe(o=>{let s=o===void 0?Nue(r):Due(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(W(lC)).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?[]:Bue(s,l,u)}):void 0}})},n)}async function Wx(e){return(await X(e.perps.get("/v1/info/fees").andThen(W(uC)))).feeSchedule}function _ue(e){let t=Date.now();return{endTimestamp:e.end??t,instrumentId:e.instrumentId,interval:e.interval,startTimestamp:e.start??t-K5}}function Q5(e){let t=Date.now();return{endTimestamp:e.end??t,instrumentId:e.instrumentId,startTimestamp:e.start??t-K5}}function Iue(e){return fe(e!==void 0,"Expected initial Perps candles params."),{kind:"perpsCandles",...e}}function Cue(e){return fe(e!==void 0,"Expected initial Perps funding params."),{kind:"perpsFundingHistory",...e}}function Nue(e){return fe(e!==void 0,"Expected initial Perps trades params."),{kind:"perpsTrades",seenTradeIds:[],...e}}function Oue(e){return _o(e,Pue,"Invalid Perps pagination cursor")}function Lue(e){return _o(e,Eue,"Invalid Perps pagination cursor")}function Due(e){return _o(e,Rue,"Invalid Perps pagination cursor")}function Uue(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}fe(!1,`Unsupported Perps kline interval: ${String(e)}`)}function Bue(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 Xx(e,t={}){let n=M(t,Vue),r="credentials"in n?await Jue(e,n.credentials):await Xue(e,n);return e.webSockets.perpsSession.connect(r,n.builderAttribution,Gae.bind(null,e),n.includeBuilderFills)}async function Jx(e,t){let n=M(t,Wue),r={type:"deleteProxy",args:{proxy:n.proxy}},o=["deleteProxy",[n.proxy]],s=Vf(),i=Date.now(),a=await eV(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(W(HI)));if(l.status==="err")throw new O(l.error??"Perps credentials revocation was rejected.",{status:200})}async function OO(e,t){let n=M(t,zue),{contracts:r}=e.environment,o=zN(r.perpsDepositContract,r.collateralToken,n.amount,e.account.signer);return async function*(){return e.account.walletType===Se.EOA?wn(yield ade(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 Zx(e,t){return OO(e,t).then(vn(e.signer))}async function eA(e,t){let n=M(t,Gue),r=Math.floor(Date.now()/1e3),o=Vf(),s={type:"withdraw",args:{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:n.amount.toString(),to:e.account.wallet}},i=await ede(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(W(YI)));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 tA(e,t){sde(e);let n=M(t,Que);if(zt(n.recipient,e.account.signer))throw new E("Perps collateral cannot be transferred to the authenticated account.");return due({signTransfer({account:r,token:o,amount:s,recipient:i,salt:a,timestamp:l}){return eV(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(W(JI)))).transferId}},{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:n.amount,recipient:n.recipient,label:n.label,salt:Vf(),timestamp:Date.now()})}async function Xue(e,t){let n=rde(),r=tV(n),o=e.account.signer,s=Date.now()+t.expiresIn,i=Date.now(),a=Vf(),l={args:{expiry:s,owner:o,proxy:r},type:"createProxy"},c=await Zue(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(W(qI))),p={expiresAt:s,privateKey:n,proxy:r,secret:d.secret};return Z5(e,p)}async function Jue(e,t){return ode(t),Z5(e,t)}async function Z5(e,t){let n=await X(e.perps.get("/v1/account/credentials",{headers:ide(t)}).andThen(W(FI)));if(!zt(n.address,e.account.signer))throw new C("Perps credentials belong to a different signer account.");let r=n.keys.find(o=>zt(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 Zue(e,t){try{return await e.signer.signTypedData(nde({chainId:e.environment.chainId,...t}))}catch(n){throw ce.fromError(n,"Could not sign the Perps proxy credentials request")}}async function eV(e,t){try{return await e.signer.signTypedData(xO({chainId:e.environment.chainId,op:t.signedOp,salt:t.salt,timestamp:t.timestamp}))}catch(n){throw ce.fromError(n,"Could not sign the Perps operation request")}}async function ede(e,t){try{return await e.signer.signTypedData(tde({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 ce.fromError(n,"Could not sign the Perps withdrawal request")}}function tde(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 nde(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 rde(){return aq(ad.randomPrivateKey(),"Generated invalid Perps proxy key.")}function tV(e){return Be(Jo.fromPublicKey(ad.getPublicKey({privateKey:e})))}function ode(e){let t=tV(e.privateKey);if(!zt(t,e.proxy))throw new E("Perps credentials private key does not match the proxy address.")}function sde(e){if(e.account.signerType!=="OWNER")throw new E("Perps collateral transfers must be signed by the account owner.")}function ide(e){return{"POLYMARKET-PROXY":e.proxy,"POLYMARKET-SECRET":e.secret}}function ade(e){return{kind:"sendPerpsDepositTransaction",request:e}}function Wf(e,t){let{cursor:n,pageSize:r,window:o,...s}=M(t,lde);return Fe(i=>nn(()=>e.data.get("/v2/positions",{params:tn({...s,...o,limit:r,cursor:i})})).andThen(W(W$)),n)}function zf(e,t){let{cursor:n,pageSize:r,...o}=M(t,dde);return Fe(s=>nn(()=>e.data.get("/v2/positions/combos",{params:tn({...o,limit:r,cursor:s})})).andThen(W(Q$)),n)}async function Gf(e,t){let{conditionIds:n,...r}=M(t,pde);return X(nn(()=>e.data.get("/v2/value",{params:tn({...r,condition:n})})).andThen(W(z$)))}async function Kf(e,t){let n=M(t,mde);return X(nn(()=>e.data.get("/v2/user-stats",{params:tn(n)})).andThen(W(G$)))}async function Yf(e,t){let n=M(t,hde);return X(nn(()=>e.data.get("/v2/user-pnl",{params:tn(n)})).andThen(W(K$)))}async function Qf(e,t){let{window:n,...r}=M(t,fde);return X(nn(()=>e.data.get("/v2/user-volume",{params:tn({...r,...n})})).andThen(W(Y$)))}async function Xf(e,t){let n=M(t,gde);return X(e.data.get("/v1/accounting/snapshot",{params:goe(n)}).andThen(jre))}function yde(e,t){if(!Kr(e.conditionId))throw new C(`Missing condition ID for ${t}`);if(!Kr(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===Zi.V2){if(Kr(o)!==Kr(s))throw new C(`Incomplete market position IDs for ${t}`);if(!Kr(o)||!Kr(s))throw new C(`Missing market position IDs for ${t}`);return{marketId:e.id,conditionId:e.conditionId,protocol:"v2",outcomeIds:[o,s]}}if(Kr(n)!==Kr(r))throw new C(`Incomplete market token IDs for ${t}`);if(Kr(n)&&Kr(r)){if(!Kr(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 uA(e,t){let n=M(t,nV),r=await MO(e,{conditionId:n.conditionId}),o=r.protocol==="ctf"?GN(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId,n.amount):uv(e.environment.contracts.protocolV2Router,r.conditionId,n.amount);return async function*(){return e.account.walletType===Se.EOA?wn(yield IN(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 dA(e,t){let n=M(t,oV),r=o5(n.legs),o=pv(e.environment.contracts.combinatorialModule,r),s=r5(r),i=uv(e.environment.contracts.protocolV2Router,s.conditionId,n.amount);return async function*(){return e.account.walletType===Se.EOA?(await wn(yield IN(Qn(e.environment.chainId,o))).wait(),wn(yield IN(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 LO(e,t){let n=M(t,bde);return n.legs!==void 0?dA(e,n):uA(e,n)}function aV(e,t){return uA(e,t).then(vn(e.signer))}function cV(e,t){return dA(e,t).then(vn(e.signer))}function pA(e,t){return LO(e,t).then(vn(e.signer))}async function hA(e,t){let n=M(t,uV),r=await MO(e,{conditionId:n.conditionId}),o=Cf(await e.rpc.ethCall(If(r.positionErc1155Address,e.account.wallet,r.outcomeIds))),s=TV(r.conditionId,o,n.amount),i=r.protocol==="ctf"?KN(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId,s):dv(e.environment.contracts.protocolV2Router,r.conditionId,s);return async function*(){return e.account.walletType===Se.EOA?wn(yield CN(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 fA(e,t){let n=M(t,pV),r=o5(n.legs),o=pv(e.environment.contracts.combinatorialModule,r),s=r5(r),i=Cf(await e.rpc.ethCall(If(e.environment.contracts.positionManager,e.account.wallet,s.positionIds))),a=TV(s.conditionId,i,n.amount),l=dv(e.environment.contracts.protocolV2Router,s.conditionId,a);return async function*(){return e.account.walletType===Se.EOA?(await wn(yield CN(Qn(e.environment.chainId,o))).wait(),wn(yield CN(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 DO(e,t){let n=M(t,wde);return n.legs!==void 0?fA(e,n):hA(e,n)}function fV(e,t){return hA(e,t).then(vn(e.signer))}function yV(e,t){return fA(e,t).then(vn(e.signer))}function gA(e,t){return DO(e,t).then(vn(e.signer))}async function UO(e,t){let n=M(t,vde),r=await MO(e,n.conditionId!==void 0?{conditionId:n.conditionId,closed:!0}:{marketId:n.marketId,closed:!0}),o=await Tde(e,r);return async function*(){return e.account.walletType===Se.EOA?yield*xde(e,o):yield*await Or(e,{calls:o,metadata:n.metadata??`Redeem positions for market ${r.marketId} (condition ${r.conditionId})`})}.call(null)}async function bA(e,t){let n=M(t,kV),r=nae(n.positionId),o=VN(await e.rpc.ethCall($N(e.environment.contracts.positionManager,e.account.wallet,n.positionId)));if(o===0n)throw new E("Position has no balance to redeem");let s=xf(e.environment.contracts.protocolV2Router,r.conditionId,r.outcomeIndex,o);return async function*(){return e.account.walletType===Se.EOA?wn(yield NN(Qn(e.environment.chainId,s))):yield*await Or(e,{calls:[s],metadata:n.metadata??`Redeem position ${n.positionId}`})}.call(null)}function AV(e,t){return bA(e,t)}async function BO(e,t){let n=M(t,kde);return n.positionId!==void 0?bA(e,n):UO(e,n)}function vA(e,t){return BO(e,t).then(vn(e.signer))}function IN(e){return{kind:"sendSplitPositionTransaction",request:e}}function CN(e){return{kind:"sendMergePositionsTransaction",request:e}}function NN(e){return{kind:"sendRedeemPositionsTransaction",request:e}}async function*xde(e,t){let[n,...r]=t;fe(n!==void 0,"Expected at least one redemption call");let o=n;for(let s of r)await wn(yield NN(Qn(e.environment.chainId,o))).wait(),o=s;return wn(yield NN(Qn(e.environment.chainId,o)))}async function MO(e,t){let n=t.conditionId!==void 0?`condition ${t.conditionId}`:`market ${t.marketId}`,r=await Ff(e,t.conditionId!==void 0?{conditionIds:[t.conditionId],closed:t.closed,pageSize:1}:{ids:[Ade(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=yde(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 Ade(e){let t=Number(e);if(!Number.isInteger(t))throw new E(`Market ID must be an integer, received ${e}`);return t}async function Tde(e,t){if(t.protocol==="ctf")return[YN(t.adapterAddress,e.environment.contracts.collateralToken,t.conditionId)];let n=Cf(await e.rpc.ethCall(If(t.positionErc1155Address,e.account.wallet,t.outcomeIds)));if(n.length!==2)throw new C("Expected two position balances");let[r,o]=n;fe(r!==void 0,"Expected YES position balance"),fe(o!==void 0,"Expected NO position balance");let s=[];if(r>0n&&s.push(xf(e.environment.contracts.protocolV2Router,t.conditionId,0,r)),o>0n&&s.push(xf(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 TV(e,t,n){let r=Sde(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 Sde(e){if(e.length!==2)throw new C("Expected two position balances");let[t,n]=e;return fe(t!==void 0,"Expected YES position balance"),fe(n!==void 0,"Expected NO position balance"),t<n?t:n}async function xA(e,t){let n=M(t,Pde);return X(e.gamma.get("/public-profile",{params:ve(n,Ee())}).andThen(W(r$)).orElse(r=>r instanceof O&&r.status===404?go(null):Sr(r)))}async function EA(e){return Jf(e),e.webSockets.rfqQuoter.connect()}function qO(e){return e instanceof O?new fs(e.message,{cause:e,code:SV(e.code),status:e.status}):e}function SV(e){return e!==void 0&&Lde.has(e)?e:li.RequestFailed}function PV(e){if(!e.hasBuilderApiKey)throw new E("Combo RFQ requests require a Builder API Key in the client configuration, via builderApiKey(...) or remoteBuilderSigning(...).")}function Dde(e,t){return BigInt(e)*1000000n+BigInt(t.padEnd(6,"0"))}async function _A(e,t){Jf(e);let n=M(t,Ude);PV(e);let r=rc(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:Xr.Notional,value_e6:n.amount}:{unit:Xr.Shares,value_e6:n.size},side:Eo.Yes,signature_type:r.signatureType,signer_address:r.signer},s=await X(e.builderGateway.post(FO,{json:o,timeout:Ede}).andThen(W(S4)).mapErr(qO));if("quote"in s){Bde(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 Mde(s)}function Bde(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 Mde(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 fs(e.error?.message??"The combo quote request failed.",{code:SV(e.error?.code),status:200,...e.error===void 0?{}:{cause:e.error}})}}async function CA(e,t){Jf(e);let n=M(t,qde);PV(e);let r=wO({chainId:e.environment.chainId,exchange:e.environment.contracts.exchangeV3}),o=Vde(e,n),s=await Wde(e,r,o),i={quote_id:n.quoteId,signed_order:s};function a(){return e.builderGateway.post(`${FO}/${encodeURIComponent(n.rfqId)}/accept`,{json:i,timeout:Rde}).andThen(W(rN))}let l=await a();if(l.isErr()&&(l.error instanceof I||l.error instanceof C)&&(l=await a()),l.isErr()){let p=Hde(n.rfqId,l.error);if(p!==void 0)return p;throw qO(l.error)}let c=l.value,u=l.value.takerOrderHash,d=Date.now()+_de;for(;c.status===mn.AwaitingMakerConfirmation;){if(Date.now()>=d)throw new tt(`Timed out waiting for the acceptance outcome of RFQ ${n.rfqId}.`);await os(Ide),c=await DA(e,{rfqId:n.rfqId})}return c.status===mn.Failed||c.status===mn.Expired||c.status===mn.Canceled?{reason:$de(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 Hde(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 $de(e,t){return e===mn.Expired||t===Cr.ExpiredRfq?Ro.AcceptanceWindowExpired:t===Cr.MakerDeclined?Ro.MakerDeclined:Ro.ExecutionFailed}function Vde(e,t){let n=rc(e.account);return{builder:t.builderCode,maker:n.maker,makerAmount:t.makerAmount,metadata:Ode,salt:jde().toString(),side:ax(t.direction),signatureType:n.signatureType,signer:n.signer,takerAmount:t.takerAmount,timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.positionId}}function jde(){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 Wde(e,t,n){let r;try{r=await e.signer.signTypedData(sx({domain:t,order:n}))}catch(o){throw o instanceof vt?o:ce.fromError(o,"Could not sign the combo quote acceptance order.")}return{...n,signature:ix({domain:t,order:n,signature:r})}}async function OA(e,t){Jf(e);let n=M(t,zde),r=n.timeoutMs??Cde,o=n.pollingIntervalMs??Nde,s=Date.now()+r;for(;;){let i=await DA(e,{rfqId:n.rfqId});if(i.status===mn.Filled||i.status===ps.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 os(o)}}function DA(e,t){Jf(e);let n=M(t,Gde);return X(e.builderGateway.get(`${FO}/${encodeURIComponent(n.rfqId)}`).andThen(W(rN)).mapErr(qO))}function Jf(e){if(e.account.signerType==="SESSION_KEY")throw new E("Combos is not supported with Session Keys")}function BA(e,t){let{cursor:n,pageSize:r,...o}=M(t,Kde);return Fe(s=>{let i=Md(s,r,{maxOffset:E6});return e.gamma.get("/public-search",{params:ve({...o,limitPerType:i.pageSize,page:i.offset},Ee({excludeTagIds:"exclude_tag_id"}))}).andThen(W(o$)).map(a=>({items:Yde(a),hasMore:a.pagination?.hasMore??!1,limitReached:(a.pagination?.hasMore??!1)&&i.offset+1>E6,totalCount:a.pagination?.totalResults??void 0,nextCursor:a.pagination?.hasMore?sa({offset:i.offset+1,pageSize:i.pageSize}):void 0}))},n??sa({offset:1,pageSize:r}),{events:[],profiles:[],tags:[]})}function Yde(e){return{events:e.events??[],profiles:e.profiles??[],tags:e.tags??[]}}function FA(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,Qde);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/series",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(W(i$)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?sa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function HA(e,t){let n=M(t,Xde);return X(e.gamma.get(`series/${n.id}`,{params:ve({locale:n.locale},Ee())}).andThen(W(FC)))}function EV(e){if(e.kind==="authorization"?e.status===Od.FAILED||e.status===Od.SUPERSEDED||e.status===Od.REPAIR_REQUIRED:e.status===g0.FAILED)throw new en(`Session-key ${e.kind} reached terminal status ${e.status}`)}async function zd(e){HO(e);let t=await X(e.secureClob.get("/v1/user/session-signers").andThen(W(e$)));if(!zt(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 jA(e,t){if(HO(e),!e.hasBuilderApiKey)throw new E("Session-key authorization requires builder API-key authentication.");let n=M(t,epe),r=Math.floor(Date.now()/1e3)+Zde,o=await vn(e.signer)(qd(e,[jN(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:RV}).andThen(W(h4)));EV({kind:"authorization",status:i.status});let a=await new Lf(e,i).wait();return{sessionKey:await rpe(e,{address:n.address,scopes:n.scopes,validUntil:r}),transaction:a}}async function zA(e,t){if(HO(e),!e.supportsGasless)throw new E("Session-key revocation requires API-key authentication that supports gasless transactions.");let n=M(t,tpe),r=await vn(e.signer)(qd(e,[WN(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:RV}).andThen(W(f4)));EV({kind:"revocation",status:s.status}),await npe(e,n.address)}async function npe(e,t){for(let n=0;n<e.environment.relayerMaxPolls;n+=1){if(!(await zd(e)).some(r=>zt(r.address,t)))return;await os(e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for session key ${t} to be revoked`)}async function rpe(e,t){for(let n=0;n<e.environment.relayerMaxPolls;n+=1){let r=(await zd(e)).find(o=>zt(o.address,t.address)&&o.validUntil===t.validUntil&&ope(o.scopes,t.scopes));if(r!==void 0)return r;await os(e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for session key ${t.address} to become active`)}function ope(e,t){let n=new Set(t);return new Set(e).size===n.size&&e.every(r=>n.has(r))}function HO(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 KA(e){return X(e.gamma.get("/sports").andThen(W(wI)))}async function QA(e){return X(e.gamma.get("/sports/market-types").andThen(W(vI)))}function ape(e){return M(e,ipe)}async function Zf(e,t){let n=t.map(i=>{switch(M(i,lpe),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 ape(i);case"prices.crypto.chainlink.twap":M(i,cpe);break;case"market":M(i,upe);break}return i}),r=await Promise.allSettled(n.map(async i=>dpe(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 ppe(o)}function dpe(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 fe(e.isSecureClient(),"A 'user' subscription requires a secure client instance."),e.webSockets.clobUser.subscribe(t)}}function ppe(e){let t;async function n(){t===void 0&&(t=Promise.all(e.map(o=>o.close())).then(()=>{})),await t}let r=J4(...e);return{close:n,[Symbol.asyncIterator](){return r[Symbol.asyncIterator]()}}}function ZA(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,mpe);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/tags",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(W(s$)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?sa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function tT(e,t){let n=M(t,hpe);return"id"in n?X(e.gamma.get(`tags/${n.id}`,{params:ve({includeTemplate:n.includeTemplate,locale:n.locale},Ee())}).andThen(W(_d))):X(e.gamma.get(`tags/slug/${n.slug}`,{params:ve({locale:n.locale},Ee())}).andThen(W(_d)))}async function rT(e,t){if("id"in t){let r=M(t,fpe);return X(e.gamma.get(`tags/${r.id}/related-tags`,{params:ve({omitEmpty:r.omitEmpty,status:r.status},Ee())}).andThen(W(BC)))}let n=M(t,gpe);return X(e.gamma.get(`tags/slug/${n.slug}/related-tags`).andThen(W(BC)))}async function sT(e,t){if("id"in t){let r=M(t,ype);return X(e.gamma.get(`tags/${r.id}/related-tags/tags`,{params:ve({locale:r.locale,omitEmpty:r.omitEmpty,status:r.status},Ee())}).andThen(W(MC)))}let n=M(t,bpe);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(W(MC)))}function aT(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,wpe);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(W(bI)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?sa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function $O(e,t){let n=M(t,vpe);return async function*(){return e.account.walletType===Se.EOA?wn(yield kpe(Qn(e.environment.chainId,P0(n.tokenAddress,n.recipientAddress,n.amount)))):yield*await Or(e,{calls:[P0(n.tokenAddress,n.recipientAddress,n.amount)],metadata:n.metadata??`Transfer ${n.amount} of ${n.tokenAddress} to ${n.recipientAddress}`})}.call(null)}function cT(e,t){return $O(e,t).then(vn(e.signer))}function kpe(e){return{kind:"sendErc20TransferTransaction",request:e}}var h,Ot,C6,$re,ON,LN,Kre,Yre,Xre,toe,noe,roe,ooe,soe,ioe,aoe,loe,q6,wf,D0,H6,U0,woe,voe,M0,koe,q0,xoe,Aoe,$0,V0,Toe,W0,V6,Soe,j6,Poe,W6,Eoe,K0,Roe,Q0,z6,J0,ev,_oe,nv,ov,Ioe,iv,Coe,lv,Noe,cv,Ooe,Loe,Doe,BN,Uoe,G6,Boe,Moe,Foe,qoe,Hoe,K6,Y6,Q6,$oe,Voe,joe,Woe,zoe,Goe,Koe,Yoe,Qoe,X6,Xoe,lr,J6,Z6,e8,t8,n8,r8,o8,s8,i8,a8,l8,ise,ase,lse,cse,use,dse,pse,mse,u8,hse,fse,d8,ur,r6,p8,yse,bse,m8,b8,Lf,Ese,w8,wv,Rse,v8,vv,k8,_se,kv,xv,S8,P8,E8,R8,_8,I8,N8,L8,Cse,Nse,Ev,Ose,_v,Lse,Cv,Dse,B8,Use,F8,Bse,H8,Mse,$8,Fse,V8,qse,Ov,Hse,Dv,$se,Bv,Vse,Mv,jse,qv,Wse,$v,zse,jv,Gse,zv,Kse,Kv,Yse,Qv,j8,Zv,Xse,o6,mN,W8,tk,uO,dO,G8,Zse,eie,tie,rk,nie,sk,ak,oie,sie,iie,ck,dk,mk,lie,cie,uie,fk,die,yk,fie,wk,gie,kk,pO,yie,Ak,bie,Sk,wie,Pk,vie,Y8,kie,xie,Aie,Tie,Sie,Pie,_k,Eie,Ik,Nk,Lk,Rie,Uk,_ie,Iie,vN,Q8,X8,Cie,Nie,Oie,Lie,Mk,Die,qk,qie,Hie,$ie,Vie,$k,jk,zk,Kk,Tf,Sf,J8,c6,u6,jie,Xk,Kie,Yie,Z8,Qie,ex,tx,t5,Jie,Zie,n5,d6,eae,tae,nc,rae,hN,oae,fN,AN,cae,m6,dae,h6,pae,u5,g6,y6,gae,f5,xae,Aae,SN,PN,Tae,Sae,Pae,g5,y5,Eae,k6,vO,kO,E5,_5,Oae,Lae,Dae,Uae,dx,mx,hx,gx,yx,AO,jae,Wae,wx,zae,D5,kx,kn,Zae,ele,tle,nle,rle,ole,sle,TO,U5,B5,SO,M5,ile,ale,lle,la,mi,E0,PO,cr,xx,F5,ple,mle,EO,q5,ble,vle,xle,Ale,Sle,Ele,Rle,_le,Cle,Nle,Ole,Dle,Ule,Ble,Fle,qle,Hle,$le,jle,Wle,zle,Kle,Yle,Qle,Jle,Zle,ece,tce,oce,sce,ice,dce,Tx,mce,gN,V5,Sx,Px,_O,gce,yce,bce,IO,T0,S0,wce,vce,xce,Ace,j5,Ece,Rce,EN,RN,Ice,Cce,Nce,R0,Oce,Dce,qce,$ce,Vce,Ex,jce,zce,Kce,Rx,Qce,_x,rue,yN,oue,sue,iue,aue,bN,Ix,G5,sc,ms,K5,pue,Cx,mue,Ox,hue,Dx,fue,gue,Ux,yue,bue,wue,Mx,Y5,vue,kue,xue,Aue,Tue,qx,Sue,$x,jx,Pue,Eue,Rue,Mue,Fue,que,Hue,$ue,Vue,jue,Wue,X5,zue,Gue,Kue,Yue,Que,zx,Gx,J5,Kx,Yx,Qx,lde,nA,cde,ude,dde,rA,pde,oA,mde,sA,hde,iA,fde,aA,gde,lA,cA,nV,rV,oV,sV,bde,Vd,iV,lV,mA,uV,dV,pV,mV,wde,jd,hV,gV,yA,bV,wV,vde,vV,kV,xV,kde,wA,Pde,kA,ic,AA,ac,TA,lc,SA,PA,FO,Ede,Rde,_de,Ide,Cde,Nde,Ode,fs,Lde,P6,N0,Ude,RA,Fde,qde,IA,zde,NA,Gde,LA,Wd,E6,Kde,UA,Qde,Xde,MA,qA,$A,Jde,Zde,RV,epe,VA,tpe,WA,GA,YA,spe,R6,_V,ipe,XA,IV,lpe,cpe,upe,mpe,hpe,fpe,gpe,ype,bpe,JA,eT,nT,oT,wpe,iT,vpe,CV,lT,uT=L(()=>{"use strict";e0();pf();pf();UC();Al();h=require("zod");s0();fw();D$();f0();f0();k4();y0();y0();iN();W4();Xw();dN();Z4();Ot=h.z.number().int().positive();C6=h.z.strictObject({offset:h.z.number().int().min(0),pageSize:Ot});$re=h.z.object({kind:h.z.literal("keyset"),fingerprint:h.z.string(),cursor:h.z.string().min(1)});ON=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(!M6(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=n6(e.gasPrice)),e.value!==void 0&&(t.value=n6(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(t6(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 t6(i.result)})}async#s(e){let t;try{t=await d0.post(this.#e,{json:e,throwHttpErrors:!1})}catch(r){throw I.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(!e6(n))throw new C("Unexpected JSON-RPC response shape");return n}async#n(e){let t;try{t=await d0.post(this.#e,{json:e,throwHttpErrors:!1})}catch(r){throw I.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=>e6(r)))throw new C("Unexpected JSON-RPC response shape");return n}};LN=(e=>(e.OWNER="OWNER",e.SESSION_KEY="SESSION_KEY",e))(LN||{}),Kre="0x0000000000000000000000000000000000000000000000000000000000000000",Yre="0x6492649264926492649264926492649264926492649264926492649264926492";Xre="3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000";toe="0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",noe="0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",roe=0x61003d3d8160233d3973n;ooe="0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",soe="0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",ioe="0x60195155f3363d3d373d3d363d602036600436635c60da",aoe=0x6100523d8160233d3973n,loe="0x49493a4d";q6=h.z.string().transform(e=>e);wf=h.z.union([h.z.number().int().min(0),h.z.date()]).transform(e=>e instanceof Date?Math.floor(e.getTime()/1e3):e),D0=h.z.union([h.z.literal("full"),h.z.object({start:wf.optional(),end:wf.optional()}).refine(e=>!e.end||e.end>=(e.start??0),"end must not precede start")]).transform(e=>e==="full"?{start:1}:e),H6=Gt.refine(e=>/^[1-9]\d*$/.test(e)&&BigInt(e)<=2147483647n,"Expected a positive 32-bit event ID");U0=B($,O,ce,I,C);woe=h.z.object({cursor:ye.optional(),id:h.z.string().optional(),market:h.z.string().optional()}),voe=Fd(woe.shape).default({}),M0=B($,O,ce,I,C,E);koe=h.z.object({orderId:h.z.string()}),q0=B($,O,ce,I,C,E);xoe={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()},Aoe=Fd(xoe).default({}),$0=B($,O,ce,I,C,E);V0=B($,O,ce,I,C),Toe=h.z.object({ids:h.z.array(h.z.string()).min(1)});W0=B($,O,ce,I,C,E);V6=h.z.object({assetType:k3}),Soe=Fd(V6.shape),j6=B($,O,ce,I,C,E);Poe=Fd(V6.shape),W6=B($,O,ce,I,C,E);Eoe=h.z.object({orderId:h.z.string()}),K0=B($,O,ce,I,C,E);Roe=h.z.object({orderIds:h.z.array(h.z.string())}),Q0=B($,O,ce,I,C,E);z6=h.z.object({cursor:ye.optional(),date:h.z.string()}),J0=B($,O,ce,I,C,E);ev=B($,O,ce,I,C,E);_oe=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()}),nv=B($,O,ce,I,C,E);ov=B($,O,ce,I,C);Ioe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J.optional(),takerOnly:h.z.boolean().optional(),filterType:M$.optional(),filterAmount:h.z.number().min(0).optional(),conditionId:h.z.union([xe,aa(xe,20)]).optional(),eventId:h.z.array(Gt).min(1).optional(),side:Nt.optional(),window:D0.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),iv=B($,O,I,C,E);Coe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([xe,aa(xe,20)]).optional(),eventId:h.z.array(Gt).min(1).optional(),type:h.z.array(XC).min(1).optional(),side:Nt.optional(),sortDirection:h0.optional(),window:D0.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),lv=B($,O,I,C,E);Noe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([Zt,aa(Zt,20)]).optional()}),cv=B($,O,I,C,E);Ooe=64,Loe=/^0x[0-9a-fA-F]{62}$/,Doe=/^0x[0-9a-fA-F]{64}$/,BN="0x0000000000000000000000000000000000000000000000000000000000000000",Uoe=Ie.from("function approve(address spender, uint256 amount)"),G6=Ie.from("function allowance(address owner, address spender) view returns (uint256)"),Boe=Ie.from("function transfer(address recipient, uint256 amount)"),Moe=Ie.from("function authorizeSessionSigner(address sessionSigner, uint256 validUntil)"),Foe=Ie.from("function revokeSessionSigner(address sessionSigner)"),qoe=Ie.from("function deposit(address token, uint256 amount, address to)"),Hoe=Ie.from("function setApprovalForAll(address operator, bool approved)"),K6=Ie.from("function isApprovedForAll(address account, address operator) view returns (bool)"),Y6=Ie.from("function balanceOf(address account, uint256 id) view returns (uint256)"),Q6=Ie.from("function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])"),$oe=Ie.from("function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Voe=Ie.from("function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),joe=Ie.from("function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)"),Woe=Ie.from("function split(bytes31 conditionId, uint256 amount)"),zoe=Ie.from("function merge(bytes31 conditionId, uint256 amount)"),Goe=Ie.from("function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)"),Koe=Ie.from("function prepareCondition(uint256[] legs) returns (bytes31)"),Yoe=Ie.from("function multiSend(bytes)"),Qoe=Ie.from("function proxy((uint8 typeCode, address to, uint256 value, bytes data)[] calls) returns (bytes[])"),X6=[1n,2n],Xoe=[1n,2n],lr=(1n<<256n)-1n,J6=B(E);Z6=B(E);e8=B(E);t8=B(E);n8=B(E);r8=B(E);o8=B(E);s8=B(E);i8=B(E);a8=B(E);l8=B($,O,tt,en,I,C,E);B(vt,ce);B(vt,ce);ise=[{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],ase=[{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"}],lse="DepositWallet",cse="1",use=600,dse=[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],pse=[{name:"wallet",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"calls",type:"Call[]"}],mse=h.z.object({address:h.z.string(),type:h.z.enum(Ir)}),u8=B($,O,I,C,E);hse=h.z.object({transactionId:Ji}),fse=h.z.object({wallet:J,type:h.z.enum(Se)}),d8=B($,O,I,C,E);ur=h.z.string().max(500),r6=10,p8=B($,O,I,C,E);yse=h.z.object({data:h.z.custom(ln),to:J,value:h.z.bigint().optional()}),bse=h.z.object({calls:h.z.array(yse).min(1).transform(e=>iq(e)),metadata:ur}),m8=B($,O,I,C,E);b8=B($,O,I,C,E,tt,en),Lf=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 eO(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 os(this.#e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for transaction ${this.transactionId} to settle`)}},Ese=h.z.object({amount:h.z.union([h.z.bigint(),h.z.literal("max")]),metadata:ur.optional(),spenderAddress:J,tokenAddress:J}),w8=B(E);wv=B(vt,$,O,ce,I,C,E);Rse=h.z.object({approved:h.z.boolean().default(!0),metadata:ur.optional(),operatorAddress:J,tokenAddress:J}),v8=B(E);vv=B(vt,$,O,ce,I,C,E);k8=B(O,I,C,E),_se=h.z.object({user:J}),kv=B(O,I,C,E);xv=B(vt,$,O,ce,tt,en,I,C,E);S8=B($,O,I,C);P8=B($,O,I,C);E8=B($,O,I,C);R8=B($,O,ce,I,C);_8=B($,O,ce,I,C);I8=B($,O,ce,I,C);N8=B($,O,ce,I,C);L8=B($,O,ce,I,C);Cse=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()}),Nse=Fd(Cse.shape),Ev=B($,O,I,C,E);Ose=Nr({}),_v=B($,O,I,C,E);Lse=h.z.array(Nr({})).min(1),Cv=B($,O,I,C,E);Dse=Nr({}),B8=B($,O,I,C,E);Use=Nr({}),F8=B($,O,I,C,E);Bse=Nr({}),H8=B($,O,I,C,E);Mse=h.z.object({conditionId:xe}),$8=B($,O,I,C,E);Fse=h.z.object({builderCode:bo}),V8=B($,O,I,C,E);qse=Nr({side:Nt}),Ov=B($,O,I,C,E);Hse=h.z.array(Nr({side:Nt})).min(1),Dv=B($,O,I,C,E);$se=Nr({}),Bv=B($,O,I,C,E);Vse=h.z.array(Nr({})).min(1),Mv=B($,O,I,C,E);jse=Nr({}),qv=B($,O,I,C,E);Wse=h.z.array(Nr({})).min(1),$v=B($,O,I,C,E);zse=Nr({}),jv=B($,O,I,C,E);Gse=h.z.array(Nr({})).min(1),zv=B($,O,I,C,E);Kse=h.z.object({cursor:ye.optional(),sponsored:h.z.boolean().optional()}).default({}),Kv=B($,O,I,C,E);Yse=h.z.object({conditionId:xe,cursor:ye.optional(),sponsored:h.z.boolean().optional()}),Qv=B($,O,I,C,E);j8=2*6e4,Zv=B($,O,I,C);Xse=h.z.object({plan:E4}),o6=10,mN="Collateral return",W8=B(O,I,C,E);tk=B(vt,$,O,ce,I,C,E);uO=100,dO=200,G8={maxOffset:dO,maxPageSize:uO},Zse=h.z.object({ascending:h.z.boolean().optional(),cursor:ye.optional(),pageSize:Ot.max(uO).default(20),getPositions:h.z.boolean().optional(),holdersOnly:h.z.boolean().optional(),order:h.z.string().optional(),parentEntityId:h.z.union([Gt,Hh]),parentEntityType:Js}),eie=h.z.object({getPositions:h.z.boolean().optional(),id:Xs}),tie=h.z.object({address:h.z.string(),ascending:h.z.boolean().optional(),cursor:ye.optional(),order:h.z.string().optional(),pageSize:Ot.max(uO).default(20)}),rk=B(Nl,$,O,I,C,E),nie=h.z.enum(["id","createdAt"]);sk=B($,O,I,C,E);ak=B(Nl,$,O,I,C,E);oie=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:re.optional(),endDateMin:re.optional(),ended:h.z.boolean().optional(),eventDate:zn.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:re.optional(),startDateMin:re.optional(),startTimeMax:re.optional(),startTimeMin:re.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()}),sie=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()})]),iie=h.z.object({id:h.z.string()}),ck=B($,O,I,C,E);dk=B($,O,I,C,E);mk=B($,O,I,C,E);lie=h.z.array(Fl).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct condition ids"),cie=h.z.array(H6).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct event ids"),uie=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:lie,eventIds:h.z.never().optional()}),h.z.object({questionId:h.z.never().optional(),conditionIds:h.z.never().optional(),eventIds:cie})]),fk=B($,O,I,C,E);die=h.z.object({eventIds:h.z.array(H6).min(1).transform(e=>[...new Set(e)])}),yk=B($,O,I,C,E);fie=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),window:bf.optional()}),wk=B($,O,I,C,E);gie=h.z.object({interval:i4.optional(),bucketLimit:h.z.number().int().positive().max(90).optional()}),kk=B($,O,I,C,E);pO=h.z.string().min(1),yie=h.z.object({category:pO.optional(),cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),sortBy:a4.optional(),window:bf.optional()}),Ak=B($,O,I,C,E);bie=h.z.object({category:pO.optional(),user:J,window:bf.optional()}),Sk=B($,O,I,C,E);wie=h.z.object({category:pO.optional(),cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),window:bf.optional()}),Pk=B($,O,I,C,E);vie=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(mf),h.z.array(h.z.enum(mf))]).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)}),Y8=B($,O,I,C,E);kie=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:re.optional(),endDateMin:re.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:re.optional(),startDateMin:re.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()}),xie=h.z.object({id:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),Aie=h.z.object({slug:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),Tie=h.z.object({url:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),Sie=h.z.union([xie,Aie,Tie]),Pie=h.z.object({id:h.z.string()}),_k=B($,O,I,C,E);Eie=h.z.object({cursor:ye.optional(),pageSize:Ot.max(100).optional(),exclude:h.z.array(xe).optional()}),Ik=B($,O,I,C,E);Nk=B($,O,I,C,E);Lk=B($,O,I,C,E);Rie=h.z.object({conditionIds:aa(Fl,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"]}))}),Uk=B($,O,I,C,E);_ie=360*60*60,Iie=253402300799,vN=wf.pipe(h.z.number().int().positive().max(Iie)),Q8=h.z.string().min(1).pipe(Me),X8={assetId:Q8,bucketSeconds:h.z.number().int().min(60).max(86400).optional(),cursor:ye.optional(),pageSize:Ot.max(1e4).default(1e4)},Cie=h.z.object({...X8,interval:t4,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"]})}),Nie=h.z.object({...X8,start:vN,end:vN.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>_ie&&n.addIssue({code:"custom",message:"start to end must span at most 15 days",path:["end"]})}),Oie=h.z.object({assetId:Q8,asOf:vN,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()}),Lie=h.z.union([Cie,Nie,Oie]),Mk=B($,O,I,C,E);Die=h.z.object({conditionIds:aa(Fl,20).optional()}),qk=B($,O,I,C,E);qie=h.z.object({orderId:h.z.string()}),Hie=h.z.object({orderIds:h.z.array(h.z.string()).min(1).max(3e3)}),$ie=h.z.object({market:h.z.string().optional()}),Vie=Fd($ie.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"]}),$k=B(O,$,ce,I,C,E);jk=B(O,$,ce,I,C,E);zk=B(O,$,ce,I,C);Kk=B(O,$,ce,I,C,E);Tf=h.z.object({assetId:Me,tokenId:h.z.never().optional()}),Sf=h.z.object({assetId:h.z.never().optional(),tokenId:Me}),J8=h.z.object({orderType:h.z.union([h.z.literal(cn.FAK),h.z.literal(cn.FOK)]).default(cn.FOK)}),c6=J8.extend({side:h.z.literal(Ue.BUY),amount:ko}),u6=J8.extend({side:h.z.literal(Ue.SELL),shares:ko}),jie=h.z.union([c6.extend(Tf.shape),c6.extend(Sf.shape),u6.extend(Tf.shape),u6.extend(Sf.shape)]).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t})),Xk=B(So,$,O,I,C,E);Kie=BigInt(Number.MAX_SAFE_INTEGER),Yie=h.z.string().refine(Xie,{message:"Order salt must be a non-negative JavaScript-safe integer."}),Z8=h.z.looseObject({salt:Yie}),Qie=h.z.array(Z8).min(1).max(15),ex=B($,O,ce,I,C,E),tx=B($,O,ce,I,C,E);t5=32,Jie=1n,Zie=2n,n5=3n,d6=50,eae=(1n<<256n)-1n,tae=(1n<<64n)-1n<<40n;nc=1000000n,rae=8*Number.EPSILON,hN=6,oae=8*Number.EPSILON;fN=600*1e3,AN=Number.POSITIVE_INFINITY,cae=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:A0(this.#t,e,fN,()=>this.#e.fetchBuilderTakerFeeRate(e))}async fetchCurrentMarket(e){let t=await A0(this.#r,e,AN,()=>this.#e.resolveCondition(e)),n=await this.#i(t);return this.#o(e,t,n),this.#s.set(t,p6(n,fN)),{feeInfo:n.feeInfo,negRisk:n.negRisk,tickSize:n.tickSize}}async#n(e){let t=await A0(this.#r,e,AN,()=>this.#e.resolveCondition(e)),n=await A0(this.#s,t,fN,()=>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,p6(e));return{feeInfo:t.feeInfo,negRisk:t.negRisk,tickSize:t.tickSize,assetIds:n}}};m6=new WeakMap;dae=180,h6=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()}),pae=h.z.union([h6.extend(Tf.shape),h6.extend(Sf.shape)]).superRefine((e,t)=>{if(e.expiration!==void 0){let n=Math.floor(Date.now()/1e3)+dae;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}));u5=h.z.object({builderCode:bo.optional(),orderType:h.z.union([h.z.literal(cn.FAK),h.z.literal(cn.FOK)]).default(cn.FAK)}),g6=u5.extend({side:h.z.literal(Ue.BUY),amount:ko,maxSpend:ko.optional(),maxPrice:ko.optional()}),y6=u5.extend({side:h.z.literal(Ue.SELL),shares:ko,minPrice:ko.optional()}),gae=h.z.union([g6.extend(Tf.shape),g6.extend(Sf.shape),y6.extend(Tf.shape),y6.extend(Sf.shape)]).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t}));f5="Polymarket CTF Exchange",xae="DepositWallet",Aae="1",SN="0x0000000000000000000000000000000000000000000000000000000000000000",PN="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",Tae=Je.keccak256(we.fromString(PN),{as:"Hex"}),Sae=Je.keccak256(we.fromString("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),{as:"Hex"}),Pae=Je.keccak256(we.fromString(f5),{as:"Hex"}),g5=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],y5=[{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"}],Eae=[{name:"contents",type:"Order"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"}];k6="0x0000000000000000000000000000000000000000000000000000000000000000";vO=B(So,$,O,ce,I,C,E);kO=B($,O,ce,I,C,E);E5=vO;_5=kO;Oae=250,Lae=3e4,Dae={timeoutMs:h.z.number().int().positive().optional()},Uae=h.z.object(Dae).default({}),dx=B($,O,ce,tt,en,I,C,E);mx=B(vt,So,$,O,ce,I,C,E);hx=B(vt,So,$,O,ce,tt,en,I,C,E);gx=B(vt,$,O,ce,I,C,E);yx=B(vt,$,O,ce,tt,en,I,C,E);AO=h.z.string().regex(/^\d+(?:\.\d{1,28})?$/,"Expected a non-negative fixed-point fee rate with at most 28 fractional digits."),jae=h.z.object({builderAddress:J,feeRate:AO});Wae=h.z.object({address:J}),wx=B($,O,I,C,E);zae=h.z.strictObject({builder:J,maxFeeRate:AO,approvalVersion:h.z.number().int().positive().max(Number.MAX_SAFE_INTEGER)}),D5=h.z.strictObject({builderAddress:J.optional(),maxFeeRate:AO}),kx=B($,O,ce,I,C,E);kn=class{#e;#t;#r;#s;constructor({root:e,headers:t,resolveHeaders:n,onRateLimitUpdate:r}){this.#e=d0.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 In.fromPromise(e.then(async n=>{let r=Xae(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:I.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`}}},Zae=1e4,ele=3e4,tle=5e3,nle=10*6e4,rle=3e4,ole=25e3,sle=65e3,TO=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e("PING")},Zae)}handleMessage(e){return e!=="PONG"?!1:(this.#e=Date.now(),!0)}isStale(e){return e-this.#e>ele}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},U5=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e("PING")},tle)}handleMessage(){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>nle}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},B5=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>rle}},SO=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"}}))},ole)}handleMessage(){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>sle}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},M5=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}},ile=5e3,ale=250,lle=3e4,la=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)??ule(this.#t,{baseMs:ale,maxMs:lle});this.#t+=1,this.#e=yn(()=>{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:yn(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=cle(e.url,e.headers),s,i=()=>{o.removeEventListener("open",a),clearTimeout(s),this.#s=void 0,r(new I("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 I(`WebSocket connection failed: ${e.url}`,{cause:c}))};o.addEventListener("open",a,{once:!0}),this.#t!==void 0&&(this.#s=i,s=yn(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()},ile))}#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,()=>{})}};E0=1440*60*1e3,PO=90*E0,cr=h.z.number().int().nonnegative(),xx=h.z.object({start:cr.optional(),end:cr.optional()}),F5=h.z.object({interval:Vw,start:cr,end:cr.optional()}),ple=h.z.enum(["perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),mle=h.z.enum(["perpsEquityHistory","perpsPnlHistory"]),EO=h.z.object({kind:ple,startTimestamp:cr,endTimestamp:cr,instrumentId:Ae.optional(),depositStatus:kd.optional(),withdrawalStatus:xd.optional(),hash:et.optional(),seenKeys:h.z.array(h.z.string())}),q5=h.z.object({kind:mle,startTimestamp:cr,endTimestamp:cr,interval:Vw});ble=h.z.object({instrumentId:Ae.optional()}).default({});vle=h.z.object({instrumentId:Ae.optional()}).default({});xle=h.z.object({orderId:Cn.optional(),clientOrderId:Er.optional(),instrumentId:Ae.optional(),start:cr.optional(),end:cr.optional()}).default({}),Ale=xle.transform(({end:e,start:t,...n})=>({...n,endTimestamp:e,startTimestamp:t}));Sle=h.z.object({start:cr.optional(),end:cr.optional(),sort:II.optional(),cursor:ye.optional()});Ele=xx.extend({cursor:ye.optional(),instrumentId:Ae.optional()}),Rle=h.z.object({cursor:ye}),_le=h.z.union([Ele.transform(({cursor:e,...t})=>({cursor:e,params:Ax(t,E0)})),Rle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Cle=xx.extend({cursor:ye.optional(),depositStatus:kd.optional(),hash:et.optional()}),Nle=h.z.object({cursor:ye}),Ole=h.z.union([Cle.transform(({cursor:e,...t})=>({cursor:e,params:Ax(t,PO)})),Nle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Dle=xx.extend({cursor:ye.optional(),withdrawalStatus:xd.optional(),hash:et.optional()}),Ule=h.z.object({cursor:ye}),Ble=h.z.union([Dle.transform(({cursor:e,...t})=>({cursor:e,params:Ax(t,PO)})),Ule.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Fle=xx.extend({cursor:ye.optional()}),qle=h.z.object({kind:h.z.literal("perpsInternalTransfers"),startTimestamp:cr,endTimestamp:cr,seenKeys:h.z.array(h.z.string())}),Hle=h.z.object({cursor:ye}),$le=h.z.union([Fle.transform(({cursor:e,...t})=>({cursor:e,params:Ax(t,PO)})),Hle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);jle=F5.extend({cursor:ye.optional()}),Wle=h.z.object({cursor:ye}),zle=h.z.union([jle.transform(({cursor:e,...t})=>({cursor:e,params:H5(t)})),Wle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Kle=F5.extend({cursor:ye.optional()}),Yle=h.z.object({cursor:ye}),Qle=h.z.union([Kle.transform(({cursor:e,...t})=>({cursor:e,params:H5(t)})),Yle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Jle=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()}),Zle=h.z.object({sinceSeq:h.z.number().int().nonnegative().optional(),limit:h.z.number().int().positive().optional(),cursor:ye.optional()}),ece=h.z.object({cursor:ye}),tce=h.z.union([Zle.transform(({cursor:e,...t})=>({cursor:e,params:t})),ece.transform(({cursor:e})=>({cursor:e,params:void 0}))]);oce=h.z.object({ids:h.z.array(h.z.string().min(1)).min(1)}),sce=h.z.object({upTo:h.z.object({id:h.z.string().min(1),timestamp:h.z.number().int().nonnegative()})}),ice=h.z.union([oce.transform(({ids:e})=>({ids:e})),sce.transform(({upTo:e})=>({before:lce(e)}))]);dce=h.z.object({builder:J.optional()}).default({}),Tx=B($,O,I,C,E);mce=2160*60*60*1e3,gN=h.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),V5=h.z.object({start:gN.optional(),end:gN.optional(),asOfSequence:gN.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<=mce,{message:"The reporting window must not exceed 90 days",path:["end"]}).default({}),Sx=B($,O,I,C,E);Px=B($,O,I,C,E);_O=h.z.object({instrumentId:Ae,side:Nt,quantity:Ao,reduceOnly:h.z.boolean().default(!1),clientOrderId:Er.optional()}),gce=_O.extend({price:Ao,timeInForce:h.z.literal(ti.GTC),postOnly:h.z.boolean().default(!1)}),yce=_O.extend({price:Ao.optional(),timeInForce:h.z.literal(ti.IOC),postOnly:h.z.never().optional()}),bce=_O.extend({price:Ao.optional(),timeInForce:h.z.literal(ti.FOK),postOnly:h.z.never().optional()}),IO=h.z.discriminatedUnion("timeInForce",[gce,yce,bce]),T0=h.z.object({triggerPrice:Ao,limitPrice:Ao.optional()}),S0=h.z.object({triggerPrice:Ao}),wce=h.z.union([h.z.object({takeProfit:T0,stopLoss:T0.optional()}),h.z.object({takeProfit:T0.optional(),stopLoss:T0})]),vce=h.z.object({orders:h.z.array(IO).min(1),expiresAt:h.z.number().int().positive().optional()});xce=h.z.intersection(IO,h.z.intersection(wce,h.z.object({clientOrderId:Er.default(W5),expiresAt:h.z.number().int().positive().optional()}))),Ace=h.z.intersection(IO,h.z.object({clientOrderId:Er.default(W5),expiresAt:h.z.number().int().positive().optional(),takeProfit:h.z.never().optional(),stopLoss:h.z.never().optional()})),j5=h.z.array(cf).min(1).refine(e=>e.every(t=>t.status==="ok"),"Expected successful Perps order acknowledgements.");Ece=h.z.union([h.z.object({takeProfit:S0,stopLoss:S0.optional()}),h.z.object({takeProfit:S0.optional(),stopLoss:S0})]),Rce=h.z.intersection(Ece,h.z.object({instrumentId:Ae,expiresAt:h.z.number().int().positive().optional()}));EN=4,RN=2e3,Ice=100,Cce=1e3,Nce=h.z.object({maxAttempts:h.z.number().int().positive().default(EN),maxElapsedMs:h.z.number().int().positive().default(RN)}).default({maxAttempts:EN,maxElapsedMs:RN}),R0=h.z.object({expiresAt:h.z.number().int().positive().optional(),retry:h.z.union([h.z.literal(!1),Nce]).default({maxAttempts:EN,maxElapsedMs:RN}),signal:h.z.custom(e=>e instanceof AbortSignal,"Expected an AbortSignal.").optional()}),Oce=h.z.union([R0.extend({orderId:Cn,clientOrderId:h.z.undefined().optional()}),R0.extend({clientOrderId:Er,orderId:h.z.undefined().optional()})]);Dce=h.z.union([R0.extend({orderIds:h.z.array(Cn).min(1),clientOrderIds:h.z.undefined().optional()}),R0.extend({clientOrderIds:h.z.array(Er).min(1),orderIds:h.z.undefined().optional()})]);qce=h.z.object({instrumentId:Ae.optional(),expiresAt:h.z.number().int().positive().optional()}).default({});$ce=5e3,Vce=h.z.object({cancelAt:h.z.number().int().positive(),expiresAt:h.z.number().int().positive().optional()}).superRefine((e,t)=>{let n=Date.now()+$ce;e.cancelAt<n&&t.addIssue({code:"custom",message:"cancelAt must be at least 5 seconds in the future.",path:["cancelAt"]})}),Ex=B(df,$,O,ce,I,C,E),jce="auto_cancel_daily_limit_reached";zce=h.z.object({expiresAt:h.z.number().int().positive().optional()}).default({});Kce=h.z.object({instrumentId:Ae,leverage:h.z.number().int().positive(),crossMargin:h.z.boolean()}),Rx=B(O,ce,I,E);Qce=h.z.object({instrumentId:Ae,amount:Ao}),_x=B(O,ce,I,E);rue=3e4,yN=3e4,oue=2e3,sue=["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications","tpsl"],iue=new Set(["notifications","builderFills"]),aue=h.z.object({id:h.z.number().int().positive().optional(),data:h.z.unknown().optional()}).passthrough(),bN=h.z.union([lf,h.z.array(lf)]).transform(e=>Array.isArray(e)?e.find(t=>t.status==="err")??e[0]:e),Ix=B($,O,ce,I,C,E),G5=class{credentials;#e;#t;#r;#s;#n;#o;#i=new mi({heartbeat:new SO});#a=Bd({objectMode:!0});#u=new Map;#l=new Set;#c=new la;#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(M(e.builderAttribution,jae)),this.#d=typeof e.builderAttribution=="string"?M(e.builderAttribution,J):this.#m?.builderAddress,this.#t=new kn({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(W(tf)));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=A6(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=M(e,D5);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 I("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(W(tf)));this.#d=n.builder;let o=A6(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 pce(this.#t,e)}listBuilderEarnings(e){return hce(this.#t,e)}async fetchBuilderEarningsSummary(e){return await fce(this.#t,e)}async fetchBalances(){return await hle(this.#t)}async fetchPortfolio(){return await fle(this.#t)}async fetchStats(){return await gle(this.#t)}async fetchAccountConfig(e){return await wle(this.#t,e)}async fetchAutoCancelStatus(){return await yle(this.#t)}async fetchOpenOrders(e){return await kle(this.#t,e)}async fetchOrders(e){return await Tle(this.#t,e)}listFills(e={}){return Ple(this.#t,e)}listFundingPayments(e={}){return Ile(this.#t,e)}listDeposits(e={}){return Lle(this.#t,e)}listInternalTransfers(e={}){return Vle(this.#t,e)}listWithdrawals(e={}){return Mle(this.#t,e)}listEquityHistory(e){return Gle(this.#t,e)}listPnlHistory(e){return Xle(this.#t,e)}listNotifications(e={}){return nce(this.#t,e)}async fetchUnreadNotificationsCount(){return await rce(this.#t)}async markNotificationsRead(e){await ace(this.#t,e)}async placeOrder(e){return await Sce(this,e)}async postOrders(e){return await kce(this,e)}async placePositionTpSl(e){return await _ce(this,e)}async cancelOrder(e){return await Lce(this,e)}async cancelOrders(e){return await _N(this,e)}async cancelAllOrders(e){await Hce(this,e)}async armAutoCancel(e){await Wce(this.#t,(t,n)=>this.#k(t,n),e)}async disarmAutoCancel(e){await Gce(this.#t,(t,n)=>this.#k(t,n),e)}async updateLeverage(e){return await Yce(this,e)}async updateMargin(e){await Xce(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"},bN,rue,"Perps session authentication timed out.")}async#v(){await this.#w({id:this.#f++,req:"sub",chs:sue},bN,yN,"Perps session subscription timed out."),this.#h&&this.#w({id:this.#f++,req:"sub",chs:["builderFills"]},bN,yN,"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=C0(e.op),r=this.#k(e.op,e.expiresAt);return await this.#w({...r,id:this.#f++,op:n,req:"post"},t,yN,"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,oue),()=>{});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:C0(e.op)}}).andThen(W(e.responseSchema)))}#k(e,t){let n=uue(),r=Date.now(),o;try{o=Vae({chainId:this.#r,op:e,privateKey:this.credentials.privateKey,salt:n,timestamp:r})}catch(i){throw ce.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=lue(t);this.#u.set(e.id,o);let s=yn(()=>{o.reject(new I(r))},n);try{if(!this.#i.send(e))throw new I("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 I("Perps session closed.")),this.#I(new I("Perps session closed.")),this.#a.end(),await this.#i.close(),this.#n(this)}#S(e){if(this.#C(e)||HH.safeParse(e).success)return;let t=$H.safeParse(e);if(!t.success)return;let n=t.data;this.#O(n),this.#_(n)}#C(e){let t=aue.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=NO(t.data.data??t.data);return o!==void 0?n.reject(new O(o.error,{status:200})):n.reject(new I("Perps session unexpected response.")),!0}return cue(r.data)?n.reject(new O(r.data.error,{status:200})):n.resolve(r.data),!0}#N(){this.#R(new I("Perps session connection closed.")),this.#I(new I("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(iue.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.#_({channel:e.channel,previousSequence:t,reason:"sequence_gap",sequence:e.sequence,type:"resync"})}#_(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=yn(()=>{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)}#I(e){for(let t of Array.from(this.#l))this.#E(t),t.reject(e)}};sc=B($,O,I,C,E),ms=h.z.number().int().nonnegative(),K5=1440*60*1e3,pue=h.z.object({instrumentId:Ae.optional(),category:ef.optional()}).default({}),Cx=sc;mue=h.z.object({instrumentId:Ae}),Ox=sc;hue=h.z.object({instrumentId:Ae.optional()}).default({}),Dx=sc;fue=h.z.union([h.z.literal(10),h.z.literal(100),h.z.literal(500),h.z.literal(1e3)]),gue=h.z.object({instrumentId:Ae,depth:fue.default(100)}),Ux=sc;yue=h.z.object({instrumentId:Ae,interval:$w,start:ms.optional(),end:ms.optional(),cursor:ye.optional()}),bue=h.z.object({cursor:ye}),wue=h.z.union([yue.transform(({cursor:e,...t})=>({cursor:e,params:_ue(t)})),bue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Mx=sc;Y5=h.z.object({instrumentId:Ae,start:ms.optional(),end:ms.optional()}),vue=Y5.extend({cursor:ye.optional()}),kue=h.z.object({cursor:ye}),xue=h.z.union([vue.transform(({cursor:e,...t})=>({cursor:e,params:Q5(t)})),kue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Aue=Y5.extend({cursor:ye.optional()}),Tue=h.z.object({cursor:ye}),qx=sc;Sue=h.z.union([Aue.transform(({cursor:e,...t})=>({cursor:e,params:Q5(t)})),Tue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),$x=sc;jx=B($,O,I,C);Pue=h.z.object({kind:h.z.literal("perpsCandles"),instrumentId:Ae,interval:$w,startTimestamp:ms,endTimestamp:ms}),Eue=h.z.object({kind:h.z.literal("perpsFundingHistory"),instrumentId:Ae,startTimestamp:ms,endTimestamp:ms}),Rue=h.z.object({kind:h.z.literal("perpsTrades"),instrumentId:Ae,startTimestamp:ms,endTimestamp:ms,seenTradeIds:h.z.array(ea)});Mue=h.z.custom(e=>$_(e),"Expected a hex-encoded 32-byte private key."),Fue=h.z.object({proxy:h.z.string().transform(e=>Be(e)),privateKey:Mue,secret:h.z.string().min(1),expiresAt:h.z.number().int().positive()}),que=10080*60*1e3,Hue=h.z.strictObject({builderAttribution:J.optional(),includeBuilderFills:h.z.boolean().optional(),expiresIn:h.z.number().int().positive().default(que),label:h.z.string().min(1).optional()}),$ue=h.z.strictObject({builderAttribution:J.optional(),includeBuilderFills:h.z.boolean().optional(),credentials:Fue}),Vue=h.z.union([Hue,$ue]),jue=h.z.object({proxy:h.z.string()}),Wue=jue.transform(e=>({proxy:Be(e.proxy)})),X5=h.z.bigint().positive().max(lr),zue=h.z.object({amount:X5,metadata:ur.optional()}),Gue=h.z.object({amount:X5}),Kue=Ao.refine(e=>/^\d+(?:\.\d+)?$/.test(e)&&/[1-9]/.test(e),"Expected a positive fixed-point decimal amount."),Yue=h.z.string().min(1).refine(e=>new TextEncoder().encode(e).byteLength<=64,"Expected a label no longer than 64 UTF-8 bytes."),Que=h.z.object({recipient:J,amount:Kue,label:Yue.optional()}),zx=B($,O,ce,I,C,E),Gx=B($,O,ce,I,C,E),J5=B(E),Kx=B(vt,$,O,ce,I,C,E),Yx=B($,O,ce,I,C,E),Qx=B($,O,ce,I,C,E);lde=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J.optional(),conditionId:h.z.union([Fl,aa(Fl,20)]).optional(),status:F$.optional(),eventId:h.z.array(Gt).min(1).optional(),filterType:H$.optional(),filterAmount:h.z.number().min(0).optional(),includeArchived:h.z.boolean().optional(),sortBy:q$.optional(),sortDirection:h0.optional(),window:D0.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"]}),nA=B($,O,I,C,E);cde=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"})]),ude=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([Zt,aa(Zt,20)]).optional(),status:cde.optional(),sortBy:$$.optional(),sortDirection:h0.optional(),updatedAfter:wf.optional(),updatedBefore:wf.optional()}),dde=ude.refine(e=>e.updatedBefore===void 0||e.updatedAfter===void 0||e.updatedBefore>=e.updatedAfter,{message:"updatedBefore must not precede updatedAfter",path:["updatedBefore"]}),rA=B($,O,I,C,E);pde=h.z.object({user:J,conditionIds:aa(Fl,20).optional()}),oA=B($,O,I,C,E);mde=h.z.object({user:J}),sA=B($,O,I,C,E);hde=h.z.object({user:J,interval:JC.optional(),fidelity:p0.optional()}),iA=B($,O,I,C,E);fde=h.z.object({user:J,window:D0.optional()}),aA=B($,O,I,C,E);gde=h.z.object({user:h.z.string()}),lA=B($,O,I,C,E);cA=B($,O,I,C,E),nV=h.z.object({amount:h.z.bigint().min(0n),conditionId:xe,metadata:ur.optional()}),rV=cA;oV=h.z.object({amount:h.z.bigint().positive(),legs:h.z.array(Xe).min(1).max(50),metadata:ur.optional()}),sV=cA;bde=h.z.union([nV.extend({legs:h.z.never().optional()}),oV.extend({conditionId:h.z.never().optional()})]);Vd=B(vt,$,O,ce,tt,en,I,C,E),iV=Vd;lV=Vd;mA=B($,O,I,C,E),uV=h.z.object({amount:h.z.union([h.z.bigint().positive(),h.z.literal("max")]),conditionId:xe,metadata:ur.optional()}),dV=mA;pV=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()}),mV=mA;wde=h.z.union([uV.extend({legs:h.z.never().optional()}),pV.extend({conditionId:h.z.never().optional()})]);jd=B(vt,$,O,ce,tt,en,I,C,E),hV=jd;gV=jd;yA=B($,O,I,C,E),bV=h.z.object({conditionId:xe,marketId:h.z.never().optional(),amount:h.z.never().optional(),positionId:h.z.never().optional(),metadata:ur.optional()}),wV=h.z.object({conditionId:h.z.never().optional(),marketId:Qi,amount:h.z.never().optional(),positionId:h.z.never().optional(),metadata:ur.optional()}),vde=h.z.union([bV,wV]),vV=yA;kV=h.z.object({positionId:Xe,conditionId:h.z.never().optional(),marketId:h.z.never().optional(),metadata:ur.optional()});xV=yA;kde=h.z.union([bV,wV,kV]);wA=B(vt,$,O,ce,tt,en,I,C,E);Pde=h.z.object({address:h.z.string()}),kA=B($,O,I,C,E);ic=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}},AA=B(Qr,ic,ce,tt,I,E),ac=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}},TA=B(Qr,ac,tt,I),lc=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}},SA=B(Qr,lc,tt,I),PA=B(Qr,I,E);FO="/v1/builder/rfq/requests",Ede=3e4,Rde=3e4,_de=3e4,Ide=500,Cde=3e4,Nde=1e3,Ode="0x0000000000000000000000000000000000000000000000000000000000000000",fs=class extends Ct{name="RfqRequestRejectedError";status;code;constructor(e,t){super(e,t),this.status=t.status,this.code=t.code}};Lde=new Set(Object.values(li));P6=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})),N0=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=Dde(r,o);return s<=0n?(t.addIssue({code:"custom",message:"Value must be greater than 0."}),h.z.NEVER):s.toString()});Ude=h.z.discriminatedUnion("direction",[h.z.object({amount:N0,direction:h.z.literal(Ue.BUY),legPositionIds:P6,side:h.z.literal(Eo.Yes).optional()}),h.z.object({direction:h.z.literal(Ue.SELL),legPositionIds:P6,side:h.z.literal(Eo.Yes).optional(),size:N0})]),RA=B($,fs,I,C,E);Fde=Nt,qde=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(xw),direction:Fde,expiresAt:h.z.number().int().nonnegative(),makerAmount:N0.transform(Tl),netReceive:h.z.string().optional(),positionId:h.z.string().regex(/^\d+$/,"positionId must be a numeric string.").transform(Tw),quoteId:h.z.string().min(1).transform(Sw),rfqId:h.z.string().min(1).transform(md),takerAmount:N0.transform(Tl),totalRequired:h.z.string()}),IA=B(vt,$,fs,ce,tt,I,C,E);zde=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()}),NA=B($,fs,tt,I,C,E);Gde=h.z.object({rfqId:h.z.string().min(1).transform(md)}),LA=B($,fs,I,C,E);Wd=(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))(Wd||{}),E6=100,Kde=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(Wd).optional()}),UA=B(Nl,$,O,I,C,E);Qde=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()}),Xde=h.z.object({id:h.z.string(),locale:h.z.string().optional()}),MA=B($,O,I,C,E);qA=B($,O,I,C,E);$A=B($,O,ce,I,C,E);Jde=[yo.ALL],Zde=4315*60*60,RV=300*1e3,epe=h.z.object({address:J,idempotencyKey:h.z.string().trim().min(1).optional(),scopes:h.z.array(Nh).min(1).default(Jde)}).superRefine((e,t)=>{zt(e.address,rs)&&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())})),VA=B(vt,$,O,ce,tt,en,I,C,E);tpe=h.z.object({address:J,idempotencyKey:h.z.string().trim().min(1).optional()}).superRefine((e,t)=>{zt(e.address,rs)&&t.addIssue({code:"custom",message:"Session key address must not be the zero address.",path:["address"]})}).transform(e=>({...e,address:Be(e.address.toLowerCase())})),WA=B(vt,$,O,ce,tt,en,I,C,E);GA=B($,O,I,C);YA=B($,O,I,C);spe=h.z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._:/-]+$/),R6=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."}),_V=(e=>(e.Update="update",e.Subscribe="subscribe",e))(_V||{}),ipe=h.z.discriminatedUnion("topic",[h.z.strictObject({topic:h.z.literal("prices.crypto"),symbols:h.z.array(R6).min(1)}),h.z.strictObject({topic:h.z.literal("prices.crypto.twap"),symbols:h.z.array(R6).min(1)}),h.z.strictObject({topic:h.z.literal("prices.equity"),symbol:spe,types:h.z.array(h.z.enum(_V)).optional()})]);XA=B(I,E,O,Qr),IV=(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))(IV||{}),lpe=h.z.object({topic:h.z.enum(IV)}),cpe=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()}),upe=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()})]);mpe=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)}),hpe=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()})]),fpe=h.z.object({id:h.z.string(),omitEmpty:h.z.boolean().optional(),status:h.z.enum(["active","closed","all"]).optional()}),gpe=h.z.object({slug:h.z.string()}),ype=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()}),bpe=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()}),JA=B($,O,I,C,E);eT=B($,O,I,C,E);nT=B($,O,I,C,E);oT=B($,O,I,C,E);wpe=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()}),iT=B($,O,I,C,E);vpe=h.z.object({amount:h.z.bigint(),metadata:ur.optional(),recipientAddress:J,tokenAddress:J}),CV=B(E);lT=B(vt,$,O,ce,I,C,E)});var rj={};fr(rj,{AcceptComboQuoteError:()=>IA,ActivityType:()=>m0,ApproveErc1155ForAllError:()=>vv,ApproveErc20Error:()=>wv,ApprovePerpsBuilderFeeError:()=>kx,ArmPerpsAutoCancelError:()=>Ex,AssetType:()=>ra,AuthorizeSessionKeyError:()=>VA,AutoCancelDailyLimitError:()=>df,BiggestWinnerKind:()=>Yl,BuilderVolumeInterval:()=>Gl,CancelAllError:()=>zk,CancelMarketOrdersError:()=>Kk,CancelOrderError:()=>$k,CancelOrdersError:()=>jk,CancelledSigningError:()=>vt,CollateralReturnKnownOperationKind:()=>Dd,CombinatorialPrepareConditionCallError:()=>a8,ComboAcceptFailureReason:()=>Ro,ComboActivityType:()=>Wl,ComboKnownStatus:()=>Iw,ComboPositionSortBy:()=>$l,ComboPositionStatus:()=>ii,ComboQuoteUnavailableReason:()=>ci,CommentParentEntityType:()=>Ch,ConnectionLostError:()=>Qr,CreateLimitOrderError:()=>gx,CreateMarketOrderError:()=>mx,CreateSecureClientError:()=>Mme,CtfMergePositionsCallError:()=>n8,CtfRedeemPositionsCallError:()=>r8,CtfSplitPositionCallError:()=>t8,DepositToPerpsError:()=>Kx,DownloadAccountingSnapshotError:()=>lA,DropNotificationsError:()=>W0,Erc20ApprovalCallError:()=>J6,Erc20TransferCallError:()=>Z6,EstimateMarketPriceError:()=>Xk,ExecuteCollateralReturnPlanError:()=>tk,FetchBuilderVolumeError:()=>kk,FetchClosedOnlyModeError:()=>U0,FetchCommentsByIdError:()=>sk,FetchEventError:()=>dk,FetchEventLiveVolumeError:()=>yk,FetchEventTagsError:()=>mk,FetchLastTradePriceError:()=>jv,FetchLastTradePricesError:()=>zv,FetchMarketError:()=>Nk,FetchMarketTagsError:()=>Lk,FetchMidpointError:()=>_v,FetchMidpointsError:()=>Cv,FetchNotificationsError:()=>V0,FetchOpenInterestError:()=>qk,FetchOrderBookError:()=>Bv,FetchOrderBooksError:()=>Mv,FetchOrderError:()=>q0,FetchOrderScoringError:()=>K0,FetchOrdersScoringError:()=>Q0,FetchPerpsBookError:()=>Ux,FetchPerpsBuilderApprovalsError:()=>Tx,FetchPerpsBuilderEarningsSummaryError:()=>Px,FetchPerpsBuilderStatusError:()=>wx,FetchPerpsFeesError:()=>jx,FetchPerpsInstrumentsError:()=>Cx,FetchPerpsTickerError:()=>Ox,FetchPerpsTickersError:()=>Dx,FetchPortfolioValueError:()=>oA,FetchPriceError:()=>Ov,FetchPricesError:()=>Dv,FetchPublicProfileError:()=>kA,FetchRelatedTagResourcesError:()=>oT,FetchRelatedTagsError:()=>nT,FetchResolutionsError:()=>fk,FetchRewardPercentagesError:()=>ov,FetchRfqStatusError:()=>LA,FetchSeriesError:()=>qA,FetchSessionKeysError:()=>$A,FetchSportsMarketTypesError:()=>YA,FetchSpreadError:()=>qv,FetchSpreadsError:()=>$v,FetchTagError:()=>eT,FetchTotalEarningsForUserForDayError:()=>ev,FetchTraderLeaderboardStandingError:()=>Sk,FetchTradingApprovalsStateError:()=>kv,FetchUserPnlError:()=>iA,FetchUserStatsError:()=>sA,FetchUserVolumeError:()=>aA,InsufficientLiquidityError:()=>So,LeaderboardWindow:()=>zl,ListAccountTradesError:()=>$0,ListActivityError:()=>lv,ListBiggestWinnersError:()=>Pk,ListBuilderLeaderboardError:()=>wk,ListBuilderTradesError:()=>Ev,ListComboActivityError:()=>cv,ListComboMarketsError:()=>Ik,ListComboPositionsError:()=>rA,ListCommentsByUserAddressError:()=>ak,ListCommentsError:()=>rk,ListCurrentRewardsError:()=>Kv,ListEventsError:()=>ck,ListMarketHoldersError:()=>Uk,ListMarketRewardsError:()=>Qv,ListMarketsError:()=>_k,ListOpenOrdersError:()=>M0,ListPerpsBuilderEarningsError:()=>Sx,ListPerpsCandlesError:()=>Mx,ListPerpsFundingHistoryError:()=>qx,ListPerpsTradesError:()=>$x,ListPositionsError:()=>nA,ListPriceHistoryError:()=>Mk,ListSeriesError:()=>MA,ListSportsError:()=>GA,ListTagsError:()=>JA,ListTeamsError:()=>iT,ListTraderLeaderboardError:()=>Ak,ListTradesError:()=>iv,ListUserEarningsAndMarketsConfigError:()=>nv,ListUserEarningsForDayError:()=>J0,MAX_UINT256:()=>lr,MergePositionsError:()=>jd,NotificationType:()=>n0,OpenPerpsSessionError:()=>zx,OpenRfqSessionError:()=>PA,OperationAbortedError:()=>Jw,OrderPostStatus:()=>r0,OrderResponseErrorCode:()=>o0,OrderSide:()=>Ue,OrderType:()=>cn,PaginationLimitError:()=>Nl,PerpsCancelRetryError:()=>Zw,PerpsDepositCallError:()=>e8,PerpsDepositStatus:()=>Qh,PerpsInstrumentCategory:()=>Kh,PerpsInstrumentType:()=>Gh,PerpsInternalTransferDirection:()=>Xh,PerpsKlineInterval:()=>Jh,PerpsKnownCancelOrderErrorCode:()=>Sd,PerpsKnownInternalTransferType:()=>Hw,PerpsKnownWithdrawalStatus:()=>qw,PerpsLiquidityRole:()=>nf,PerpsMarginType:()=>sf,PerpsNotificationOrderType:()=>of,PerpsNotificationType:()=>rf,PerpsOrderStatus:()=>af,PerpsSide:()=>Yh,PerpsSortDirection:()=>Zh,PerpsTimeInForce:()=>ti,PlaceLimitOrderError:()=>yx,PlaceMarketOrderError:()=>hx,PlanCollateralReturnError:()=>Zv,PositionFilterType:()=>Hl,PositionSortBy:()=>ql,PositionStatus:()=>ai,PostOrderError:()=>ex,PostOrdersError:()=>tx,PriceHistoryInterval:()=>Po,ProtocolVersion:()=>Zi,RateLimitError:()=>$,RealtimeKnownErrorCode:()=>Ed,RedeemPositionsError:()=>wA,RequestComboQuoteError:()=>RA,RequestRejectedError:()=>O,ResolutionMarketType:()=>Xl,ResolutionReporter:()=>Zl,ResolutionSource:()=>Jl,ResolutionStatus:()=>Ql,RevokePerpsBuilderFeeError:()=>Ix,RevokePerpsCredentialsError:()=>Gx,RevokeSessionKeyError:()=>WA,RfqCancelQuoteError:()=>TA,RfqCancelQuoteRejectedError:()=>ac,RfqConfirmationDecision:()=>ds,RfqConfirmationError:()=>SA,RfqConfirmationRejectedError:()=>lc,RfqDirection:()=>Nn,RfqExecutionStatus:()=>ps,RfqKnownErrorCode:()=>Cr,RfqQuoteError:()=>AA,RfqQuoteRejectedError:()=>ic,RfqRejectionCode:()=>li,RfqRequestRejectedError:()=>fs,RfqRequestedSizeUnit:()=>Xr,RfqSide:()=>Eo,RfqStatus:()=>mn,RouterMergeCallError:()=>s8,RouterRedeemCallError:()=>i8,RouterSplitCallError:()=>o8,SearchError:()=>UA,SearchSort:()=>Wd,SessionKeyKnownScope:()=>yo,SetupGaslessWalletError:()=>Fme,SetupTradingApprovalsError:()=>xv,SignatureType:()=>Rr,SignerType:()=>LN,SigningError:()=>ce,SortDirection:()=>Bl,SplitPositionError:()=>Vd,SubscribeError:()=>XA,TeamOrdering:()=>$h,TimeoutError:()=>tt,TipSide:()=>Ul,TradeFilterType:()=>Ml,TraderLeaderboardSort:()=>Kl,TradingRestriction:()=>_C,TransactionFailedError:()=>en,TransferErc20Error:()=>lT,TransferPerpsCollateralError:()=>Qx,TransportError:()=>I,UnexpectedResponseError:()=>C,UpdatePerpsLeverageError:()=>Rx,UpdatePerpsMarginError:()=>_x,UserInputError:()=>E,UserPnlFidelity:()=>jl,UserPnlInterval:()=>Vl,WaitForComboFillError:()=>NA,WaitForOrderFillSettlementError:()=>dx,WaitForTransactionError:()=>l8,WalletType:()=>Se,WebSocketKnownCloseCode:()=>RC,WithdrawFromPerpsError:()=>Yx,accountActions:()=>WO,allActions:()=>WV,analyticsActions:()=>zO,authorizeSessionSignerCall:()=>jN,buildHmacSignature:()=>GV,combinatorialPrepareConditionCall:()=>pv,createPublicClient:()=>nj,createSecureClient:()=>qme,ctfMergePositionsCall:()=>KN,ctfRedeemPositionsCall:()=>YN,ctfSplitPositionCall:()=>GN,dataActions:()=>GO,decodeErc1155BalanceOfBatchResult:()=>Cf,decodeErc1155BalanceOfResult:()=>VN,decodeErc1155IsApprovedForAllResult:()=>HN,decodeErc20AllowanceResult:()=>FN,discoveryActions:()=>KO,encodeProxyCall:()=>XN,encodeSafeMultisendCall:()=>JN,erc1155ApprovalForAllCall:()=>kf,erc1155BalanceOfBatchCall:()=>If,erc1155BalanceOfCall:()=>$N,erc1155IsApprovedForAllCall:()=>qN,erc20AllowanceCall:()=>MN,erc20ApprovalCall:()=>vf,erc20TransferCall:()=>P0,expectTransactionHandle:()=>wn,forkEnvironmentConfig:()=>zV,makeErrorGuard:()=>B,perpsActions:()=>YO,perpsDepositCall:()=>zN,preproduction:()=>Cpe,production:()=>ZO,relayerApiKey:()=>Tpe,remoteBuilderSigning:()=>Ape,revokeSessionSignerCall:()=>WN,rewardsActions:()=>QO,rfqActions:()=>$V,routerMergeCall:()=>dv,routerRedeemCall:()=>xf,routerSplitCall:()=>uv,sessionKeyActions:()=>VV,subscriptionsActions:()=>XO,tradingActions:()=>jV,walletActions:()=>JO});function Ape(e){return new Spe(e)}function Tpe(e){return new Ppe(e)}function Epe(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 Rpe(e){return{listPositions:Wf.bind(null,e),listComboPositions:zf.bind(null,e),fetchPortfolioValue:Gf.bind(null,e),fetchTraderLeaderboardStanding:Mf.bind(null,e),fetchUserStats:Kf.bind(null,e),fetchUserPnl:Yf.bind(null,e),fetchUserVolume:Qf.bind(null,e),downloadAccountingSnapshot:Xf.bind(null,e),listActivity:Rf.bind(null,e),listComboActivity:_f.bind(null,e)}}function gs(e,t={}){return t===null||typeof t!="object"||Array.isArray(t)?t:{...t,user:t.user===void 0?e.account.wallet:t.user}}function WO(e){let t=Rpe(e);return e.isPublicClient()?t:{...t,listPositions:n=>Wf(e,gs(e,n)),listComboPositions:n=>zf(e,gs(e,n)),fetchPortfolioValue:n=>Gf(e,gs(e,n)),fetchTraderLeaderboardStanding:n=>Mf(e,gs(e,n)),fetchUserStats:n=>Kf(e,gs(e,n)),fetchUserPnl:n=>Yf(e,gs(e,n)),fetchUserVolume:n=>Qf(e,gs(e,n)),downloadAccountingSnapshot:n=>Xf(e,gs(e,n)),listActivity:n=>Rf(e,gs(e,n)),listComboActivity:n=>_f(e,gs(e,n)),listAccountTrades:Ef.bind(null,e),fetchNotifications:j0.bind(null,e),dropNotifications:z0.bind(null,e),fetchClosedOnlyMode:B0.bind(null,e)}}function zO(e){return{listBuilderTrades:Rv.bind(null,e),listBuilderLeaderboard:vk.bind(null,e),fetchBuilderVolume:xk.bind(null,e),listTraderLeaderboard:Tk.bind(null,e),listBiggestWinners:Ek.bind(null,e)}}function GO(e){return{fetchEventLiveVolume:bk.bind(null,e),fetchResolutions:gk.bind(null,e),fetchMidpoint:Iv.bind(null,e),fetchMidpoints:Nv.bind(null,e),fetchPrice:Lv.bind(null,e),fetchPrices:Uv.bind(null,e),fetchOrderBook:Hd.bind(null,e),fetchOrderBooks:Fv.bind(null,e),fetchSpread:Hv.bind(null,e),fetchSpreads:Vv.bind(null,e),fetchLastTradePrice:Wv.bind(null,e),fetchLastTradePrices:Gv.bind(null,e),listPriceHistory:Fk.bind(null,e),estimateMarketPrice:Jk.bind(null,e),fetchOpenInterest:Hk.bind(null,e),listMarketHolders:Bk.bind(null,e),listTrades:av.bind(null,e)}}function KO(e){return{listEvents:uk.bind(null,e),fetchEvent:pk.bind(null,e),fetchEventTags:hk.bind(null,e),listMarkets:Ff.bind(null,e),listComboMarkets:Ck.bind(null,e),fetchMarket:Ok.bind(null,e),fetchMarketTags:Dk.bind(null,e),listSeries:FA.bind(null,e),fetchSeries:HA.bind(null,e),listMarketClarifications:Rk.bind(null,e),listTags:ZA.bind(null,e),fetchTag:tT.bind(null,e),fetchRelatedTags:rT.bind(null,e),fetchRelatedTagResources:sT.bind(null,e),search:BA.bind(null,e),listSports:KA.bind(null,e),fetchSportsMarketTypes:QA.bind(null,e),listTeams:aT.bind(null,e),fetchPublicProfile:xA.bind(null,e),listComments:ok.bind(null,e),fetchCommentsById:ik.bind(null,e),listCommentsByUserAddress:lk.bind(null,e)}}function YO(e){let t={fetchPerpsBuilderStatus:vx.bind(null,e),fetchPerpsBook:n=>Bx(e,n),fetchPerpsFees:()=>Wx(e),fetchPerpsInstruments:n=>Nx(e,n),fetchPerpsTicker:n=>Lx(e,n),fetchPerpsTickers:n=>jf(e,n),listPerpsCandles:n=>Fx(e,n),listPerpsFundingHistory:n=>Hx(e,n),listPerpsTrades:n=>Vx(e,n)};return e.isSecureClient()?{...t,depositToPerps:n=>Zx(e,n),openPerpsSession:n=>Xx(e,n),revokePerpsCredentials:n=>Jx(e,n),transferPerpsCollateral:tA.bind(null,e),withdrawFromPerps:n=>eA(e,n)}:t}function _pe(e){return{listCurrentRewards:Yv.bind(null,e),listMarketRewards:Xv.bind(null,e)}}function QO(e){let t=_pe(e);return e.isPublicClient()?t:{...t,fetchOrderScoring:Y0.bind(null,e),fetchOrdersScoring:X0.bind(null,e),listUserEarningsForDay:Z0.bind(null,e),fetchTotalEarningsForUserForDay:tv.bind(null,e),listUserEarningsAndMarketsConfig:rv.bind(null,e),fetchRewardPercentages:sv.bind(null,e)}}function $V(e){return{openRfqSession(){return EA(e)},requestComboQuote(t){return _A(e,t)},acceptComboQuote(t){return CA(e,t)},waitForComboFill(t){return OA(e,t)}}}function VV(e){return{authorizeSessionKey:jA.bind(null,e),fetchSessionKeys:zd.bind(null,e),revokeSessionKey:zA.bind(null,e)}}function XO(e){return e.isSecureClient()?{subscribe(t){return Zf(e,t)}}:{subscribe(t){return Zf(e,t)}}}function jV(e){return{createMarketOrder:Hf.bind(null,e),placeMarketOrder:fx.bind(null,e),createLimitOrder:$f.bind(null,e),placeLimitOrder:bx.bind(null,e),postOrder:$d(e),postOrders:nx(e),waitForOrderFillSettlement:px.bind(null,e),cancelOrder:Vk.bind(null,e),cancelOrders:Wk.bind(null,e),cancelAll:Gk.bind(null,e),cancelMarketOrders:Yk.bind(null,e),listOpenOrders:F0.bind(null,e),fetchOrder:H0.bind(null,e)}}function Ipe(e){return{fetchTradingApprovalsState:Bf.bind(null,e)}}function JO(e){let t=Ipe(e);return e.isPublicClient()?t:{...t,fetchTradingApprovalsState:()=>Bf(e,{user:e.account.wallet}),setupTradingApprovals:Av.bind(null,e),approveErc20:Df.bind(null,e),approveErc1155ForAll:Uf.bind(null,e),transferErc20:cT.bind(null,e),splitPosition:pA.bind(null,e),mergePositions:gA.bind(null,e),redeemPositions:vA.bind(null,e),planCollateralReturn:ek.bind(null,e),executeCollateralReturnPlan:nk.bind(null,e)}}function WV(e){return e.isSecureClient()?{...WO(e),...zO(e),...GO(e),...KO(e),...YO(e),...QO(e),...$V(e),...VV(e),...XO(e),...jV(e),...JO(e)}:{...WO(e),...zO(e),...GO(e),...KO(e),...YO(e),...QO(e),...XO(e),...JO(e)}}function zV(e,t=ZO){return{...t,...e,walletDerivation:{...t.walletDerivation,...e.walletDerivation},contracts:{...t.contracts,...e.contracts},clob:{...Gd(t.clob,e.clob),market:eg(t.clob.market,e.clob?.market),user:eg(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:{...NV(t.combos,e.combos),builderGateway:Gd(t.combos.builderGateway,e.combos?.builderGateway),collateralReturn:Gd(t.combos.collateralReturn,e.combos?.collateralReturn)},perps:NV(t.perps,e.perps),realtime:eg(t.realtime,e.realtime),rtds:eg(t.rtds,e.rtds),sports:eg(t.sports,e.sports)}}function Gd(e,t){return{...e,...t,headers:eL(e.headers,t?.headers)}}function eg(e,t){return{...e,...t,headers:eL(e.headers,t?.headers)}}function NV(e,t){return{...e,...t,headers:eL(e.headers,t?.headers)}}function eL(e,t){if(!(e===void 0&&t===void 0))return{...e,...t}}async function GV(e,t,n,r,o){let s=`${t}${n}${r}`;o!==void 0&&(s+=o);let i=await globalThis.crypto.subtle.importKey("raw",Npe(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(s));return Lpe(Ope(a))}function Npe(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 Ope(e){let t=new Uint8Array(e),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function Lpe(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}function ng(e,t){let n;return{close:()=>(n===void 0&&(n=Promise.resolve(e.return()).then(()=>t())),n),[Symbol.asyncIterator](){return e[Symbol.asyncIterator]()}}}function OV(e,t,n){let r=pT(n.assetsIds,t.assetsIds),o=pT(t.assetsIds,n.assetsIds);r.length>0&&e(DV(r,n.customFeatureEnabled));let s=n.assetsIds[0];r.length===0&&t.customFeatureEnabled!==n.customFeatureEnabled&&s!==void 0&&e(DV([s],n.customFeatureEnabled)),o.length>0&&e(Mpe(o))}function LV(e,t,n){if(n.includeAllMarkets){!t.includeAllMarkets&&t.markets.length>0&&e(BV(t.markets));return}if(t.includeAllMarkets){n.markets.length>0&&e(UV(n.markets));return}let r=pT(n.markets,t.markets),o=pT(t.markets,n.markets);r.length>0&&e(UV(r)),o.length>0&&e(BV(o))}function Dpe(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 Upe(e){let t=!1,n=new Set;for(let{subscription:r}of e){if(KV(r)){t=!0;continue}for(let o of r.markets??[])n.add(o)}return{includeAllMarkets:t,markets:t?[]:Array.from(n)}}function Bpe(e){return{assets_ids:e.assetsIds,custom_feature_enabled:e.customFeatureEnabled,type:"market"}}function DV(e,t){return{assets_ids:e,custom_feature_enabled:t,operation:"subscribe"}}function Mpe(e){return{assets_ids:e,operation:"unsubscribe"}}function Fpe(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 UV(e){return{markets:e,operation:"subscribe"}}function BV(e){return{markets:e,operation:"unsubscribe"}}function qpe(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 Hpe(e){if(KV(e))return()=>!0;let t=new Set((e.markets??[]).map(n=>n.toLowerCase()));return n=>t.has(n.payload.market.toLowerCase())}function KV(e){return(e.markets?.length??0)===0}function pT(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}function jpe(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(Wpe(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 MV(e,t){return Array.from(t).filter(n=>!e.has(n))}function FV(e,t){return Array.from(e).filter(n=>!t.has(n))}function Wpe(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:fe(!1,`Unknown Perps topic: ${String(e)}`)}}function zpe(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:fe(!1,`Unknown Perps topic: ${String(e)}`)}}function Gpe(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 Kpe(e,t){return Math.random()*(e===4003?1e4:Math.min(1e3*2**t,3e4))}function Qpe(e){return new Promise((t,n)=>{let r=yn(()=>{n(new I("Realtime subscription was not accepted within 30 seconds."))},3e4);e.then(()=>{clearTimeout(r),t()},o=>{clearTimeout(r),n(o)})})}function Xpe(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 Zpe(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 nme(e,t){return{...t,quote:n=>e.quote(t,n)}}function rme(e,t){let n=t.rfqId,r=t.quoteId;return{...t,confirm:()=>e.respondToConfirmation(n,r,ds.Confirm),decline:()=>e.respondToConfirmation(n,r,ds.Decline)}}function ome(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function sme(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function ime(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function ame(e,t){let n=rc(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 lme(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 cme(e,t,n){let r=rc(e);return{maker_address:r.maker,quote_id:n,rfq_id:t,signer_address:r.signer,type:"RFQ_QUOTE_CANCEL"}}function ume(e,t,n){return{decision:n,quote_id:t,rfq_id:e,type:"RFQ_CONFIRMATION_RESPONSE"}}function pme(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}async function mme(e){let t=rc(e.account),n=wO({chainId:e.chainId,exchange:e.exchange}),r={builder:qV,maker:t.maker,makerAmount:b5(e.orderSide,e.orderPrice,e.size),metadata:qV,salt:hme().toString(),side:ax(e.orderSide),signatureType:t.signatureType,signer:t.signer,takerAmount:w5(e.orderSide,e.orderPrice,e.size),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:e.tokenId},o;try{o=await e.signer.signTypedData(sx({domain:n,order:r}))}catch(s){throw ce.fromError(s,"Could not sign the RFQ quote order.")}return{...r,signature:ix({domain:n,order:r,signature:o})}}function hme(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)}function gme(e){return M(e,fme)}async function yme(e){let t=e.response.price,n=e.response.size===void 0?kme(e.request.requestedSize,t):e.response.size,r=await mme({account:e.account,chainId:e.chainId,exchange:e.exchange,orderPrice:wme(e.request,e.response.source,t),orderSide:vme(e.response.source),signer:e.signer,size:n,tokenId:bme(e.request,e.response.source)});return{price:t,signedOrder:r,size:n}}function bme(e,t){return e.direction===Nn.Buy?t==="collateral"?e.noPositionId:e.yesPositionId:t==="collateral"?e.yesPositionId:e.noPositionId}function wme(e,t,n){return e.direction===Nn.Buy&&t==="collateral"||e.direction===Nn.Sell&&t==="inventory"?1000000n-n:n}function vme(e){return e==="collateral"?Ue.BUY:Ue.SELL}function kme(e,t){let n=XV(e.value);return e.unit===Xr.Shares?n:n*1000000n/t}function XV(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 dT(e){return`ACK_RFQ_QUOTE:${e}`}function VO(e,t){return`ACK_RFQ_QUOTE_CANCEL:${e}:${t}`}function jO(e,t){return`ACK_RFQ_CONFIRMATION_RESPONSE:${e}:${t}`}function Pme(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}function Eme(e,t){return Array.from(t).flatMap(([n,r])=>e.has(n)?[]:[r])}function Rme(e,t){return Array.from(e).flatMap(([n,r])=>t.has(n)?[]:[r])}function _me(e){let t=new Map;for(let{subscription:n}of e)for(let r of Nme(n))t.has(r.key)||t.set(r.key,r);return t}function Ime(e){return{action:"subscribe",subscriptions:e.map(({topic:t,type:n})=>({topic:t,type:n}))}}function Cme(e){return{action:"unsubscribe",subscriptions:e.map(({topic:t,type:n})=>({topic:t,type:n}))}}function Nme(e){switch(e.topic){case"comments":return(e.types??["comment_created"]).map(t=>tg("comments",t));case"prices.crypto.binance":return[tg("crypto_prices","update")];case"prices.crypto.chainlink":return[tg("crypto_prices_chainlink","update")];case"prices.crypto.chainlink.twap":return[tg(Ome(e.windowSeconds),"update")];case"prices.equity.pyth":return[tg("equity_prices","update")];default:fe(!1,`Unknown RTDS topic: ${String(e)}`)}}function Ome(e){switch(e){case 30:return"crypto_prices_twap_thirty";case 60:return"crypto_prices_twap_sixty";default:fe(!1,`Unknown TWAP window: ${String(e)}`)}}function tg(e,t){return{key:`${e}:${t}`,topic:e,type:t}}function Lme(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:fe(!1,`Unknown RTDS topic: ${String(e)}`)}}function nj(e={}){return new tj({environment:e.environment??ZO,apiKey:e.apiKey,onRateLimitUpdate:e.onRateLimitUpdate}).extend(WV)}async function qme(e){let t=nj({environment:e.environment,apiKey:e.apiKey,onRateLimitUpdate:e.onRateLimitUpdate}),n=await Hme(t,e),r=await t.beginAuthentication({wallet:n,credentials:e.credentials,nonce:e.nonce},e.signer).then(c8(e.signer));if(r.account.walletType===Se.EOA||await Of(r,{wallet:r.account.wallet,type:r.account.walletType}))return r;if(r.account.walletType===Se.DEPOSIT_WALLET)return await $me(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 Hme(e,t){if(t.wallet!==void 0)return t.wallet;let n=Be(await t.signer.getAddress()),r=L0(n,e.environment.walletDerivation);return await Of(e,{wallet:r,type:Se.DEPOSIT_WALLET})?r:Pf(n,e.environment.walletDerivation)}async function $me(e){let t=Pf(e.account.signer,e.environment.walletDerivation);if(!zt(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 mv(e)).wait()}var Lr,xpe,Spe,Ppe,ZO,Cpe,rg,YV,$pe,Vpe,QV,Ype,Jpe,eme,tme,dme,qV,HV,fme,xme,Ame,Tme,Sme,JV,ZV,ej,Dme,Ume,tj,Bme,Mme,Fme,oj=L(()=>{"use strict";uT();uT();e0();e0();pf();pf();UC();f0();s0();s0();iN();Lr=require("zod");Al();fw();Xw();dN();y0();xpe=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)});Spe=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 ce.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 xpe.parse(await t.json())}},Ppe=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})}};ZO={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};Cpe=zV({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"}});rg=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)}};YV=class{#e;#t;#r;#s=new mi({heartbeat:new TO});#n=new la;#o=new rg({deriveServerState:Dpe});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#o.add(e,{matches:qpe(e)});return await this.#i(n,t),ng(n.subscriber.queue,()=>this.#a(n))}async#i(e,t){let{before:n,after:r}=t;try{(await this.#l()).reusedOpenSocket&&OV(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}OV(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=BH.safeParse(n);r.success&&this.#o.dispatch(r.data)}}#d(){this.#o.hasActiveSubscriptions()&&this.#h()}#m(){}#y(){this.#s.send(Bpe(this.#o.serverState()))}#h(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}},$pe=class{#e;#t;#r;#s;#n=new mi({heartbeat:new TO});#o=new la;#i=new rg({deriveServerState:Upe});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:Hpe(e)});return await this.#a(n,t),ng(n.subscriber.queue,()=>this.#u(n))}async#a(e,t){let{before:n,after:r}=t;try{(await this.#c()).reusedOpenSocket&&LV(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}LV(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=MH.safeParse(n);r.success&&this.#i.dispatch(r.data)}}#m(){this.#i.hasActiveSubscriptions()&&this.#f()}#y(){}#h(e){this.#n.send(Fpe(this.#i.serverState(),e))}#f(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()})}},Vpe=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 I("Perps session manager has been shut down."));let o=new G5({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 I("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)}},QV=class{#e;#t;#r;#s=1;#n=new mi({heartbeat:new SO});#o=new la;#i=new rg({deriveServerState:jpe});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#i.add(e,{matches:zpe(e)});return await this.#a(n,t),ng(n.subscriber.queue,()=>this.#u(n))}async#a(e,t){try{(await this.#c()).reusedOpenSocket&&(this.#h(MV(t.before,t.after)),this.#f(FV(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(MV(t,n)),this.#f(FV(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=qH.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()})}};Ype=class{#e;#t=new la;#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(),Qpe(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 I("Realtime subscription closed.")),this.#i&&this.#f("unsubscribe",[n]),this.#r.size===0&&(this.#o=yn(()=>{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),I.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=yn(()=>{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=Xpe(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 Qr("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=>Kpe(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=yn(()=>{this.close()},1e3))}async close(){if(this.#a)return;this.#a=!0,this.#t.stop(),clearTimeout(this.#o);let e=new I("Realtime connection closed.");this.#v();for(let t of this.#r.values())t.reject(e);this.#r.clear(),await this.#e.close()}};Jpe=class{#e;#t=new mi({heartbeat:new M5,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 Qr("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}},Cl.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=Zpe(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"?Cl.Subscribed:Cl.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=yn(()=>{i.timer=yn(()=>{this.#r.delete(r),s(new I("Realtime acknowledgement timed out after 10 seconds."))},1e4),this.#o=Date.now();try{if(!this.#t.send({...e,rid:r}))throw new I("Realtime connection is not open.")}catch(a){clearTimeout(i.timer),this.#r.delete(r),s(I.fromError(a))}},Math.max(0,110-(Date.now()-this.#o)))})}#u(e){let t=jH.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===Cl.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=WH.safeParse(e);if(!n.success)return;let r=KH(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 I("Realtime connection closed.")),await this.#t.close()}};eme=class{#e;#t=new Set;#r=new Set;constructor(e){this.#e=e}async subscribe(e){let t=[...new Map(Gpe(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 Ype(new Jpe(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()))}},tme=class{#e;constructor(e){this.#e=new eme(e)}async subscribe(e){return this.#e.subscribe(e)}async close(){await this.#e.close()}};dme=class{#e=new Map;#t;constructor(e){this.#t=e}waitFor(e,t){let n=pme(),r,o=yn(()=>{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()}};qV="0x0000000000000000000000000000000000000000000000000000000000000000";HV=H.transform(e=>XV(e)).refine(e=>e<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),fme=Lr.z.strictObject({price:HV.refine(e=>e<1000000n,{message:"Price must be less than 1."}),size:HV.optional(),source:Lr.z.enum(["collateral","inventory"]).default("collateral")});xme=3e4,Ame=3e4,Tme=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 I("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 Sme({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 I("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)}},Sme=class{#e;#t;#r;#s;#n;#o;#i;#a;#u=new mi;#l=Bd({objectMode:!0});#c=new dme(Ame);#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=Pme();this.#d=e;let t=yn(()=>{e.reject(new I("RFQ quoter authentication timed out."))},xme);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 I("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 I("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(ame(this.#e,this.#r))}#x(e){if(this.#p!==void 0)return;let t=A4.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(nme(this,n));return;case"quote_ack":this.#c.resolve(dT(n.rfqId),ome(n));return;case"quote_cancel_ack":this.#c.resolve(VO(n.rfqId,n.quoteId),sme(n));return;case"confirmation_request":this.#l.push(rme(this,n));return;case"confirmation_ack":this.#c.resolve(jO(n.rfqId,n.quoteId),ime(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 I(`RFQ quoter authentication failed: ${e.error}`))}#v(e){this.#h(new Qr("RFQ quoter connection lost.",e))}#T(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new I("Uncorrelated RFQ quoter error."));return}this.#c.reject(dT(e.rfqId),new ic(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 I("Uncorrelated RFQ quoter error."));return}this.#c.reject(VO(e.rfqId,e.quoteId),new ac(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 I("Uncorrelated RFQ quoter error."));return}this.#c.reject(jO(e.rfqId,e.quoteId),new lc(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}))}}async quote(e,t){let n=gme(t),r=await yme({account:this.#e,chainId:this.#t,exchange:this.#s,request:e,response:n,signer:this.#i}),o=this.#c.waitFor(dT(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#m(lme(e,r)),await o}catch(s){throw this.#c.remove(dT(e.rfqId),o),s}}async cancelQuote(e){let t=VO(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(cme(this.#e,e.rfqId,e.quoteId)),await n}catch(r){throw this.#c.remove(t,n),r}}async respondToConfirmation(e,t,n){let r=jO(e,t),o=this.#c.waitFor(r,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#m(ume(e,t,n)),await o}catch(s){throw this.#c.remove(r,o),s}}};JV=class{#e;#t;#r;#s=new mi({heartbeat:new U5});#n=new la;#o=new rg({deriveServerState:_me});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#o.add(e,{matches:Lme(e)});return await this.#i(n,t),ng(n.subscriber.queue,()=>this.#a(n))}async#i(e,t){try{if((await this.#l()).reusedOpenSocket){let{before:n,after:r}=t,o=Eme(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=Rme(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=t3.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(Ime(e))}#f(e){e.length!==0&&this.#s.send(Cme(e))}#g(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}};ZV=class{#e;#t;#r;#s=new mi({heartbeat:new B5});#n=new la;#o=new rg;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),ng(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=n3.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()})}},ej=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)}},Dme=Lr.z.object({key:is,passphrase:Lr.z.string(),secret:Lr.z.string()}),Ume=Lr.z.object({wallet:J,credentials:Dme.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}),tj=class extends ej{constructor(e){super({apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,data:new kn({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new kn({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new kn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:t=>this.resolveClobHeaders(t)}),relayer:new kn({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:t=>this.resolveRelayerHeaders(t)}),rfq:new kn({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new kn({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new ON({url:e.environment.rpc}),webSockets:{clobMarket:new YV({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new ZV({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new JV({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new QV({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=M(e,Ume);return Promise.resolve(async function*(){let r=Math.floor(Date.now()/1e3),o=n?.nonce??0,s=Be(yield ZN()),i=Be(n.wallet),a=F6(this.environment,s,i);if(n.credentials!==void 0){let u=this.#e(n.credentials,a,t);try{if((await Sv(u)).includes(n.credentials.key))return u}catch(d){if(!(d instanceof O)||d.status!==401)throw d}}let l=yield{kind:"signAuthMessage",payload:Epe({address:s,chainId:this.environment.chainId,nonce:o,timestamp:r})},c=await Tv(this,{address:s,nonce:o,signature:ss(l),timestamp:r});return this.#e(c,a,t)}.call(this))}#e(e,t,n){let r=new Bme({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}},Bme=class extends ej{#e=!1;get context(){return fe(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=!0}constructor(e){let t=new tme({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 kn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:n=>this.resolveClobHeaders(n)}),relayer:new kn({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:n=>this.resolveRelayerHeaders(n)}),rpc:new ON({url:e.environment.rpc}),gamma:new kn({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new kn({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new kn({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new kn({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new kn({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 kn({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:n=>this.resolveRelayerHeaders(n),root:e.environment.combos.collateralReturn.rest}),builderGateway:new kn({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 YV({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new $pe({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new Tme({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 ZV({headers:e.environment.sports.headers,url:e.environment.sports.ws}),realtime:t,rtds:new JV({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new QV({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new Vpe({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 Pv(this)}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,t,n]).then(()=>{})}let i=new tj({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 GV(this.credentials.secret,t,e.method,e.path,e.body),POLY_TIMESTAMP:`${t}`}}catch(t){throw ce.fromError(t,"Could not sign the L2-authenticated request")}}};Mme=B(vt,$,O,ce,tt,en,I,C,E),Fme=B(E)});var sj={};fr(sj,{AcceptComboQuoteError:()=>IA,ApproveErc1155ForAllError:()=>vv,ApproveErc20Error:()=>wv,ApprovePerpsBuilderFeeError:()=>kx,ArmPerpsAutoCancelError:()=>Ex,AuthorizeSessionKeyError:()=>VA,BiggestWinnerKind:()=>Yl,BuilderVolumeInterval:()=>Gl,CancelAllError:()=>zk,CancelMarketOrdersError:()=>Kk,CancelOrderError:()=>$k,CancelOrdersError:()=>jk,CollateralReturnKnownOperationKind:()=>Dd,ComboAcceptFailureReason:()=>Ro,ComboActivityType:()=>Wl,ComboPositionSortBy:()=>$l,ComboPositionStatus:()=>ii,ComboQuoteUnavailableReason:()=>ci,CreateApiKeyError:()=>S8,CreateBuilderApiKeyError:()=>I8,CreateLimitOrderError:()=>gx,CreateMarketOrderError:()=>mx,CreateOrDeriveApiKeyError:()=>E8,DeleteApiKeyError:()=>_8,DeployDepositWalletError:()=>p8,DepositToPerpsError:()=>Kx,DeriveApiKeyError:()=>P8,DownloadAccountingSnapshotError:()=>lA,DropNotificationsError:()=>W0,EstimateMarketPriceError:()=>Xk,ExecuteCollateralReturnPlanError:()=>tk,FetchApiKeysError:()=>R8,FetchBalanceAllowanceError:()=>j6,FetchBuilderApiKeysError:()=>N8,FetchBuilderFeeRatesError:()=>V8,FetchBuilderVolumeError:()=>kk,FetchClosedOnlyModeError:()=>U0,FetchCommentsByIdError:()=>sk,FetchEventError:()=>dk,FetchEventLiveVolumeError:()=>yk,FetchEventTagsError:()=>mk,FetchExecuteParamsError:()=>u8,FetchLastTradePriceError:()=>jv,FetchLastTradePricesError:()=>zv,FetchMarketError:()=>Nk,FetchMarketInfoError:()=>$8,FetchMarketTagsError:()=>Lk,FetchMidpointError:()=>_v,FetchMidpointsError:()=>Cv,FetchNegRiskError:()=>F8,FetchNotificationsError:()=>V0,FetchOpenInterestError:()=>qk,FetchOrderBookError:()=>Bv,FetchOrderBooksError:()=>Mv,FetchOrderError:()=>q0,FetchOrderScoringError:()=>K0,FetchOrdersScoringError:()=>Q0,FetchPerpsBookError:()=>Ux,FetchPerpsBuilderApprovalsError:()=>Tx,FetchPerpsBuilderEarningsSummaryError:()=>Px,FetchPerpsBuilderStatusError:()=>wx,FetchPerpsFeesError:()=>jx,FetchPerpsInstrumentsError:()=>Cx,FetchPerpsTickerError:()=>Ox,FetchPerpsTickersError:()=>Dx,FetchPortfolioValueError:()=>oA,FetchPriceError:()=>Ov,FetchPricesError:()=>Dv,FetchPublicProfileError:()=>kA,FetchRelatedTagResourcesError:()=>oT,FetchRelatedTagsError:()=>nT,FetchResolutionsError:()=>fk,FetchRewardPercentagesError:()=>ov,FetchRfqStatusError:()=>LA,FetchSeriesError:()=>qA,FetchSessionKeysError:()=>$A,FetchSportsMarketTypesError:()=>YA,FetchSpreadError:()=>qv,FetchSpreadsError:()=>$v,FetchTagError:()=>eT,FetchTickSizeError:()=>B8,FetchTotalEarningsForUserForDayError:()=>ev,FetchTraderLeaderboardStandingError:()=>Sk,FetchTradingApprovalsStateError:()=>kv,FetchUserPnlError:()=>iA,FetchUserStatsError:()=>sA,FetchUserVolumeError:()=>aA,GaslessTransactionHandle:()=>Lf,GaslessTransactionMetadataSchema:()=>ur,IsWalletDeployedError:()=>d8,LeaderboardWindow:()=>zl,ListAccountTradesError:()=>$0,ListActivityError:()=>lv,ListBiggestWinnersError:()=>Pk,ListBuilderLeaderboardError:()=>wk,ListBuilderTradesError:()=>Ev,ListComboActivityError:()=>cv,ListComboMarketsError:()=>Ik,ListComboPositionsError:()=>rA,ListCommentsByUserAddressError:()=>ak,ListCommentsError:()=>rk,ListCurrentRewardsError:()=>Kv,ListEventsError:()=>ck,ListMarketClarificationsError:()=>Y8,ListMarketHoldersError:()=>Uk,ListMarketRewardsError:()=>Qv,ListMarketsError:()=>_k,ListOpenOrdersError:()=>M0,ListPerpsBuilderEarningsError:()=>Sx,ListPerpsCandlesError:()=>Mx,ListPerpsFundingHistoryError:()=>qx,ListPerpsTradesError:()=>$x,ListPositionsError:()=>nA,ListPriceHistoryError:()=>Mk,ListSeriesError:()=>MA,ListSportsError:()=>GA,ListTagsError:()=>JA,ListTeamsError:()=>iT,ListTraderLeaderboardError:()=>Ak,ListTradesError:()=>iv,ListUserEarningsAndMarketsConfigError:()=>nv,ListUserEarningsForDayError:()=>J0,MergeComboPositionError:()=>gV,MergeMarketPositionError:()=>hV,MergePositionsError:()=>jd,OpenPerpsSessionError:()=>zx,OpenRfqSessionError:()=>PA,PlaceLimitOrderError:()=>yx,PlaceMarketOrderError:()=>hx,PlanCollateralReturnError:()=>Zv,PositionFilterType:()=>Hl,PositionSortBy:()=>ql,PositionStatus:()=>ai,PostOrderError:()=>ex,PostOrdersError:()=>tx,PrepareCollateralReturnExecutionError:()=>W8,PrepareErc1155ApprovalForAllError:()=>v8,PrepareErc20ApprovalError:()=>w8,PrepareErc20TransferError:()=>CV,PrepareGaslessTransactionError:()=>m8,PrepareLimitOrderError:()=>kO,PrepareLimitOrderPostingError:()=>_5,PrepareMarketOrderError:()=>vO,PrepareMarketOrderPostingError:()=>E5,PrepareMergeComboPositionError:()=>mV,PrepareMergeMarketPositionError:()=>dV,PrepareMergePositionsError:()=>mA,PreparePerpsDepositError:()=>J5,PrepareRedeemComboPositionError:()=>xV,PrepareRedeemMarketPositionsError:()=>vV,PrepareRedeemPositionsError:()=>yA,PrepareSplitComboPositionError:()=>sV,PrepareSplitMarketPositionError:()=>rV,PrepareSplitPositionError:()=>cA,PrepareTradingApprovalsError:()=>k8,PriceHistoryInterval:()=>Po,RedeemPositionsError:()=>wA,RequestComboQuoteError:()=>RA,ResolutionMarketType:()=>Xl,ResolutionReporter:()=>Zl,ResolutionSource:()=>Jl,ResolutionStatus:()=>Ql,ResolveConditionByTokenError:()=>H8,RevokeBuilderApiKeyError:()=>L8,RevokePerpsBuilderFeeError:()=>Ix,RevokePerpsCredentialsError:()=>Gx,RevokeSessionKeyError:()=>WA,RfqCancelQuoteError:()=>TA,RfqCancelQuoteRejectedError:()=>ac,RfqConfirmationDecision:()=>ds,RfqConfirmationError:()=>SA,RfqConfirmationRejectedError:()=>lc,RfqDirection:()=>Nn,RfqExecutionStatus:()=>ps,RfqKnownErrorCode:()=>Cr,RfqQuoteError:()=>AA,RfqQuoteRejectedError:()=>ic,RfqRejectionCode:()=>li,RfqRequestRejectedError:()=>fs,RfqRequestedSizeUnit:()=>Xr,RfqSide:()=>Eo,RfqStatus:()=>mn,SearchError:()=>UA,SearchSort:()=>Wd,SessionKeyKnownScope:()=>yo,SetupTradingApprovalsError:()=>xv,SortDirection:()=>Bl,SplitComboPositionError:()=>lV,SplitMarketPositionError:()=>iV,SplitPositionError:()=>Vd,SubscribeError:()=>XA,TipSide:()=>Ul,TradeFilterType:()=>Ml,TraderLeaderboardSort:()=>Kl,TransferErc20Error:()=>lT,TransferPerpsCollateralError:()=>Qx,UpdateBalanceAllowanceError:()=>W6,UpdatePerpsLeverageError:()=>Rx,UpdatePerpsMarginError:()=>_x,UserPnlFidelity:()=>jl,UserPnlInterval:()=>Vl,WaitForComboFillError:()=>NA,WaitForGaslessTransactionError:()=>b8,WaitForOrderFillSettlementError:()=>dx,WithdrawFromPerpsError:()=>Yx,acceptComboQuote:()=>CA,approveErc1155ForAll:()=>Uf,approveErc20:()=>Df,authorizeSessionKey:()=>jA,buildDepositWalletExecuteRequest:()=>qd,buildProxyWalletExecuteRequest:()=>hv,buildSafeWalletExecuteRequest:()=>yv,cancelAll:()=>Gk,cancelMarketOrders:()=>Yk,cancelOrder:()=>Vk,cancelOrders:()=>Wk,createApiKey:()=>oO,createBuilderApiKey:()=>C8,createLimitOrder:()=>$f,createMarketOrder:()=>Hf,createOrDeriveApiKey:()=>Tv,deleteApiKey:()=>Pv,deployDepositWallet:()=>mv,depositToPerps:()=>Zx,deriveApiKey:()=>sO,downloadAccountingSnapshot:()=>Xf,dropNotifications:()=>z0,estimateMarketPrice:()=>Jk,executeCollateralReturnPlan:()=>nk,extractOnChainNonceFromSubmitError:()=>fv,fetchApiKeys:()=>Sv,fetchBalanceAllowance:()=>G0,fetchBuilderApiKeys:()=>O8,fetchBuilderFeeRates:()=>lO,fetchBuilderVolume:()=>xk,fetchClosedOnlyMode:()=>B0,fetchCommentsById:()=>ik,fetchEvent:()=>pk,fetchEventLiveVolume:()=>bk,fetchEventTags:()=>hk,fetchExecuteParams:()=>Nf,fetchLastTradePrice:()=>Wv,fetchLastTradePrices:()=>Gv,fetchMarket:()=>Ok,fetchMarketInfo:()=>aO,fetchMarketTags:()=>Dk,fetchMidpoint:()=>Iv,fetchMidpoints:()=>Nv,fetchNegRisk:()=>q8,fetchNotifications:()=>j0,fetchOpenInterest:()=>Hk,fetchOrder:()=>H0,fetchOrderBook:()=>Hd,fetchOrderBooks:()=>Fv,fetchOrderScoring:()=>Y0,fetchOrdersScoring:()=>X0,fetchPerpsBook:()=>Bx,fetchPerpsBuilderStatus:()=>vx,fetchPerpsFees:()=>Wx,fetchPerpsInstruments:()=>Nx,fetchPerpsTicker:()=>Lx,fetchPerpsTickers:()=>jf,fetchPortfolioValue:()=>Gf,fetchPrice:()=>Lv,fetchPrices:()=>Uv,fetchPublicProfile:()=>xA,fetchRelatedTagResources:()=>sT,fetchRelatedTags:()=>rT,fetchResolutions:()=>gk,fetchRewardPercentages:()=>sv,fetchRfqStatus:()=>DA,fetchSeries:()=>HA,fetchSessionKeys:()=>zd,fetchSportsMarketTypes:()=>QA,fetchSpread:()=>Hv,fetchSpreads:()=>Vv,fetchTag:()=>tT,fetchTickSize:()=>M8,fetchTotalEarningsForUserForDay:()=>tv,fetchTraderLeaderboardStanding:()=>Mf,fetchTradingApprovalsState:()=>Bf,fetchTransaction:()=>eO,fetchUserPnl:()=>Yf,fetchUserStats:()=>Kf,fetchUserVolume:()=>Qf,isRetryableGaslessSubmitError:()=>bv,isWalletDeployed:()=>Of,listAccountTrades:()=>Ef,listActivity:()=>Rf,listBiggestWinners:()=>Ek,listBuilderLeaderboard:()=>vk,listBuilderTrades:()=>Rv,listComboActivity:()=>_f,listComboMarkets:()=>Ck,listComboPositions:()=>zf,listComments:()=>ok,listCommentsByUserAddress:()=>lk,listCurrentRewards:()=>Yv,listEvents:()=>uk,listMarketClarifications:()=>Rk,listMarketHolders:()=>Bk,listMarketRewards:()=>Xv,listMarkets:()=>Ff,listOpenOrders:()=>F0,listPerpsCandles:()=>Fx,listPerpsFundingHistory:()=>Hx,listPerpsTrades:()=>Vx,listPositions:()=>Wf,listPriceHistory:()=>Fk,listSeries:()=>FA,listSports:()=>KA,listTags:()=>ZA,listTeams:()=>aT,listTraderLeaderboard:()=>Tk,listTrades:()=>av,listUserEarningsAndMarketsConfig:()=>rv,listUserEarningsForDay:()=>Z0,mergeComboPosition:()=>yV,mergeMarketPosition:()=>fV,mergePositions:()=>gA,openPerpsSession:()=>Xx,openRfqSession:()=>EA,placeLimitOrder:()=>bx,placeMarketOrder:()=>fx,planCollateralReturn:()=>ek,postOrder:()=>$d,postOrders:()=>nx,prepareCollateralReturnExecution:()=>cO,prepareErc1155ApprovalForAll:()=>nO,prepareErc20Approval:()=>tO,prepareErc20Transfer:()=>$O,prepareGaslessTransaction:()=>Or,prepareLimitOrder:()=>ux,prepareLimitOrderPosting:()=>I5,prepareMarketOrder:()=>cx,prepareMarketOrderPosting:()=>R5,prepareMergeComboPosition:()=>fA,prepareMergeMarketPosition:()=>hA,prepareMergePositions:()=>DO,preparePerpsDeposit:()=>OO,prepareRedeemComboPosition:()=>AV,prepareRedeemMarketPositions:()=>UO,prepareRedeemPosition:()=>bA,prepareRedeemPositions:()=>BO,prepareSplitComboPosition:()=>dA,prepareSplitMarketPosition:()=>uA,prepareSplitPosition:()=>LO,prepareTradingApprovals:()=>rO,redeemPositions:()=>vA,requestComboQuote:()=>_A,resignDepositWalletExecuteRequest:()=>gv,resolveConditionByToken:()=>iO,resolveEstimatedMarketPrice:()=>hO,resolveMarketPriceFromOrderBook:()=>Zk,revokeBuilderApiKey:()=>D8,revokePerpsCredentials:()=>Jx,revokeSessionKey:()=>zA,search:()=>BA,setupTradingApprovals:()=>Av,signOrder:()=>lx,splitComboPosition:()=>cV,splitMarketPosition:()=>aV,splitPosition:()=>pA,subscribe:()=>Zf,transferErc20:()=>cT,transferPerpsCollateral:()=>tA,updateBalanceAllowance:()=>UN,waitForComboFill:()=>OA,waitForOrderFillSettlement:()=>px,withdrawFromPerps:()=>eA});var ij=L(()=>{"use strict";uT()});var yye={};fr(yye,{AI_AGENT_TOOL_NAMES:()=>rS,AbortError:()=>Ni,AgentCore:()=>dS,ApproveTokenTool:()=>Kp,BRIDGE_NON_EVM_CHAIN_FAMILY:()=>Ya,BRIDGE_STATUS_POLL_MS:()=>EY,BRIDGE_SUPPORT_URL:()=>RY,BUILDER_CODE:()=>IP,BaseNftAiTool:()=>ws,BaseSwapProvider:()=>Aa,BaseTool:()=>K,BaseWalletActionTool:()=>to,BuyTokenTool:()=>Yp,CachedResource:()=>xs,ChatHistory:()=>Jp,CoinpoolConfigApi:()=>ig,DEFAULT_CHAIN:()=>er,DEFAULT_PROVIDER:()=>gi,DEFAULT_RPC_BY_CHAIN:()=>Fr,DEFILLAMA_EXTRA_SIGNALS:()=>Lo,DEFILLAMA_POOL_CHAIN_HEXES:()=>Mp,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION:()=>hr,DELAYED_ORDER:()=>Ny,DEPOSIT_REFERENCE_USD:()=>oL,DEPOSIT_STABLE_SYMBOLS:()=>Hm,DebridgeProvider:()=>Sp,DefiLlamaEstimatePoolYieldTool:()=>jp,DefiLlamaPoolByAddressTool:()=>Vp,DefiLlamaPoolCandidateResolver:()=>Wp,DefiLlamaPoolDetailTool:()=>$p,DefiLlamaPoolSearchTool:()=>Hp,DefiLlamaPoolService:()=>Jn,DefiLlamaTopPoolsTool:()=>qp,ERC1967_INIT_CODE:()=>Ds,EstimatePoolYieldTool:()=>Ip,GAMES_TAG_ID:()=>BP,GeminiProvider:()=>jt,GeminiSearchAiTool:()=>hp,HEX_TO_PANTOGRAPH:()=>nD,HIDE_FROM_NEW_TAG_ID:()=>MP,KeyringSettingApi:()=>cg,KnowledgeBase:()=>em,LendingMarketDetailTool:()=>Iu,LendingMarketsTool:()=>_u,LendingReadService:()=>Eu,LendingService:()=>io,LendingSupplyService:()=>Ru,MARKET_ORDER:()=>Vm,MARKET_STREAM:()=>jm,MULTICALL3_ADDRESS:()=>xt,ManageLiquidityRedirectTool:()=>bc,MoralisService:()=>De,NATIVE_GAS_LIMIT:()=>CW,NATIVE_TOKEN_PLACEHOLDER:()=>NP,NFC_AGENT_TOOL_NAMES:()=>nS,NFC_AMAZON_DEFAULT_DOMAIN:()=>bL,NFC_AMAZON_DOMAINS:()=>yL,NFTContractInfoTool:()=>cp,NFTMetadataTool:()=>up,NFT_AGENT_TOOL_NAMES:()=>tS,NfcBuyTool:()=>mp,NfcInfoTool:()=>pp,NoFormTool:()=>yg,ONBOARDING_STEP:()=>on,ONBOARDING_TRACKING:()=>Cy,ORDER_INPUT_ERROR:()=>Us,OpenAddLiquidityFormTool:()=>fc,OpenSupplyFormTool:()=>Nu,PERPS_DEPOSIT_CONTRACT:()=>LP,POLYGON_CHAIN_ID:()=>qm,POLYGON_HEX_CHAIN_ID:()=>Hi,POLYMARKET_API:()=>Fi,POLYMARKET_LIVE_DATA_WS:()=>OP,POLYMARKET_WEB_URL:()=>qi,POOL_UNISWAP_AGENT_TOOL_NAMES:()=>sS,POSITION_DUST_SHARES:()=>qP,PREDICTION_ACTIVITY_TYPES:()=>FP,PREDICTION_AGENT_TOOL_NAMES:()=>ZT,PREDICTION_CATEGORIES:()=>$i,PREDICTION_SORTS:()=>$m,PUSD_ADDRESS:()=>Ls,PUSD_DECIMALS:()=>zo,PantographService:()=>Ft,PolymarketApiError:()=>Ys,PolymarketOnboardingError:()=>hi,PolymarketRedeemError:()=>ma,PolymarketService:()=>Ye,PolymarketTradeError:()=>pa,PolymarketWithdrawError:()=>Io,PoolByAddressTool:()=>_p,PoolDetailTool:()=>Ep,PoolFallbackAiTool:()=>fp,PoolPriceRangesTool:()=>yc,PoolSearchTool:()=>Rp,PoolService:()=>Et,PoolSwapRouter:()=>kp,PredictionActivityTool:()=>np,PredictionDepositTool:()=>op,PredictionMarketDetailTool:()=>ep,PredictionMarketsTool:()=>Jd,PredictionPortfolioTool:()=>tp,PredictionSetupTool:()=>rp,PredictionTradeTool:()=>sp,PredictionWithdrawTool:()=>ip,PreviewAddLiquidityTool:()=>gc,PublicClient:()=>qa,REDEEM:()=>Qa,RELAYER_DEPLOY_POLL:()=>Iy,RELAYER_SUBMIT_PATH:()=>_y,RelayProvider:()=>wp,Router:()=>tm,SUPPLIABLE_TYPES:()=>xP,SUPPORTED_CHAINS:()=>eu,SUPPORTED_CHAINS_LABEL:()=>nu,SWAP_PROVIDER_CONFIG:()=>Tp,SendNativeTool:()=>zp,SendNftTool:()=>Xp,SendTokenTool:()=>Gp,Subagent:()=>ut,SubgraphAddPoolTool:()=>Bp,SubgraphCoinPoolPairsTool:()=>Up,SubgraphPoolByAddressTool:()=>Op,SubgraphPoolByPositionIdTool:()=>Lp,SubgraphPoolSearchTool:()=>Cp,SubgraphPositionDetailTool:()=>Dp,SubgraphTrendingPoolsTool:()=>Np,Summarizer:()=>Zp,SwapProviderFactory:()=>lg,SwapRouter:()=>vp,SwapRouterRegistry:()=>ag,SwapTokenTool:()=>Qp,Synthesizer:()=>nm,TOKEN_AGENT_TOOL_NAMES:()=>eS,TRADE_ERROR:()=>bt,TRADING_APPROVALS_METADATA:()=>DP,TRANSFER_TOPIC:()=>gW,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>rD,TokenAnalyticsTool:()=>du,TokenHoldersTool:()=>uu,TokenInfoTool:()=>cu,TokenScoreTool:()=>pu,ToolRegistry:()=>Zc,TopGainersTool:()=>hu,TopPoolsTool:()=>Pp,TransactionByHashTool:()=>Pu,TrendingTokensTool:()=>mu,UNISWAP_CHAIN_SLUG:()=>dg,UNRESOLVED_ASSET:()=>Ga,UP_OR_DOWN_TAG_ID:()=>UP,UpstashKnowledgeBase:()=>Ra,UserSwapRouter:()=>xp,WALLET_ACTION_AGENT_TOOL_NAMES:()=>iS,WALLET_AGENT_TOOL_NAMES:()=>JT,WALLET_DERIVATION:()=>Wr,WITHDRAW:()=>gn,WalletApprovalsTool:()=>Au,WalletDefiPositionsTool:()=>Tu,WalletDefiProtocolPositionsTool:()=>Su,WalletHistoryTool:()=>bu,WalletLendingPositionsTool:()=>Cu,WalletNFTsTool:()=>lp,WalletNftTransfersTool:()=>vu,WalletPnlSummaryTool:()=>ku,WalletPnlTool:()=>xu,WalletTokenBalancesTool:()=>yu,WalletTokenTransfersTool:()=>wu,WebsiteTrustKeyringAgent:()=>mS,ZERO_ADDRESS:()=>Pt,adjustBuyAmountForFees:()=>QP,allInBuyNotional:()=>iU,amazonDomainForLanguage:()=>wL,apiClient:()=>se,applyMarketEvent:()=>sL,applyYieldConversions:()=>fy,bestPrice:()=>cU,buildApprovalCalls:()=>nL,buildApprovals:()=>$T,buildBuilderSignature:()=>M_,buildChallenge:()=>tP,buildRangePresets:()=>SL,buildUniswapPoolUrl:()=>Ur,builderApiKey:()=>F_,buyNotional:()=>sU,buyNotionalAfterFee:()=>aU,call:()=>Fo,canDeriveV3PoolAddress:()=>IL,ceil2:()=>oU,chains:()=>Da,checkNativeGasAffordable:()=>hg,checksumAddress:()=>Sc,clampTick:()=>ks,classifyTradeError:()=>aL,classifyWithdrawError:()=>cL,clearPublicClientCache:()=>Xg,coinpoolConfigApi:()=>Sa,compareDecimal:()=>Ci,completeX402:()=>nP,configureSupportedChains:()=>ny,configureSwapProvider:()=>qT,convertSusdsShares:()=>za,createAiAgent:()=>Tg,createDefaultSubagents:()=>aS,createNfcAgent:()=>Ag,createNftAgent:()=>xg,createPolymarketSigner:()=>da,createPoolUniswapAgent:()=>Sg,createPredictionAgent:()=>vg,createPublicClient:()=>Ii,createTokenAgent:()=>kg,createTransport:()=>_i,createWalletActionAgent:()=>Pg,createWalletAgent:()=>wg,createX402SignatureProvider:()=>oP,decodeAbiParameters:()=>Dn,decodeErrorResult:()=>Ic,decodeFunctionData:()=>CS,decodeFunctionResult:()=>Uo,defiLlamaPoolInfoScope:()=>pr,defiLlamaPoolSupportsLabel:()=>mr,deployDepositWallet:()=>kw,depositPriceImpact:()=>dj,deriveBeaconDepositWallet:()=>D_,deriveDepositWallet:()=>B_,deriveSafeWallet:()=>U_,deriveUupsDepositWallet:()=>L_,deriveV3PoolAddress:()=>CL,displayFromChallenge:()=>W1,effectivePriceUSD:()=>Lm,encodeAbiParameters:()=>Ec,encodeApprove:()=>HT,encodeErrorResult:()=>PS,encodeFunctionData:()=>Le,encodeSignedHeader:()=>rP,erc1155Abi:()=>Vg,erc20Abi:()=>Ve,erc20Abi_bytes32:()=>Fc,erc721Abi:()=>qc,estimateGas:()=>Bc,estimateNativeGasReserveWei:()=>pg,estimateTransactionFeeWei:()=>OL,ethCallAt:()=>yD,ethCallByChain:()=>SK,eventHeadline:()=>My,eventUrl:()=>GP,evmDepositAssets:()=>yT,exactAmountString:()=>Ha,extractOutRaw:()=>pW,extractQuoteError:()=>mW,fallback:()=>wm,feePerShare:()=>Vi,feeWeiToNative:()=>LL,fetchOnboardingSnapshot:()=>ys,fetchTopMarketplaces:()=>vL,fetchTradingApprovalsStatus:()=>fT,fetchUnderlyingPricesUSD:()=>Bm,findWalletDepositOptions:()=>gT,floor2:()=>Ja,floorToDecimals:()=>gr,formatDefiLlamaPool:()=>Ln,getAbiItem:()=>Si,getAddress:()=>kS,getBalance:()=>Oc,getBlock:()=>Mc,getBlockNumber:()=>Cc,getCashBalance:()=>cd,getCashBalanceBaseUnits:()=>Rh,getChain:()=>xn,getChainContractAddress:()=>pm,getChainId:()=>Nc,getChainMeta:()=>No,getCode:()=>Pi,getDefaultRpcUrl:()=>zS,getGasPrice:()=>Uc,getNativeTokenInfo:()=>mc,getPolymarketBuilderCode:()=>Ou,getPublicClient:()=>Rt,getRevertReason:()=>lm,getRpcOverrides:()=>gm,getStorageAt:()=>Lc,getTokenPriceUSD:()=>py,getTransactionCount:()=>Dc,http:()=>so,humanToWei:()=>Is,ingestKnowledgeBase:()=>JW,isAbortError:()=>Va,isAddress:()=>ge,isAddressEqual:()=>xS,isBelowWithdrawMinimum:()=>kT,isEvmAddress:()=>zr,isMarketOpen:()=>Gm,isPaymentRequired:()=>hG,isShareBasedProtocol:()=>au,isShareBasedYieldToken:()=>aD,isSupplyChain:()=>vy,keyringSettingApi:()=>Ta,listCandidateChains:()=>kP,listSupplyChains:()=>wy,mapEvent:()=>By,mapMarket:()=>zP,marketFee:()=>zm,marketProtocol:()=>Wm,moneylineMarket:()=>Xa,mulDivFloor:()=>$a,multicall:()=>Qc,multicall3Abi:()=>oo,multicallRaw:()=>Ri,nativeGasShortfall:()=>OW,nfcAmazonSearchUrl:()=>OT,normaliseCountry:()=>LT,normalizeDecimal:()=>Xc,normalizeLevels:()=>Za,normalizePriceRangeToPool:()=>bp,normalizeText:()=>lt,onboardingStep:()=>lj,openSecureClient:()=>Yd,parseAbi:()=>DS,parseAbiItem:()=>Hg,parseAbiParameters:()=>um,parsePolymarketUrl:()=>Km,parsePredictionHint:()=>Ym,pickLogo:()=>yi,placePredictionOrder:()=>fj,planYieldTokenConversions:()=>bP,predictionHint:()=>rU,prepareMarketOrder:()=>lU,priceToTick:()=>pc,protocolLabelFor:()=>yr,psm3For:()=>hy,pusdFromBaseUnits:()=>lL,pusdToBaseUnits:()=>xT,quoteBuyAsPolymarket:()=>YP,quoteBuyUsd:()=>Du,quoteDeposit:()=>sg,quoteMarketOrder:()=>JP,quoteSellShares:()=>XP,quoteWithdrawal:()=>bj,readContract:()=>qo,readPaymentError:()=>V1,readPaymentRequired:()=>Zg,readProtocolFeeWei:()=>VT,readReceipt:()=>j1,readSpendableBalance:()=>gg,readTokenUsdPrice:()=>fg,redeemPredictionPositions:()=>vj,registerMaybeNoForm:()=>XT,remoteBuilderSigning:()=>KF,requestWithX402:()=>mG,resolveAccountWallet:()=>bw,resolveCategory:()=>Fy,resolveGasLimit:()=>NW,resolveNfcShopLinks:()=>dp,resolveRawYieldAsset:()=>J1,resolveRawYieldIdentity:()=>ja,resolveRawYieldProtocol:()=>X1,resolveRpcUrl:()=>$o,resolveRpcUrls:()=>Fa,resolveTokenPriceUSD:()=>Dm,roundTickToSpacing:()=>vs,rpcCall:()=>gD,runPolymarketOnboarding:()=>cj,setPolymarketBuilderCode:()=>CP,setRpcOverrides:()=>Ma,slippagePrice:()=>qy,spendableNative:()=>mg,swapProviderFactory:()=>Ap,swapRouterRegistry:()=>FT,tickToPrice:()=>Co,ticketFee:()=>KP,toBuilderAuthorization:()=>ts,toEventSelector:()=>AS,toFunctionSelector:()=>Es,toPantographChain:()=>NG,toPlainDecimal:()=>vm,unitPriceUSD:()=>lu,upDownWindow:()=>Dy,valueYieldTokens:()=>gy,walletDepositAssets:()=>rL,watchCryptoPrice:()=>eU,watchOrderBooks:()=>mj,weiToHuman:()=>Jc,withdrawDestinations:()=>vT,withdrawFromPolymarket:()=>wj});module.exports=sz(yye);var zL=jL(require("axios"));var WL="0.4.3";var az=`keyring-agent-core/${WL} (Keyring Chatbot Agent; +https://keyring.app)`,hS=null;function GL(e){hS=e}var lz=["payment-signature","x-payment"];function cz(e){return e?Object.keys(e).some(t=>lz.includes(t.toLowerCase())):!1}var gS;function om(e){gS=e}function KL(){return gS}var uz=3e4,dz=typeof process<"u"&&process.versions?.node!=null,fS=class{instance;constructor(t={}){this.instance=zL.default.create({baseURL:t.baseURL,timeout:t.timeout??uz,validateStatus:()=>!0,headers:{Accept:"application/json",...dz?{"Accept-Encoding":"gzip, deflate, br","User-Agent":t.userAgent??az}:{},...t.headers}})}async request(t,n,r,o={}){let s=o.signal??gS,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&&hS&&!cz(o.headers)){let c=await hS(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 fS;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 pz(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??pz(n.cause),o=n.metaMessages??[],s=[t||"An error occurred.",...o.length>0?["",...o]:[],...r?["",`Details: ${r}`]:[]].join(`
|
|
8
|
+
`)}function o3(e){return s3(e).slice(0,99)}function s3(e,t=[]){let n=e.flatMap(r=>{let o=[...t,...r.path];return r.code==="invalid_union"?r.errors.flatMap(s=>s3(s,o)):[{code:r.code,message:r.message,path:o.length===0?null:Bee(o)}]});return Dee(n)}function Dee(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(Uee)}function Uee(e,t){return e.path===null&&t.path!==null?-1:e.path!==null&&t.path===null?1:(e.path??"").localeCompare(t.path??"")}function Bee(e){return e.reduce((t,n)=>typeof n=="number"?`${t}[${n.toString()}]`:typeof n!="string"?t:n.includes('"')?`${t}["${n.replaceAll('"','\\"')}"]`:Nee.test(n)?t.length===0?n:`${t}.${n}`:`${t}["${n}"]`,"")}function B(...e){return{isError(t){return e.some(n=>t instanceof n)}}}var Nee,E,Nl,C,I,RC,Qr,_C,O,$,tt,Jw,en,vt,So,df,Zw,ce,e0=L(()=>{"use strict";Xw();Al();Nee=/^[$A-Z_a-z][$\w]*$/;E=class i3 extends Ct{name="UserInputError";constructor(t,n={}){super(t,n)}static fromZodError(t){return new i3(Oee(t),{cause:t})}},Nl=class extends Ct{name="PaginationLimitError";constructor(e,t={}){super(e,t)}},C=class a3 extends Ct{name="UnexpectedResponseError";constructor(t,n={}){super(t,n)}static fromZodError(t,n){return new a3(Lee(t,n),{cause:t})}},I=class l3 extends Ct{name="TransportError";constructor(t,n={}){super(t,n)}static fromError(t){return new l3(t instanceof Error?t.message:"Request failed",{cause:t})}},RC=(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))(RC||{}),Qr=class extends Ct{name="ConnectionLostError";code;reason;constructor(e,t){super(e,t),this.code=t.code,this.reason=t.reason}},_C=(e=>(e.RESTARTING="restarting",e.POST_ONLY="post_only",e))(_C||{}),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)}},Jw=class c3 extends Ct{name="OperationAbortedError";constructor(t,n={}){super(t,n)}static fromReason(t){return new c3("Operation was aborted.",{cause:t})}},en=class extends Ct{name="TransactionFailedError";constructor(e,t={}){super(e,t)}},vt=class u3 extends Ct{name="CancelledSigningError";constructor(t,n={}){super(t,n)}static fromError(t){return new u3(t.message,{cause:t})}},So=class extends Ct{name="InsufficientLiquidityError";constructor(e,t={}){super(e,t)}},df=class extends Ct{name="AutoCancelDailyLimitError";constructor(e,t={}){super(e,t)}},Zw=class extends Ct{name="PerpsCancelRetryError";results;pendingIndexes;constructor(e,t){super(e,t),this.results=[...t.results],this.pendingIndexes=[...t.pendingIndexes]}},ce=class d3 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 d3(r,{cause:t})}}});var pf=L(()=>{"use strict";xo()});var m3,Rr,IC,CC=L(()=>{"use strict";m3=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||{}),IC=m3.z.enum(Rr)});function t0(e){return x.z.object({count:x.z.number(),data:x.z.array(e),limit:x.z.number(),next_cursor:x.z.string()}).transform(({next_cursor:t,...n})=>({...n,nextCursor:t}))}function ls(e,t){return x.z.object({id:uI,owner:is,payload:t,timestamp:ute,type:x.z.literal(e)})}function Ite(e){return e.success&&e.errorMsg===""&&e.orderID!==""&&Lte(e.status)}function Cte(e){switch(e){case"live":return"live";case"matched":return"matched";case"delayed":return"delayed";default:oq(`Unexpected order post status: ${e}`)}}function Nte(e){return Ite(e)?Rte.parse({makingAmount:e.makingAmount,ok:!0,orderId:e.orderID,status:Cte(e.status),takingAmount:e.takingAmount,tradeIds:e.tradeIDs,transactionsHashes:e.transactionsHashes}):_te.parse({code:Ote(e),message:e.errorMsg||"Unknown order failure",ok:!1})}function Ote(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 Lte(e){return e==="live"||e==="matched"||e==="delayed"}var x,b3,NC,w3,Mee,Fee,v3,ra,k3,x3,A3,T3,qee,S3,Hee,P3,E3,$ee,Vee,jee,Wee,R3,OC,_3,I3,h3,C3,zee,N3,f3,Gee,O3,L3,D3,U3,B3,Kee,M3,F3,q3,Yee,H3,Qee,$3,Xee,V3,Jee,Zee,ete,j3,tte,W3,n0,nte,LC,rte,ote,z3,ste,ite,ate,lte,cte,ute,dte,pte,mte,hte,fte,gte,yte,bte,wte,vte,kte,xte,G3,g3,Ate,Tte,K3,Y3,Q3,y3,Ste,r0,Pte,o0,Ete,Rte,_te,DC,X3,Yn,Dte,Ute,J3,Bte,Mte,Fte,Z3,qte,e$,Hte,t$,UC=L(()=>{"use strict";CC();Wh();xo();x=require("zod");Al();b3=x.z.object({closed_only:x.z.boolean()}).transform(({closed_only:e})=>({closedOnly:e})),NC=x.z.object({asset_id:Me,associate_trades:x.z.array(x.z.string()),created_at:Yi,expiration:iI,id:x.z.string(),maker_address:x.z.string(),market:xe,order_type:x.z.string(),original_size:R,outcome:x.z.string(),owner:x.z.string(),price:R,side:x.z.string(),size_matched:R,status:x.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}}),w3=t0(NC),Mee=x.z.object({asset_id:Me,fee_rate_bps:x.z.preprocess(Gn,R.nullable()),maker_address:x.z.string(),matched_amount:R,order_id:x.z.string(),outcome:x.z.string(),owner:x.z.string(),price:R,side:x.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})),Fee=x.z.object({asset_id:Me,bucket_index:x.z.number(),fee_rate_bps:R,id:x.z.string(),last_update:Yi,maker_address:x.z.string(),maker_orders:x.z.array(Mee),market:xe,match_time:Yi,outcome:x.z.string(),owner:x.z.string(),price:R,side:x.z.string(),size:R,status:Bh,taker_order_id:x.z.string(),trader_side:x.z.enum(["TAKER","MAKER"]),transaction_hash:x.z.preprocess(gd,x.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})),v3=t0(Fee),ra=(e=>(e.COLLATERAL="COLLATERAL",e.CONDITIONAL="CONDITIONAL",e.CONDITIONAL_V2="CONDITIONAL-V2",e))(ra||{}),k3=x.z.enum(ra),x3=x.z.object({allowances:x.z.record(J,x.z.string().transform(BigInt)),balance:as}),A3=x.z.object({scoring:x.z.boolean()}),T3=x.z.record(x.z.string(),x.z.boolean()),qee=x.z.object({asset_address:x.z.string(),asset_rate:H,condition_id:xe,date:un,earnings:H,maker_address:x.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})),S3=t0(qee),Hee=x.z.object({asset_address:x.z.string(),asset_rate:H,date:un,earnings:H,maker_address:x.z.string()}).transform(({asset_address:e,asset_rate:t,maker_address:n,...r})=>({...r,assetAddress:e,assetRate:t,makerAddress:n})),P3=x.z.array(Hee),E3=x.z.record(xe,x.z.number()),$ee=x.z.object({outcome:x.z.string(),price:H,token_id:Me}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Vee=x.z.object({asset_address:x.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})),jee=x.z.object({asset_address:x.z.string(),asset_rate:H,earnings:H}).transform(({asset_address:e,asset_rate:t,...n})=>({...n,assetAddress:e,assetRate:t})),Wee=x.z.object({condition_id:xe,earning_percentage:x.z.number(),earnings:x.z.array(jee),event_slug:x.z.string(),image:x.z.string(),maker_address:x.z.string(),market_competitiveness:x.z.number(),market_slug:x.z.string(),question:x.z.string(),rewards_config:x.z.array(Vee),rewards_max_spread:x.z.number(),rewards_min_size:H,tokens:x.z.array($ee)}).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})),R3=t0(Wee),OC=x.z.object({apiKey:is,secret:x.z.string(),passphrase:x.z.string()}).transform(e=>({key:e.apiKey,passphrase:e.passphrase,secret:e.secret})),_3=x.z.object({apiKeys:x.z.array(is)}),I3=x.z.object({key:is,secret:x.z.string(),passphrase:x.z.string()}),h3=x.z.object({key:is,createdAt:un.optional(),revokedAt:un.nullable().optional()}),C3=x.z.array(x.z.union([is.transform(e=>({key:e})),h3])).transform(e=>e.map(t=>h3.parse(t))),zee=x.z.object({id:x.z.string(),tradeType:x.z.string(),takerOrderHash:x.z.string(),builder:x.z.string(),market:xe,assetId:Me,side:Nt,size:R,sizeUsdc:R,price:R,status:x.z.string(),outcome:x.z.string(),outcomeIndex:x.z.number().int(),owner:x.z.string(),maker:x.z.string(),transactionHash:x.z.string(),matchTime:Yi,bucketIndex:x.z.number().int(),fee:R,feeUsdc:R,err_msg:x.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})),N3=x.z.object({limit:x.z.number().int(),count:x.z.number().int(),next_cursor:x.z.string(),data:x.z.array(zee)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),f3=1e4,Gee=x.z.object({builder_maker_fee_rate_bps:x.z.number(),builder_taker_fee_rate_bps:x.z.number()}).transform(({builder_maker_fee_rate_bps:e,builder_taker_fee_rate_bps:t})=>({maker:e/f3,taker:t/f3})),O3=Gee,L3=x.z.object({canceled:x.z.array(fd),not_canceled:x.z.record(fd,x.z.string())}).transform(({canceled:e,not_canceled:t})=>({canceled:e,notCanceled:t})),D3=x.z.object({mid:R}),U3=x.z.record(Me,R),B3=x.z.object({price:R}),Kee=x.z.partialRecord(Nt,R),M3=x.z.record(Me,Kee),F3=x.z.object({spread:R}),q3=x.z.record(Me,R),Yee=x.z.object({price:R,side:Nt}),H3=Yee.extend({side:x.z.union([Nt,x.z.literal("")])}).transform(e=>e.side===""?null:{price:e.price,side:e.side}),Qee=x.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})),$3=x.z.array(Qee),Xee=x.z.object({condition_id:xe}).transform(({condition_id:e})=>e),V3=Xee,Jee=x.z.object({r:x.z.number().default(0),e:x.z.number().default(0)}).transform(({r:e,e:t})=>({rate:e,exponent:t})),Zee=x.z.object({t:Me,o:x.z.string()}).transform(({t:e,o:t})=>({assetId:e,tokenId:e,outcome:t})),ete=x.z.object({fd:Jee.nullish(),mts:Sl,nr:x.z.boolean().optional(),t:x.z.array(Zee)}).transform(({fd:e,mts:t,nr:n,t:r})=>({feeInfo:e??{rate:0,exponent:0},negRisk:n??!1,tickSize:t,tokens:r})),j3=ete,tte=x.z.object({neg_risk:x.z.boolean()}).transform(({neg_risk:e,...t})=>({...t,negRisk:e})),W3=tte,n0=(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))(n0||{}),nte=x.z.enum(n0),LC=x.z.object({asset_id:Me,eventSlug:x.z.string().optional(),icon:x.z.string().optional(),image:x.z.string().optional(),market:xe,market_slug:x.z.string().optional(),matched_size:R,order_id:fd,original_size:R,outcome:x.z.string(),outcome_index:x.z.number().int(),price:R,question:x.z.string().optional(),remaining_size:R,seriesSlug:x.z.string().optional(),side:Nt,trade_id:x.z.preprocess(gd,x.z.string().optional()),transaction_hash:x.z.preprocess(gd,et.optional()),type:x.z.preprocess(gd,Uh.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})),rte=x.z.object({outcome:x.z.string(),price:H.optional(),token_id:Me,winner:x.z.boolean()}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),ote=x.z.object({max_spread:x.z.number(),min_size:H,rates:x.z.array(x.z.object({asset_address:x.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})),z3=x.z.object({accepting_order_timestamp:hd.nullish(),accepting_orders:x.z.boolean(),active:x.z.boolean(),archived:x.z.boolean().optional(),closed:x.z.boolean(),condition_id:xe,description:x.z.string(),enable_order_book:x.z.boolean().optional(),end_date_iso:hd.nullish(),eventSlug:x.z.string().optional(),fpmm:x.z.string(),game_start_time:hd.nullish(),icon:x.z.string(),image:x.z.string(),is_50_50_outcome:x.z.boolean().optional(),maker_base_fee:x.z.number().nullable(),market_slug:x.z.string(),minimum_order_size:H,minimum_tick_size:H,neg_risk:x.z.boolean().optional(),neg_risk_market_id:x.z.string().optional(),neg_risk_request_id:x.z.string().optional(),notifications_enabled:x.z.boolean().optional(),question:x.z.string(),question_id:vo,rewards:ote.optional(),seconds_delay:x.z.number().int(),tags:x.z.array(x.z.string()).nullish(),taker_base_fee:x.z.number().nullable(),tokens:x.z.array(rte)}).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})),ste=x.z.object({proxyWallet:J,reward:H,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),ite=x.z.object({amount:H,proxyWallet:J,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),ate=x.z.object({body:x.z.string().nullish(),createdAt:re.nullish(),eventSlug:x.z.string().nullish(),eventTitle:x.z.string().nullish(),id:Xs,image:x.z.string().nullish(),parentCommentID:Xs.nullish(),parentEntityID:x.z.number().int().nullish(),parentEntityType:Js.nullish(),profile:El.nullish(),seriesSlug:x.z.string().nullish(),seriesTitle:x.z.string().nullish(),userAddress:x.z.string().nullish()}),lte=x.z.object({amount:H,conditionId:xe,image:x.z.string(),marketUrl:x.z.string().optional(),negRisk:x.z.boolean(),portfolioUrl:x.z.string().optional(),position:x.z.string().optional(),proxyWallet:J,question:x.z.string(),slug:x.z.string(),txnHash:et}).transform(({slug:e,txnHash:t,...n})=>({...n,marketSlug:e,transactionHash:t})),cte=x.z.object({amount:H,conditionId:Zt,legs:x.z.number().int(),outcomeIndex:x.z.number().int(),portfolioUrl:x.z.string().optional(),positionId:Xe,proxyWallet:J,txnHash:et}).transform(({txnHash:e,...t})=>({...t,transactionHash:e})),ute=x.z.preprocess(e=>typeof e!="string"?e:/^\d+$/.test(e)?Number(e):Date.parse(e),pe);dte=ls(1,LC),pte=ls(2,LC),mte=ls(3,z3),hte=ls(4,z3),fte=ls(5,ste),gte=ls(6,ate),yte=ls(7,ite),bte=ls(8,LC),wte=ls(9,lte),vte=ls(10,cte),kte=x.z.discriminatedUnion("type",[dte,pte,mte,hte,fte,gte,yte,bte,wte,vte]),xte=x.z.object({type:x.z.number().int()}),G3=x.z.array(x.z.unknown()).transform((e,t)=>{let n=[];return e.forEach((r,o)=>{let s=xte.safeParse(r);if(!s.success){for(let a of s.error.issues)t.addIssue({...a,path:[o,...a.path]});return}if(!nte.safeParse(s.data.type).success)return;let i=kte.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}),g3=x.z.object({price:R,size:R}),Ate=x.z.string().regex(/^[a-f0-9]{40}$/).transform(e=>e),Tte=R.transform(Number).pipe(Sl),K3=x.z.object({market:xe,asset_id:Me,timestamp:Pr.nullish(),bids:x.z.array(g3),asks:x.z.array(g3),min_order_size:R,tick_size:Tte,neg_risk:x.z.boolean(),last_trade_price:R.nullish(),hash:Ate}).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})),Y3=K3,Q3=x.z.array(K3),y3=x.z.preprocess(e=>e===""?"0":e,R),Ste=x.z.object({errorMsg:x.z.string(),makingAmount:y3,orderID:x.z.string(),status:x.z.string(),success:x.z.boolean(),takingAmount:y3,tradeIDs:x.z.array(x.z.string()).default([]),transactionsHashes:x.z.array(x.z.string()).default([])}),r0=(e=>(e.LIVE="live",e.MATCHED="matched",e.DELAYED="delayed",e))(r0||{}),Pte=x.z.nativeEnum(r0),o0=(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))(o0||{}),Ete=x.z.nativeEnum(o0),Rte=x.z.object({ok:x.z.literal(!0),orderId:fd.refine(e=>e.length>0),status:Pte,makingAmount:R,takingAmount:R,tradeIds:x.z.array(x.z.string()),transactionsHashes:x.z.array(et)}),_te=x.z.object({ok:x.z.literal(!1),code:Ete,message:x.z.string().min(1)}),DC=Ste.transform(Nte),X3=x.z.array(DC);Yn="LTE=",Dte=x.z.object({id:x.z.number().int().optional(),asset_address:x.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})),Ute=x.z.object({condition_id:xe,rewards_max_spread:x.z.number().optional(),rewards_min_size:H.optional(),rewards_config:x.z.array(Dte).optional(),sponsored_daily_rate:H.optional(),sponsors_count:x.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})),J3=x.z.object({limit:x.z.number().int(),count:x.z.number().int(),next_cursor:x.z.string(),data:x.z.array(Ute)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),Bte=x.z.object({token_id:Me,outcome:x.z.string(),price:H}).transform(({token_id:e,...t})=>({...t,assetId:e,tokenId:e})),Mte=x.z.object({asset_address:x.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})),Fte=x.z.object({condition_id:xe,question:x.z.string(),market_slug:x.z.string().optional(),event_slug:x.z.string().optional(),image:x.z.string().optional(),rewards_max_spread:x.z.number().optional(),rewards_min_size:H.optional(),market_competitiveness:x.z.number().optional(),tokens:x.z.array(Bte),rewards_config:x.z.array(Mte).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})),Z3=x.z.object({limit:x.z.number().int(),count:x.z.number().int(),next_cursor:x.z.string(),data:x.z.array(Fte)}).transform(({next_cursor:e,...t})=>({...t,nextCursor:e})),qte=x.z.object({address:J,scopes:x.z.array(Nh).min(1),valid_until:x.z.number().int().nonnegative()}).transform(({valid_until:e,...t})=>({...t,validUntil:e})),e$=x.z.object({signers:x.z.array(qte),wallet:J}),Hte=x.z.object({minimum_tick_size:Sl}).transform(({minimum_tick_size:e,...t})=>({...t,minimumTickSize:e})),t$=Hte});var ae,mf,$te,Vte,n$,UCe,jte,Wte,r$,zte,Gte,o$,_d,Kte,s$,BC,MC,FC,i$,Se,BCe,s0=L(()=>{"use strict";Wh();Wh();xo();ae=require("zod"),mf=(e=>(e.Pending="pending",e.Queued="queued",e.Success="success",e.Failed="failed",e.Cancelled="cancelled",e))(mf||{}),$te=ae.z.union([ae.z.string(),ae.z.number().int().transform(String)]).transform(Aw),Vte=ae.z.object({id:ae.z.number().int(),marketId:$te.nullish(),eventId:Gt.nullish(),questionId:vo.nullish(),content:ae.z.string().nullish(),state:ae.z.enum(mf).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:re.nullish(),queuedAt:re.nullish(),scheduledFor:re.nullish(),txTimestamp:re.nullish()}),n$=ae.z.array(Vte),UCe=ae.z.object({hasMore:ae.z.boolean().nullish(),totalResults:ae.z.number().int().nullish()}),jte=ae.z.object({id:ae.z.string(),communityMod:ae.z.boolean().nullish(),creator:ae.z.boolean().nullish(),mod:ae.z.boolean().nullish()}),Wte=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:re.nullish(),updatedAt:re.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:re.nullish(),discordUsername:ae.z.string().nullish(),xUsername:ae.z.string().nullish(),verifiedBadge:ae.z.boolean().nullish(),dubPartnerId:ae.z.string().nullish(),termsAcceptedAt:re.nullish(),viewOnlyAcknowledgedAt:re.nullish(),isReferralRestricted:ae.z.boolean().nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),r$=ae.z.object({createdAt:re.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(jte).nullish(),xUsername:ae.z.string().nullish(),verifiedBadge:ae.z.boolean().nullish()}).transform(({proxyWallet:e,...t})=>({...t,wallet:e})),zte=ae.z.object({id:Mh,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})),Gte=ae.z.object({hasMore:ae.z.boolean().nullish(),totalResults:ae.z.number().int().nullish()}),o$=ae.z.object({events:ae.z.array(ei).nullish(),tags:ae.z.array(zte).nullish(),profiles:ae.z.array(Wte).nullish(),pagination:Gte.nullish()}),_d=Pl.extend({templates:ae.z.array(Bw).nullish()}),Kte=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})),s$=ae.z.array(_d),BC=ae.z.array(Kte),MC=ae.z.array(_d),FC=Uw.extend({events:ae.z.array(ei).nullish(),collections:ae.z.array(Dw).nullish(),tags:ae.z.array(_d).nullish()}),i$=ae.z.array(FC),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||{}),BCe=ae.z.object({type:ae.z.enum(Se),typeName:ae.z.enum(["EOA","POLY_PROXY","GNOSIS_SAFE","DEPOSIT_WALLET"])})});var Ol,qC=L(()=>{"use strict";Ol=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 Id,HC=L(()=>{"use strict";Id=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,a$=L(()=>{"use strict";HC();Cd=class extends Error{name="ForceRetryError";customDelay;code;customRequest;constructor(t){let n=t?.cause?t.cause instanceof Error?t.cause:new Id(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 $C,l$,i0,c$,u$,a0,Yte,d$,l0,p$,c0,hf,m$,h$,f$,g$,Ll=L(()=>{"use strict";$C=(()=>{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})(),l$=typeof globalThis.AbortController=="function",i0=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",c$=typeof globalThis.ReadableStream=="function",u$=typeof globalThis.FormData=="function",a0=["get","post","put","patch","head","delete"],Yte=()=>{};Yte();d$={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},l0=2147483647,p$=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,c0=Symbol("stop"),hf=class{options;constructor(t){this.options=t}},m$=e=>new hf(e),h$={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},f$={next:!0},g$={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 Qte,y$,b$,w$,v$=L(()=>{"use strict";Ll();Qte=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=p$,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},y$=(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))}}))},b$=(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(y$(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},w$=(e,t,n)=>{if(!e.body)return e;let r=Qte(n??e.body);return new Request(e,{duplex:"half",body:y$(e.body,r,t)})}});var oa,k$=L(()=>{"use strict";oa=e=>e!==null&&typeof e=="object"});function u0(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:WC(e[n]??[],t[n]??[])}var ff,VC,jC,Xte,WC,zC=L(()=>{"use strict";Ll();k$();ff=(...e)=>{for(let t of e)if((!oa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return WC({},...e)},VC=(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};jC=(e={},t={})=>({beforeRequest:u0(e,t,"beforeRequest"),beforeRetry:u0(e,t,"beforeRetry"),afterResponse:u0(e,t,"afterResponse"),beforeError:u0(e,t,"beforeError")}),Xte=(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(oa(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},WC=(...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(oa(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&&(!oa(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:Xte(o,l);continue}oa(l)&&a in t&&(l=WC(t[a],l)),t={...t,[a]:l}}oa(i.hooks)&&(r=jC(r,i.hooks),t.hooks=r),oa(i.headers)&&(n=VC(n,i.headers),t.headers=n)}return o!==void 0&&(t.searchParams=o),s.length>0&&(s.length===1?t.signal=s[0]:i0?t.signal=AbortSignal.any(s):t.signal=s.at(-1)),t}});var A$,Jte,Zte,ene,x$,T$,S$=L(()=>{"use strict";Ll();A$=e=>a0.includes(e)?e.toUpperCase():e,Jte=["get","put","head","delete","options","trace"],Zte=[408,413,429,500,502,503,504],ene=[413,429,503],x$={limit:2,methods:Jte,statusCodes:Zte,afterStatusCodes:ene,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},T$=(e={})=>{if(typeof e=="number")return{...x$,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{...x$,...t}}});var Dl,GC=L(()=>{"use strict";Dl=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}}});async function KC(e,t,n,r){return new Promise((o,s)=>{let i=setTimeout(()=>{n&&n.abort(),s(new Dl(e))},r.timeout);r.fetch(e,t).then(o).catch(s).then(()=>{clearTimeout(i)})})}var P$=L(()=>{"use strict";GC()});async function YC(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 E$=L(()=>{"use strict"});var R$,_$,I$=L(()=>{"use strict";Ll();R$=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in g$)&&!(r in h$)&&(!(r in e)||r in f$)&&(n[r]=t[r]);return n},_$=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 C$(e){return e instanceof Ol||e?.name===Ol.name}function N$(e){return e instanceof Dl||e?.name===Dl.name}var O$=L(()=>{"use strict";qC();GC()});var gf,L$=L(()=>{"use strict";qC();HC();a$();v$();zC();S$();P$();E$();I$();O$();Ll();gf=class e{static create(t,n){let r=new e(t,n),o=async()=>{if(typeof r.#n.timeout=="number"&&r.#n.timeout>l0)throw new RangeError(`The \`timeout\` option cannot be greater than ${l0}`);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 hf)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 Ol(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(!c$)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");let a=i.clone();return r.#d(i),b$(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(d$))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:VC(this.#s.headers,n.headers),hooks:jC({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:A$(n.method??this.#s.method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:T$(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}l$&&i0&&(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),$C&&(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&&(u$&&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),_$(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(!$C)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 Id(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(N$(t)&&!this.#n.retry.retryOnTimeout)throw t;if(C$(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),l0);if(this.#r<1)throw n;if(await YC(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===c0)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=R$(this.request,this.#n);return this.#o=this.request,this.request=this.#o.clone(),this.#n.timeout===!1?this.#n.fetch(this.#o,t):KC(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:w$(t,this.#n.onUploadProgress,n??this.#n.body??void 0)}}});var QC,tne,d0,D$=L(()=>{"use strict";L$();Ll();zC();QC=e=>{let t=(n,r)=>gf.create(n,ff(e,r));for(let n of a0)t[n]=(r,o)=>gf.create(r,ff(e,o,{method:n}));return t.create=n=>QC(ff(n)),t.extend=n=>(typeof n=="function"&&(n=n(e??{})),QC(ff(e,n))),t.stop=c0,t.retry=m$,t},tne=QC(),d0=tne});function nne(e){let t=e.length===64?`${e}00`:e;return Oh(t.toLowerCase())}function rne(e){if(e.length===66)return!0;let t=e.toLowerCase();return t.startsWith("0x01")||t.startsWith("0x02")}function us(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 vne(e){let t=kne(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 kne(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 xne(e){let t=Tne(e);switch(e.type){case"TRADE":return Ane(e,t);case"SPLIT":case"MERGE":case"REDEEM":case"CONVERSION":return{...t,type:e.type,conditionId:_r(e.condition_id,"condition_id"),amount:e.usdc_size,title:_r(e.title,"title"),slug:_r(e.slug,"slug"),icon:e.icon??null,eventSlug:_r(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:B$.parse(e.side)}}}function Ane(e,t){let n={...t,type:"TRADE",side:Nt.parse(_r(e.side,"side")),shares:e.size,amount:e.usdc_size,price:e.price,title:_r(e.title,"title"),icon:e.icon??null};if(e.is_combo===!0)return{...n,isCombo:!0,conditionId:Zt.parse(_r(e.condition_id,"condition_id")),positionId:Xe.parse(_r(e.token_id,"token_id"))};let r=_r(e.token_id,"token_id");return{...n,isCombo:!1,conditionId:_r(e.condition_id,"condition_id"),assetId:r,tokenId:r,outcome:_r(e.outcome,"outcome"),outcomeIndex:e.outcome_index,slug:_r(e.slug,"slug"),eventSlug:_r(e.event_slug,"event_slug")}}function Tne(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 _r(e,t){if(e==null)throw new TypeError(`Expected activity.${t} to be present`);return e}var U,m0,XC,Ul,B$,Bl,h0,Ml,M$,Fl,ii,Nd,ai,F$,one,ql,q$,Hl,H$,$l,$$,oi,sne,ine,ane,Vl,JC,jl,p0,pn,V$,lne,cne,une,dne,pne,j$,mne,W$,z$,G$,K$,Y$,Q$,Wl,hne,fne,gne,Kt,X$,yne,bne,wne,J$,Z$,e4,Po,t4,Sne,n4,yf,Pne,Ene,Rne,_ne,Ine,r4,o4,s4,zl,bf,Gl,i4,Kl,a4,Yl,SNe,Cne,Nne,cs,One,Lne,Dne,Une,Bne,l4,c4,u4,d4,p4,Ql,Mne,Xl,Fne,Jl,qne,Zl,Hne,U$,$ne,m4,f0=L(()=>{"use strict";xo();U=require("zod"),m0=(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))(m0||{}),XC=U.z.enum(m0),Ul=(e=>(e.In="IN",e.Out="OUT",e))(Ul||{}),B$=U.z.enum(Ul),Bl=(e=>(e.Asc="ASC",e.Desc="DESC",e))(Bl||{}),h0=U.z.enum(Bl),Ml=(e=>(e.Cash="CASH",e.Tokens="TOKENS",e))(Ml||{}),M$=U.z.enum(Ml);Fl=xe.refine(rne,"Expected a 32-byte condition ID or a 31-byte protocol v2 market condition ID").transform(nne);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||{}),F$=U.z.enum(ai),one=U.z.enum(["OPEN","REDEEMABLE","CLOSED"]),ql=(e=>(e.CurrentValue="CURRENT_VALUE",e.Tokens="TOKENS",e.UnrealizedPnl="UNREALIZED_PNL",e.RealizedPnl="REALIZED_PNL",e.TotalPnl="TOTAL_PNL",e.Timestamp="TIMESTAMP",e))(ql||{}),q$=U.z.enum(ql),Hl=(e=>(e.Cash="CASH",e.Tokens="TOKENS",e))(Hl||{}),H$=U.z.enum(Hl),$l=(e=>(e.FirstEntry="FIRST_ENTRY",e.EntryCost="ENTRY_COST",e.CurrentValue="CURRENT_VALUE",e.Updated="UPDATED",e))($l||{}),$$=U.z.enum($l),oi=U.z.preprocess(e=>e===""?void 0:e,U.z.string().optional()),sne=U.z.preprocess(e=>e===999?void 0:e,U.z.number().int().optional()),ine=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:one,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:sne,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,zn.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})),ane=U.z.object({proxy_wallet:J,value:H}).transform(({proxy_wallet:e,value:t})=>({wallet:e,value:t})),Vl=(e=>(e.Max="max",e.OneMonth="1m",e.OneWeek="1w",e.OneDay="1d",e.TwelveHours="12h",e.SixHours="6h",e))(Vl||{}),JC=U.z.enum(Vl),jl=(e=>(e.OneDay="1d",e.EighteenHours="18h",e.TwelveHours="12h",e.ThreeHours="3h",e.OneHour="1h",e))(jl||{}),p0=U.z.enum(jl),pn=H.nullish().transform(e=>e??null),V$=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:A,volume_usdc:k,trade_count:T,...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:A,volumeUsdc:k,tradeCount:T})),lne=U.z.object({proxy_wallet:J,interval:JC,fidelity:p0,source_fidelity:p0,points:U.z.array(V$)}).transform(({proxy_wallet:e,source_fidelity:t,...n})=>({...n,wallet:e,sourceFidelity:t})),cne=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})),une=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:V$.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})),dne=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})),pne=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:re.nullish(),event:dne.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})),j$=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:re.nullish(),leg_current_price:H.nullish(),market:pne.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})),mne=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:re,resolved_at:re.nullish(),legs_total:U.z.number().int(),legs_resolved:U.z.number().int(),legs_pending:U.z.number().int(),legs:U.z.array(j$),updated_at:re}).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})),W$=us(ine),z$=si(ane),G$=si(une.nullable()),K$=si(lne),Y$=si(cne),Q$=us(mne),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||{}),hne=U.z.enum(Wl),fne=U.z.object({id:sI,type:hne,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(j$)}),gne=fne.transform(vne),Kt=U.z.preprocess(e=>e===""?void 0:e,U.z.string().optional()),X$=U.z.preprocess(e=>e===999?void 0:e,U.z.number().int().optional()),yne=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:X$,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})),bne=U.z.object({proxy_wallet:J,timestamp:wo,condition_id:U.z.preprocess(e=>e===""?void 0:e,xe.optional()),type:XC,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,B$]).optional()),is_combo:U.z.boolean().optional(),outcome_index:X$,title:Kt,slug:Kt,icon:Kt,event_slug:Kt,outcome:Kt,name:Kt,pseudonym:Kt,bio:Kt,profile_image:Kt,profile_image_optimized:Kt}),wne=bne.transform(xne),J$=us(yne),Z$=us(wne),e4=us(gne);Po=(e=>(e.Max="max",e.OneMonth="1m",e.OneWeek="1w",e.OneDay="1d",e.SixHours="6h",e.OneHour="1h",e))(Po||{}),t4=U.z.enum(Po),Sne=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})),n4=us(Sne),yf=U.z.preprocess(e=>e===""?null:e,U.z.string().nullable()),Pne=U.z.object({proxy_wallet:J,bio:yf,token_id:Me,pseudonym:yf,amount:H,display_username_public:U.z.boolean(),outcome_index:U.z.preprocess(e=>e===999?null:e,U.z.number().int().nullable()),name:yf,profile_image:yf,profile_image_optimized:yf,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})),Ene=U.z.object({token_id:Me,holders:U.z.array(Pne)}).transform(({holders:e,token_id:t})=>({assetId:t,token:t,holders:e})),Rne=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})),_ne=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})),Ine=U.z.object({taker_volume_total:H,conditions:U.z.array(_ne)}).transform(({conditions:e,taker_volume_total:t})=>({markets:e,takerVolumeTotal:t})),r4=us(Ene),o4=si(U.z.array(Rne)),s4=si(Ine),zl=(e=>(e.Day="day",e.Week="week",e.Month="month",e.All="all",e))(zl||{}),bf=U.z.enum(zl),Gl=(e=>(e.Day="day",e.Week="week",e.Month="month",e.Year="all",e))(Gl||{}),i4=U.z.enum(Gl),Kl=(e=>(e.Pnl="PNL",e.Volume="VOLUME",e))(Kl||{}),a4=U.z.enum(Kl),Yl=(e=>(e.Market="market",e.Combo="combo",e))(Yl||{}),SNe=U.z.enum(Yl),Cne=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}})),Nne=U.z.object({date:zn,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}})),cs=U.z.preprocess(Gn,U.z.string().nullable()),One=U.z.object({rank:U.z.number().int().min(0),user_id:J,pnl:H,volume:H,user_name:cs,profile_image:cs,x_username:cs,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})),Lne=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:cs,profile_image:cs,x_username:cs,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})),Dne=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:cs,profile_image:cs}),Une=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:cs,profile_image:cs}),Bne=U.z.discriminatedUnion("kind",[Dne,Une]).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}),l4=us(Cne),c4=si(U.z.array(Nne)),u4=us(One),d4=si(Lne.nullable()),p4=us(Bne),Ql=(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))(Ql||{}),Mne=U.z.enum(Ql),Xl=(e=>(e.Binary="BINARY",e.IncrementalNegRisk="INCREMENTAL_NEGRISK",e.AtomicNegRisk="ATOMIC_NEGRISK",e))(Xl||{}),Fne=U.z.enum(Xl),Jl=(e=>(e.Reported="reported",e.Derived="derived",e))(Jl||{}),qne=U.z.enum(Jl),Zl=(e=>(e.UmaOptimisticOracle="UMA_OO",e.Chainlink="CHAINLINK",e.Eoa="EOA",e))(Zl||{}),Hne=U.z.enum(Zl),U$=U.z.number().int().min(0).transform(String).pipe(bn),$ne=U.z.object({question_id:vo.optional(),condition_id:xe.optional(),status:Mne,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:Yi,market_type:Fne.optional(),payouts:U.z.tuple([U$,U$]).optional(),resolution_source:qne.optional(),reporter:Hne.optional(),was_arbitrated:U.z.boolean().optional(),resolved_block:U.z.number().int().min(0).optional(),resolved_at:re.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}),m4=si(U.z.array($ne))});var Pe,Od,h4,g0,f4,Ir,RNe,Vne,Ld,g4,jne,y4,Wne,zne,Gne,Kne,Yne,b4,ZC,w4,v4,k4=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||{}),h4=Pe.z.object({status:Pe.z.enum(Od),transactionHash:et.nullish().transform(e=>e??null),transactionId:Ji}),g0=(e=>(e.PENDING="PENDING",e.FENCED="FENCED",e.SWEPT="SWEPT",e.CHAIN_SUBMITTED="CHAIN_SUBMITTED",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED",e))(g0||{}),f4=Pe.z.object({status:Pe.z.enum(g0),transactionId:Ji}),Ir=(e=>(e.SAFE="SAFE",e.PROXY="PROXY",e.SAFE_CREATE="SAFE-CREATE",e.WALLET="WALLET",e.WALLET_CREATE="WALLET-CREATE",e))(Ir||{}),RNe=Pe.z.enum(Ir),Vne=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||{}),g4=Pe.z.enum(Ld),jne=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()}),y4=Pe.z.object({address:J,nonce:Pe.z.string().min(1)}),Wne=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:jne,to:J,type:Vne,value:Pe.z.string().optional()}),zne=Pe.z.object({data:Pe.z.string().min(1),target:J,value:Pe.z.string().min(1)}),Gne=Pe.z.object({calls:Pe.z.array(zne).min(1),deadline:Pe.z.string().min(1),depositWallet:J}),Kne=Pe.z.object({depositWalletParams:Gne,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")}),Yne=Pe.z.object({from:J,metadata:Pe.z.string().optional(),to:J,type:Pe.z.literal("WALLET-CREATE")}),b4=Pe.z.union([Wne,Kne,Yne]),ZC=Pe.z.object({state:g4,transactionHash:et.nullish().transform(e=>e??null),transactionID:Ji}).transform(({transactionHash:e,transactionID:t,...n})=>({...n,transactionHash:e??null,transactionId:t})),w4=Pe.z.object({deployed:Pe.z.boolean()}),v4=Pe.z.object({error_msg:Pe.z.string().nullish(),state:g4,transaction_hash:Pe.z.union([Pe.z.literal(""),et]).transform(e=>e===""?null:e),transaction_id:Ji}).transform(({error_msg:e,transaction_hash:t,transaction_id:n,...r})=>({...r,errorMsg:e??null,transactionHash:t??null,transactionId:n}))});var ee,Nn,Eo,ds,ps,Xr,Cr,tN,nN,Qne,Xne,Jne,Zne,x4,ere,tre,nre,rre,ore,sre,ire,are,lre,cre,ure,A4,mn,li,ci,Ro,T4,dre,pre,mre,hre,fre,S4,rN,oN,Dd,gre,yre,eN,bre,P4,E4,R4,y0=L(()=>{"use strict";CC();xo();ee=require("zod");Al();Nn=(e=>(e.Buy="BUY",e.Sell="SELL",e))(Nn||{}),Eo=(e=>(e.Yes="YES",e.No="NO",e))(Eo||{}),ds=(e=>(e.Confirm="CONFIRM",e.Decline="DECLINE",e))(ds||{}),ps=(e=>(e.Matched="MATCHED",e.Mined="MINED",e.Confirmed="CONFIRMED",e.Retrying="RETRYING",e.Failed="FAILED",e))(ps||{}),Xr=(e=>(e.Notional="notional",e.Shares="shares",e))(Xr||{}),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||{}),tN=ee.z.enum(Nn),nN=ee.z.literal("YES"),Qne=ee.z.enum(ds),Xne=ee.z.enum(ps),Jne=ee.z.string().transform(e=>e),Zne=ee.z.object({id:Qi,condition_id:xe,position_ids:ee.z.array(Xe),pending:ee.z.boolean(),slug:ee.z.string(),title:ee.z.string(),outcomes:ee.z.array(ee.z.string()),outcome_prices:ee.z.array(R),image:ee.z.string(),volume:ee.z.number(),tags:ee.z.array(ee.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})),x4=ee.z.object({markets:ee.z.array(Zne),next_cursor:ye.nullish()}).transform(e=>({markets:e.markets,nextCursor:e.next_cursor??void 0})),ere=ee.z.discriminatedUnion("unit",[ee.z.object({unit:ee.z.literal("notional"),value_e6:bn}),ee.z.object({unit:ee.z.literal("shares"),value_e6:bn})]).transform(e=>({unit:e.unit,value:e.value_e6})),tre=(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))(tre||{}),nre=ee.z.object({type:ee.z.literal("auth"),success:ee.z.boolean(),address:J.optional(),role:ee.z.string().optional(),error:ee.z.string().optional()}),rre=ee.z.object({type:ee.z.literal("RFQ_REQUEST"),rfq_id:ar,requestor_public_id:Rw,leg_position_ids:ee.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:tN,side:nN,requested_size:ere,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})),ore=ee.z.object({type:ee.z.literal("ACK_RFQ_QUOTE"),rfq_id:ar,quote_id:Xi}).transform(e=>({quoteId:e.quote_id,rfqId:e.rfq_id,type:"quote_ack"})),sre=ee.z.object({type:ee.z.literal("ACK_RFQ_QUOTE_CANCEL"),rfq_id:ar,quote_id:Xi}).transform(e=>({quoteId:e.quote_id,rfqId:e.rfq_id,type:"quote_cancel_ack"})),ire=ee.z.object({type:ee.z.literal("RFQ_CONFIRMATION_REQUEST"),rfq_id:ar,quote_id:Xi,signer_address:J,maker_address:J,signature_type:IC,leg_position_ids:ee.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:tN,side:nN,fill_size_e6:bn,price_e6:bn,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})),are=ee.z.object({type:ee.z.literal("ACK_RFQ_CONFIRMATION_RESPONSE"),rfq_id:ar,quote_id:Xi,decision:Qne}).transform(e=>({decision:e.decision,quoteId:e.quote_id,rfqId:e.rfq_id,type:"confirmation_ack"})),lre=ee.z.object({type:ee.z.literal("RFQ_EXECUTION_UPDATE"),rfq_id:ar,status:Xne,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"})),cre=ee.z.object({type:ee.z.literal("RFQ_TRADE"),rfq_id:ar,requester_id:Rw,condition_id:Zt,leg_position_ids:ee.z.array(Xe),direction:tN,side:nN,price_e6:bn,size_e6:bn,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"})),ure=ee.z.object({type:ee.z.literal("RFQ_ERROR"),error_id:ee.z.string().optional(),request_type:ee.z.string().optional(),rfq_id:ar.optional(),quote_id:Xi.optional(),code:Jne,error:ee.z.string(),request:ee.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"})),A4=ee.z.discriminatedUnion("type",[nre,rre,ore,sre,ire,are,lre,cre,ure]),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||{}),T4=ee.z.object({code:ee.z.string().transform(e=>e),message:ee.z.string()}).transform(e=>({code:e.code,message:e.message})),dre=ee.z.object({quote_id:Xi,blended_price_e6:bn,maker_amount_e6:bn,taker_amount_e6:bn,total_required_e6:bn,net_receive_e6:bn.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}})),pre=ee.z.object({unit:ee.z.enum(Xr),value_e6:ee.z.string().regex(/^\d+$/).transform(e=>BigInt(e).toString())}).transform(e=>({unit:e.unit,valueE6:e.value_e6})),mre=ee.z.object({rfq_id:ar,leg_position_ids:ee.z.array(Xe),condition_id:Zt,yes_position_id:Xe,no_position_id:Xe,direction:ee.z.enum(Nn),side:ee.z.enum(Eo),requested_size:pre}).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})),hre=ee.z.object({rfq_id:ar,status:ee.z.literal("AWAITING_REQUESTER_ACCEPTANCE"),expires_at:pe,builder_code:bo,request:mre,quote:dre}).transform(e=>({builderCode:e.builder_code,expiresAt:e.expires_at,quote:e.quote,request:e.request,rfqId:e.rfq_id,status:e.status})),fre=ee.z.object({rfq_id:ar,status:ee.z.enum(["FAILED","EXPIRED","CANCELED"]),error:T4.optional()}).transform(e=>({rfqId:e.rfq_id,status:e.status,...e.error===void 0?{}:{error:e.error}})),S4=ee.z.union([hre,fre]),rN=ee.z.object({rfq_id:ar,status:ee.z.union([ee.z.enum(mn),ee.z.enum(ps)]),taker_order_hash:ee.z.string().optional(),tx_hash:et.optional(),error:T4.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}})),oN=ee.z.string().transform(e=>Wn(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||{}),gre=ee.z.string().transform(e=>e),yre=ee.z.object({kind:gre,condition_id:Zt.optional(),event_id:Gt.optional(),position_id:Xe.optional(),condition_index:ee.z.number().int().nonnegative().optional().default(0),amount:bn}).transform(e=>({amount:e.amount,conditionId:e.condition_id,conditionIndex:e.condition_index,eventId:e.event_id,kind:e.kind,positionId:e.position_id})),eN=ee.z.object({position_id:Xe,amount:bn}).transform(e=>({amount:e.amount,positionId:e.position_id})),bre=ee.z.object({consumed:ee.z.array(eN),created:ee.z.array(eN)}).transform(e=>({consumed:e.consumed,created:e.created})),P4=ee.z.object({to:J,data:oN}).transform(e=>({data:e.data,to:e.to})),E4=ee.z.looseObject({planHash:oN,chainId:ee.z.number().int(),wallet:J,routerCall:P4}),R4=ee.z.object({plan_hash:oN,chain_id:ee.z.number().int(),wallet:J,block_number:ee.z.string().regex(/^\d+$/).transform(BigInt),starting_pusd:R,net_pusd_out:R,final_pusd:R,operations:ee.z.array(yre),operation_count:ee.z.number().int(),truncated:ee.z.boolean(),estimated_cost:ee.z.number(),required_pusd_input:R,required_positions:ee.z.array(eN),position_summary:bre.optional(),candidate_position_ids:ee.z.array(Xe),router_call:P4}).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 ec,_4,sN,wre,I4,iN=L(()=>{"use strict";PC();xo();ec=require("zod"),_4=ec.z.number().int().transform(e=>e===0?null:pd(e)),sN=ec.z.object({status:ec.z.literal("ok"),deadline:_4}),wre=ec.z.object({deadline:_4,triggered:ec.z.number().int().nonnegative(),daily_limit:ec.z.number().int().nonnegative(),next_reset:pe}).transform(e=>({deadline:e.deadline,triggered:e.triggered,dailyLimit:e.daily_limit,nextReset:e.next_reset})),I4=wre});function C4(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 vre(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 Are(e,t,n){kre.encodeInto(e,t.subarray(n))}function N4(e,t,n){e.length>xre?Are(e,t,n):vre(e,t,n)}var kre,xre,qNe,O4=L(()=>{"use strict";kre=new TextEncoder,xre=50;qNe=new TextDecoder});var tc,L4=L(()=>{"use strict";tc=class{type;data;constructor(t,n){this.type=t,this.data=n}}});var b0,D4=L(()=>{"use strict";b0=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 U4(e,t,n){let r=n/4294967296,o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function w0(e,t,n){let r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function B4(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}var aN=L(()=>{"use strict"});function Ere({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=Pre)if(t===0&&e<=Sre){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),w0(r,4,e),n}}function Rre(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 _re(e){if(e instanceof Date){let t=Rre(e);return Ere(t)}else return null}function Ire(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=B4(t,4),r=t.getUint32(0);return{sec:n,nsec:r}}default:throw new b0(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function Cre(e){let t=Ire(e);return new Date(t.sec*1e3+t.nsec/1e6)}var Tre,Sre,Pre,M4,F4=L(()=>{"use strict";D4();aN();Tre=-1,Sre=4294967296-1,Pre=17179869184-1;M4={type:Tre,encode:_re,decode:Cre}});var v0,q4=L(()=>{"use strict";L4();F4();v0=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(M4)}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 tc(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 tc(i,s)}}}return t instanceof tc?t:null}decode(t,n,r){let o=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return o?o(t,n,r):new tc(n,t)}}});function Nre(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function H4(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Nre(e)?new Uint8Array(e):Uint8Array.from(e)}var $4=L(()=>{"use strict"});var Ore,Lre,k0,V4=L(()=>{"use strict";O4();q4();aN();$4();Ore=100,Lre=2048,k0=class e{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??v0.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??Ore,this.initialBufferSize=t?.initialBufferSize??Lre,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=C4(t);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),N4(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=H4(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),U4(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),w0(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 lN(e,t){return new k0(t).encodeSharedRef(e)}var j4=L(()=>{"use strict";V4()});var W4=L(()=>{"use strict";j4()});function ui(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}var cN=L(()=>{"use strict"});var x0,Ud,z4=L(()=>{"use strict";x0=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 x0(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 x0(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 Dre(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 Dre(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(A){w(A)}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,A;w!=null&&(v=new Promise((k,T)=>{A=()=>{T(new uN)},w.addEventListener("abort",A)}));try{await Promise.race([a.promise,v])}finally{A!=null&&w!=null&&w?.removeEventListener("abort",A)}}},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 uN,dN=L(()=>{"use strict";cN();z4();uN=class extends Error{type;code;constructor(t,n){super(t??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}});function Ure(e){return e.reason}function G4(e,t,n){if(t==null||e==null)return e;let r=n?.translateError??Ure;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 K4=L(()=>{"use strict"});function Y4(){return new pN}var pN,Q4=L(()=>{"use strict";cN();K4();pN=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 G4(this.readNext.promise,n?.signal,n)}}});function X4(e){return e[Symbol.asyncIterator]!=null}async function Bre(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*Mre(e){let t=new AbortController,n=Y4(),r=e.map(o=>X4(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());Bre(r,n,t.signal).catch(()=>{});try{yield*n}finally{t.abort();for(let o of r)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*Fre(e){for(let t of e)yield*t}function qre(...e){let t=[];for(let n of e)X4(n)||t.push(n);return t.length===e.length?Fre(t):Mre(e)}var J4,Z4=L(()=>{"use strict";Q4();J4=qre});function M(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 Hre(JSON.stringify(e))}function _o(e,t,n="Invalid pagination cursor"){try{return t.parse(JSON.parse(I6(e)))}catch(r){throw new E(n,{cause:r})}}function _6(e){try{return JSON.parse(I6(e))}catch{return}}function Hre(e){return btoa(String.fromCharCode(...new TextEncoder().encode(e)))}function I6(e){return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}function sa(e){return di(C6.parse(e))}function Md(e,t,n={}){return e===void 0?{offset:0,pageSize:t}:N6(_o(e,h.z.unknown()),n)}function N6(e,t={}){let n=C6.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 Nl(`Pagination reached this listing's supported depth limit (${t.maxOffset}); whether more items exist cannot be established.`);return r}function O6(e,t){return di({kind:"keyset",fingerprint:D6(t),cursor:e})}function L6(e,t){if(!Vre(e))return;let n=$re.safeParse(e);if(!n.success)throw new E("Invalid pagination cursor",{cause:n.error});if(t===void 0||n.data.fingerprint!==D6(t))throw new E("Pagination cursor was created for a different query");return n.data.cursor}function Vre(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="keyset"}function D6(e){return JSON.stringify(wN(e))}function wN(e){return Array.isArray(e)?e.map(wN):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,wN(n)])):e}function W(e){return function(t){return In.fromPromise(t.json(),()=>new C(`Received non-JSON response from ${t.url}`)).andThen(n=>Wre(t.url,e,n))}}function jre(e){return In.fromPromise(e.blob(),()=>new C(`Received unreadable binary response from ${e.url}`))}function Wre(e,t,n){let r=t.safeParse(n);return r.success?go(r.data):Sr(C.fromZodError(r.error,{endpoint:e}))}function zre(e){if(!(e instanceof O)||!U6(e.cause))return!1;let t=[e.cause.message,Gre(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 e6(e){return!B6(e)||e.jsonrpc!=="2.0"?!1:"error"in e?U6(e.error):"result"in e}function U6(e){return B6(e)&&typeof e.code=="number"&&typeof e.message=="string"}function B6(e){return typeof e=="object"&&e!==null}function M6(e){return/^0x[a-fA-F0-9]*$/.test(e)}function t6(e,t="eth_call"){if(typeof e!="string"||!M6(e))throw new C(`Expected JSON-RPC ${t} result to be a hex string`);return e}function n6(e){return`0x${e.toString(16)}`}function Gre(e){if(e===void 0)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function F6(e,t,n){let r=foe(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 rc(e){let t=pi(e.walletType);return{maker:e.wallet,signatureType:t,signer:t===Rr.POLY_1271?e.wallet:e.signer}}function O0(e,t){return e.signerType==="OWNER"?t:Qre(e.signer,t)}function Qre(e,t){let n=Wn(`0x${e.slice(2).padStart(64,"0")}`),r=Wt.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes"}],[n,Kre,t]);return cq(`${r}${Yre.slice(2)}`)}function Jre(e){let t=Xre.replace("%s",e.proxyFactory.slice(2).toLowerCase()).replace("%s",e.proxyImplementation.slice(2).toLowerCase());return Wn(Je.keccak256(`0x${t}`))}function Zre(e,t){return Be(ho.fromCreate2({bytecodeHash:Jre(t),from:t.proxyFactory,salt:Je.keccak256(Wt.encodePacked(["address"],[e]))}))}function eoe(e,t){return Be(ho.fromCreate2({bytecodeHash:t.safeInitCodeHash,from:t.safeFactory,salt:Je.keccak256(Wt.encode([{name:"address",type:"address"}],[e]))}))}function L0(e,t){let n=Wn(`0x${e.slice(2).padStart(64,"0")}`),r=Wt.encode([{type:"address"},{type:"bytes32"}],[t.depositWalletFactory,n]);return Be(ho.fromCreate2({bytecodeHash:coe(t.depositWalletImplementation,r),from:t.depositWalletFactory,salt:Je.keccak256(r)}))}function Pf(e,t){let n=Wn(`0x${e.slice(2).padStart(64,"0")}`),r=Wt.encode([{type:"address"},{type:"bytes32"}],[t.depositWalletFactory,n]);return Be(ho.fromCreate2({bytecodeHash:uoe(t.depositWalletBeacon,r),from:t.depositWalletFactory,salt:Je.keccak256(r)}))}function coe(e,t){let n=BigInt((t.length-2)/2),r=roe+(n<<56n);return Wn(Je.keccak256(we.concat(we.fromNumber(r,{size:10}),we.fromHex(e),we.fromHex("0x6009"),we.fromHex(noe),we.fromHex(toe),we.fromHex(t)),{as:"Hex"}))}function uoe(e,t){let n=BigInt((t.length-2)/2),r=aoe+(n<<56n);return Wn(Je.keccak256(we.concat(we.fromNumber(r,{size:10}),we.fromHex(e),we.fromHex(ioe),we.fromHex(soe),we.fromHex(ooe),we.fromHex(t)),{as:"Hex"}))}async function doe(e,t){try{let n=await e.ethCall({to:t,data:loe});return hoe(n)}catch(n){if(zre(n))return rs;throw n}}async function poe(e,t){let n=await doe(e,t);return!zt(n,rs)}async function moe(e,t,n){return await poe(e,n.depositWalletFactory)?Pf(t,n):L0(t,n)}function hoe(e){return e.length<66?rs:Be(`0x${e.slice(-40)}`)}function foe(e,t,n){if(zt(n,t))return{signerType:"OWNER",walletType:Se.EOA};let r=e.walletDerivation;return zt(n,Pf(t,r))?{signerType:"OWNER",walletType:Se.DEPOSIT_WALLET}:zt(n,L0(t,r))?{signerType:"OWNER",walletType:Se.DEPOSIT_WALLET}:zt(n,eoe(t,r))?{signerType:"OWNER",walletType:Se.GNOSIS_SAFE}:zt(n,Zre(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:q6,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:q6.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(yoe(t))return boe(e,t.exceptions);let n=new URLSearchParams;for(let[r,o]of Object.entries(t)){let s=e[r];if(s!==void 0){if(DN(s)){for(let i of s)n.append(o,ia(i));continue}n.append(o,ia(s))}}return n}function Ee(e={}){return{format:"snake_case",exceptions:e}}function goe(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(ia).join(","));continue}t.append(n,ia(r))}return t}function aa(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=$6(n);if(DN(r)){t.append(o,r.map(ia).join(","));continue}t.append(o,ia(r))}return t}function yoe(e){return"format"in e}function boe(e,t){let n=new URLSearchParams;for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=t[r]??$6(r);if(DN(o)){for(let i of o)n.append(s,ia(i));continue}n.append(s,ia(o))}return n}function DN(e){return Array.isArray(e)}function $6(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ia(e){return String(e)}async function B0(e){return(await X(e.secureClob.get("/auth/ban-status/closed-only").andThen(W(b3)))).closedOnly}function F0(e,t){let n=M(t,voe),{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(W(w3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function H0(e,t){let n=M(t,koe);return X(e.secureClob.get(`/data/order/${n.orderId}`).andThen(W(NC)))}function Ef(e,t){let n=M(t,Aoe),{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(W(v3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),r)}async function j0(e){let t=pi(e.account.walletType);return X(e.secureClob.get("/notifications",{params:ve({signatureType:t},Ee())}).andThen(W(G3)))}async function z0(e,t){let n=M(t,Toe),r=pi(e.account.walletType),o=ve({ids:n.ids.join(","),signatureType:r},Ee());await X(e.secureClob.del("/notifications",{params:o}))}async function G0(e,t){let n=M(t,Soe),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(W(x3)))}async function UN(e,t){let n=M(t,Poe),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})),G0(e,n)}async function Y0(e,t){let n=M(t,Eoe);return(await X(e.secureClob.get("/order-scoring",{params:ve(n,Ee())}).andThen(W(A3)))).scoring}async function X0(e,t){let n=M(t,Roe).orderIds;return X(e.secureClob.post("/orders-scoring",{json:n}).andThen(W(T3)))}function Z0(e,t){let{cursor:n,...r}=M(t,z6),o=pi(e.account.walletType);return Fe(s=>e.secureClob.get("/rewards/user",{params:ve({...r,nextCursor:s,signatureType:o},Ee())}).andThen(W(S3)).map(i=>({items:i.data,hasMore:i.nextCursor!==Yn,nextCursor:i.nextCursor===Yn?void 0:i.nextCursor})),n)}async function tv(e,t){let n=M(t,z6),r=pi(e.account.walletType);return X(e.secureClob.get("/rewards/user/total",{params:ve({...n,signatureType:r},Ee())}).andThen(W(P3)))}function rv(e,t){let{cursor:n,...r}=M(t,_oe),o=pi(e.account.walletType);return Fe(s=>e.secureClob.get("/rewards/user/markets",{params:ve({...r,nextCursor:s,signatureType:o},Ee())}).andThen(W(R3)).map(i=>({items:i.data,hasMore:i.nextCursor!==Yn,nextCursor:i.nextCursor===Yn?void 0:i.nextCursor})),n)}async function sv(e){let t=pi(e.account.walletType);return X(e.secureClob.get("/rewards/user/percentages",{params:ve({signatureType:t},Ee())}).andThen(W(E3)))}function nn(e,t={}){let{retries:n=2,maxDelaySeconds:r=5,sleep:o=os}=t;function s(i){return e().orElse(a=>{if(!(a instanceof $)||i<=0)return xl(a);let l=a.retryAfter??1;return l>r?xl(a):In.fromSafePromise(o(l*1e3).catch(()=>{})).andThen(()=>s(i-1))})}return s(n)}function av(e,t={}){let{cursor:n,pageSize:r,window:o,...s}=M(t,Ioe);return Fe(i=>nn(()=>e.data.get("/v2/trades",{params:tn({...s,...o,limit:r,cursor:i})})).andThen(W(J$)),n)}function Rf(e,t){let{cursor:n,pageSize:r,window:o,...s}=M(t,Coe);return Fe(i=>nn(()=>e.data.get("/v2/activity",{params:tn({...s,...o,excludeDepositsWithdrawals:!1,limit:r,cursor:i})})).andThen(W(Z$)),n)}function _f(e,t){let{cursor:n,pageSize:r,...o}=M(t,Noe);return Fe(s=>nn(()=>e.data.get("/v2/activity/combos",{params:tn({...o,limit:r,cursor:s})})).andThen(W(e4)),n)}function vf(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:Joe(t,n),to:e}}function MN(e,t,n){return{data:Ie.encodeData(G6,[t,n]),to:e}}function FN(e){return Ie.decodeResult(G6,e)}function kf(e,t,n){return{data:Zoe(t,n),to:e}}function qN(e,t,n){return{data:Ie.encodeData(K6,[t,n]),to:e}}function HN(e){return Ie.decodeResult(K6,e)}function $N(e,t,n){return{data:Ie.encodeData(Y6,[t,hs(BigInt(n),"Position ID")]),to:e}}function VN(e){return Ie.decodeResult(Y6,e)}function If(e,t,n){return{data:Ie.encodeData(Q6,[n.map(()=>t),n.map(r=>hs(BigInt(r),"id"))]),to:e}}function Cf(e){return Ie.decodeResult(Q6,e)}function P0(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:ese(t,n),to:e}}function jN(e,t,n){return{data:Ie.encodeData(Moe,[t,hs(n,"Session key expiry")]),to:e}}function WN(e,t){return{data:Ie.encodeData(Foe,[t]),to:e}}function zN(e,t,n,r){if(n<=0n)throw new E("Perps deposit amount must be positive");return{data:Ie.encodeData(qoe,[t,hs(n,"Perps deposit amount"),r]),to:e}}function GN(e,t,n,r){return{data:tse(t,n,r),to:e}}function KN(e,t,n,r){return{data:nse(t,n,r),to:e}}function YN(e,t,n){return{data:rse(t,n),to:e}}function uv(e,t,n){return{data:Ie.encodeData(Woe,[QN(t),hs(n,"Split amount")]),to:e}}function dv(e,t,n){return{data:Ie.encodeData(zoe,[QN(t),hs(n,"Merge amount")]),to:e}}function xf(e,t,n,r){return{data:Ie.encodeData(Goe,[QN(t),BigInt(ose(n)),hs(r,"Redeem amount")]),to:e}}function pv(e,t){return{data:Ie.encodeData(Koe,[t.map(n=>hs(n,"Leg position ID"))]),to:e}}function Joe(e,t){return fe(t>=0n,"Approval amount must be non-negative"),Ie.encodeData(Uoe,[e,t])}function Zoe(e,t){return Ie.encodeData(Hoe,[e,t])}function ese(e,t){return Ie.encodeData(Boe,[e,t])}function tse(e,t,n){return Ie.encodeData($oe,[e,BN,t,X6,hs(n,"Split amount")])}function nse(e,t,n){return Ie.encodeData(Voe,[e,BN,t,X6,hs(n,"Merge amount")])}function rse(e,t){return Ie.encodeData(joe,[e,BN,t,Xoe])}function hs(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 QN(e){if(Loe.test(e))return e.toLowerCase();if(Doe.test(e)){let t=e.toLowerCase();if(t.endsWith("00")||t.endsWith("01"))return t.slice(0,Ooe)}throw new E("Protocol v2 condition ID must be bytes31, or bytes32 with a binary outcome byte")}function ose(e){if(e!==0&&e!==1)throw new E("Protocol v2 outcome index must be 0 or 1");return e}function XN(e){return Ie.encodeData(Qoe,[e.map(t=>({typeCode:1,to:t.to,value:t.value??0n,data:t.data}))])}function JN(e){let t=e.map(n=>sse(n));return Ie.encodeData(Yoe,[t.length===0?"0x":Wt.encodePacked(Array.from({length:t.length},()=>"bytes"),t)])}function sse(e){let t=e.value??0n;return Wt.encodePacked(["uint8","address","uint256","uint256","bytes"],[0,e.to,t,BigInt((e.data.length-2)/2),e.data])}function wn(e,t="Expected a TransactionHandle"){return fe(typeof e=="object"&&e!==null&&"transactionHash"in e&&"transactionId"in e&&"wait"in e&&typeof e.wait=="function",t),e}function c8(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 vn(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 ZN(){return{kind:"requestAddress"}}function Qn(e,t){return{chainId:e,...t}}async function Nf(e,t){let n=M(t,mse);return X(e.relayer.get("/v1/account/transactions/params",{params:ve(n,{address:"address",type:"type"})}).andThen(W(y4)))}async function Of(e,t){let n=await gse(e,t);return n.type===Se.EOA?!1:X(e.relayer.get("/deployed",{params:ve({address:n.wallet,type:n.type===Se.DEPOSIT_WALLET?Ir.WALLET:void 0},{address:"address",type:"type"})}).andThen(W(w4)).map(({deployed:r})=>r))}async function gse(e,t){if(t!==void 0)return M(t,fse);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 moe(e.rpc,e.account.signer,e.environment.walletDerivation),type:Se.DEPOSIT_WALLET}}async function mv(e){return fe(e.supportsGasless,"Deposit Wallet deployment requires a Relayer API Key or Builder API Key in the client configuration."),Af(e,{from:e.account.signer,metadata:"Deploy Deposit Wallet",to:e.environment.walletDerivation.depositWalletFactory,type:Ir.WALLET_CREATE})}async function eO(e,t){let n=M(t,hse);return X(e.relayer.get(`/v1/account/transactions/${n.transactionId}`).andThen(W(v4)))}async function Or(e,t){let n=M(t,bse);return fe(e.supportsGasless,"Gasless transactions require a Relayer API Key or Builder API Key in the client configuration."),fe(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 ZN());fe(r===e.account.signer,"Wallet client address does not match the authenticated signer");for(let o=0;o<=r6;o+=1)try{switch(e.account.walletType){case Se.POLY_PROXY:return yield*wse(e,n);case Se.DEPOSIT_WALLET:return yield*vse(e,n);case Se.GNOSIS_SAFE:return yield*kse(e,n)}fe(!1,"Unsupported wallet type for gasless transaction")}catch(s){if(!bv(s)||o===r6)throw s;await os(e.environment.relayerPollFrequencyMs)}fe(!1,"Expected gasless transaction retry loop to return")}.call(null)}async function*wse(e,t){let n=yield*hv(e,t.calls,t.metadata);return Af(e,n)}async function*hv(e,t,n){let r=await Nf(e,{address:e.account.signer,type:Ir.PROXY}),o=e.environment.walletDerivation.proxyFactory,s=XN(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=Sse(e.account.signer,o,s,i,a,l,r.nonce,c,u),p=ss(yield g8(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:Ir.PROXY}}function fv(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*vse(e,t){let n=yield*qd(e,t.calls,t.metadata);try{return await Af(e,n)}catch(r){let o=fv(r);if(o===void 0)throw r;let s=yield*gv(e,n,t.calls,o);return Af(e,s)}}async function*qd(e,t,n){let r=await Nf(e,{address:e.account.signer,type:Ir.WALLET}),o=t.map(h8),s=`${Math.floor(Date.now()/1e3)+use}`,i=O0(e.account,ss(yield y8(f8({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:Ir.WALLET}}async function*gv(e,t,n,r){let o=O0(e.account,ss(yield y8(f8({calls:n.map(h8),chainId:e.environment.chainId,deadline:t.depositWalletParams.deadline,nonce:r,wallet:e.account.wallet}))));return{...t,nonce:r,signature:o}}async function*kse(e,t){let n=yield*yv(e,t.calls,t.metadata);return Af(e,n)}async function*yv(e,t,n){let r=await Nf(e,{address:e.account.signer,type:Ir.SAFE}),o=xse(t,e.environment.contracts.safeMultisend),s=Tse({chainId:e.environment.chainId,data:o.data,nonce:r.nonce,operation:o.operation,safeAddress:e.account.wallet,to:o.to,value:o.value}),i=ss(yield g8(Wn(fo.getSignPayload(s))));return{data:o.data,from:e.account.signer,...n!==void 0&&{metadata:n},nonce:r.nonce,proxyWallet:e.account.wallet,signature:Pse(i),signatureParams:Ase(o.operation),to:o.to,type:Ir.SAFE,value:o.value>0n?`${o.value}`:void 0}}async function Af(e,t){let n=M(t,b4),r=await X(e.relayer.post("/submit",{json:n}).andThen(W(ZC)));return new Lf(e,r)}function bv(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 h8(e){return{data:e.data,target:e.to,value:`${e.value??0n}`}}function f8(e){let t={chainId:e.chainId,name:lse,verifyingContract:e.wallet,version:cse};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:pse,Call:dse,EIP712Domain:fo.extractEip712DomainTypes(t)}}}function xse(e,t){if(e.length===1){let[n]=e;return{data:n.data,operation:0,to:n.to,value:n.value??0n}}return{data:JN(e),operation:1,to:t,value:0n}}function Ase(e){return{baseGas:"0",gasPrice:"0",gasToken:rs,operation:`${e}`,refundReceiver:rs,safeTxnGas:"0"}}function Tse(e){return{domain:{chainId:e.chainId,verifyingContract:e.safeAddress},message:{baseGas:0n,data:e.data,gasPrice:0n,gasToken:rs,nonce:BigInt(e.nonce),operation:e.operation,refundReceiver:rs,safeTxGas:0n,to:e.to,value:e.value},primaryType:"SafeTx",types:{EIP712Domain:ise,SafeTx:ase}}}function g8(e){return{kind:"signGaslessMessage",payload:e}}function y8(e){return{kind:"signGaslessTypedData",payload:e}}function Sse(e,t,n,r,o,s,i,a,l){return Wn(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 Pse(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 Wn(`0x${t.slice(0,128)}${r.toString(16).padStart(2,"0")}`)}async function tO(e,t){let n=M(t,Ese),r=n.amount==="max"?lr:n.amount;return async function*(){return e.account.walletType===Se.EOA?wn(yield A8(Qn(e.environment.chainId,vf(n.tokenAddress,n.spenderAddress,r)))):yield*await Or(e,{calls:[vf(n.tokenAddress,n.spenderAddress,r)],metadata:n.metadata??`Approve ${n.amount} of ${n.tokenAddress} to ${n.spenderAddress}`})}.call(null)}function Df(e,t){return tO(e,t).then(vn(e.signer))}async function nO(e,t){let n=M(t,Rse);return async function*(){return e.account.walletType===Se.EOA?wn(yield T8(Qn(e.environment.chainId,kf(n.tokenAddress,n.operatorAddress,n.approved)))):yield*await Or(e,{calls:[kf(n.tokenAddress,n.operatorAddress,n.approved)],metadata:n.metadata??`${n.approved?"Approve":"Revoke"} ${n.operatorAddress} on ${n.tokenAddress}`})}.call(null)}function Uf(e,t){return nO(e,t).then(vn(e.signer))}async function Bf(e,t){let{user:n}=M(t,_se),r=await x8(e,n);return{isFullyApproved:r.erc20.length===0&&r.erc1155.length===0,missing:r}}async function rO(e){let t=await x8(e,e.account.wallet),n=t.erc20.map(o=>vf(o.tokenAddress,o.spenderAddress,o.amount)),r=t.erc1155.map(o=>kf(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 wn(yield A8(Qn(e.environment.chainId,o))).wait();for(let o of r)await wn(yield T8(Qn(e.environment.chainId,o))).wait();return}await(yield*await Or(e,{calls:[...n,...r],metadata:"Trading setup approvals"})).wait()}}.call(null)}function Av(e){return rO(e).then(vn(e.signer)).then(()=>{})}async function x8(e,t){let n=Ise(e),r=[...n.erc20.map(a=>MN(a.tokenAddress,t,a.spenderAddress)),...n.erc1155.map(a=>qN(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)=>FN(s[l])<a.amount),erc1155:n.erc1155.filter((a,l)=>!HN(i[l]))}}catch(a){throw new C("Expected JSON-RPC approval checks to return ABI-encoded values",{cause:a})}}function Ise(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 A8(e){return{kind:"sendErc20ApprovalTransaction",request:e}}function T8(e){return{kind:"sendErc1155ApprovalForAllTransaction",request:e}}async function oO(e,t){return X(e.clob.post("/auth/api-key",{headers:U8(t)}).andThen(W(OC)))}async function sO(e,t){return X(e.clob.get("/auth/derive-api-key",{headers:U8(t)}).andThen(W(OC)))}async function Tv(e,t){try{return await oO(e,t)}catch(n){if(!(n instanceof O)||n.status!==400)throw n}return sO(e,t)}async function Sv(e){return(await X(e.secureClob.get("/auth/api-keys").andThen(W(_3)))).apiKeys}async function Pv(e){await X(e.secureClob.del("/auth/api-key").andThen(W(h.z.literal("OK"))))}async function C8(e){return X(e.secureClob.post("/auth/builder-api-key").andThen(W(I3)))}async function O8(e){return X(e.secureClob.get("/auth/builder-api-key").andThen(W(C3)))}async function D8(e){await X(e.clob.del("/auth/builder-api-key").andThen(W(h.z.literal("OK"))))}function U8(e){return{POLY_ADDRESS:e.address,POLY_NONCE:`${e.nonce}`,POLY_SIGNATURE:e.signature,POLY_TIMESTAMP:`${e.timestamp}`}}function Rv(e,t){let n=M(t,Nse),{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(W(N3)).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=M(t,Ose);return(await X(e.clob.get("/midpoint",{params:oc(n)}).andThen(W(D3)))).mid}async function Nv(e,t){let n=M(t,Lse);return X(e.clob.post("midpoints",{json:Jv(n)}).andThen(W(U3)))}async function M8(e,t){let n=M(t,Dse);return(await X(e.clob.get("/tick-size",{params:oc(n)}).andThen(W(t$)))).minimumTickSize}async function q8(e,t){let n=M(t,Use);return(await X(e.clob.get("/neg-risk",{params:oc(n)}).andThen(W(W3)))).negRisk}async function iO(e,t){let n=M(t,Bse);return X(e.clob.get(`/markets-by-token/${n.assetId??n.tokenId}`).andThen(W(V3)))}async function aO(e,t){let n=M(t,Mse);return X(e.clob.get(`/clob-markets/${n.conditionId}`).andThen(W(j3)))}async function lO(e,t){let n=M(t,Fse);return X(e.clob.get(`/fees/builder-fees/${n.builderCode}`).andThen(W(O3)).mapErr(r=>r instanceof O&&r.status===404?new E(`Unknown builder code: ${n.builderCode}`,{cause:r}):r))}async function Lv(e,t){let n=M(t,qse);return(await X(e.clob.get("/price",{params:oc(n)}).andThen(W(B3)))).price}async function Uv(e,t){let n=M(t,Hse);return X(e.clob.post("prices",{json:Qse(n)}).andThen(W(M3)))}async function Hd(e,t){let n=M(t,$se);return X(e.clob.get("/book",{params:oc(n)}).andThen(W(Y3)))}async function Fv(e,t){let n=M(t,Vse);return X(e.clob.post("books",{json:Jv(n)}).andThen(W(Q3)))}async function Hv(e,t){let n=M(t,jse);return(await X(e.clob.get("/spread",{params:oc(n)}).andThen(W(F3)))).spread}async function Vv(e,t){let n=M(t,Wse);return X(e.clob.post("spreads",{json:Jv(n)}).andThen(W(q3)))}async function Wv(e,t){let n=M(t,zse);return X(e.clob.get("/last-trade-price",{params:oc(n)}).andThen(W(H3)))}async function Gv(e,t){let n=M(t,Gse);return X(e.clob.post("last-trades-prices",{json:Jv(n)}).andThen(W($3)))}function Yv(e,t={}){let{cursor:n,...r}=M(t,Kse);return Fe(o=>e.clob.get("/rewards/markets/current",{params:ve({...r,nextCursor:o},Ee())}).andThen(W(J3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),n)}function Xv(e,t){let{cursor:n,...r}=M(t,Yse);return Fe(o=>e.clob.get(`rewards/markets/${r.conditionId}`,{params:ve({nextCursor:o,sponsored:r.sponsored},Ee())}).andThen(W(Z3)).map(s=>({items:s.data,hasMore:s.nextCursor!==Yn,nextCursor:s.nextCursor===Yn?void 0:s.nextCursor})),n)}function Jv(e){return e.map(t=>({token_id:t.assetId??t.tokenId}))}function Qse(e){return e.map(t=>({token_id:t.assetId??t.tokenId,side:t.side}))}function oc(e){let{assetId:t,tokenId:n,...r}=e;return ve({...r,tokenId:e.assetId??e.tokenId},Ee())}async function ek(e){return z8(e),X(e.combos.post("/v1/collateral-return/plan",{json:{wallet:e.account.wallet},timeout:j8}).andThen(W(R4)))}async function cO(e,t){let{plan:n}=M(t,Xse);if(fe(e.supportsGasless,"Collateral return execution requires a Relayer API Key or Builder API Key in the client configuration."),z8(e),!zt(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<=o6;o+=1)try{let s=yield*Jse(e,r);try{return await s6(e,n.planHash,s)}catch(i){let a=fv(i);if(a===void 0||s.type!==Ir.WALLET)throw i;let l=yield*gv(e,s,r,a);return await s6(e,n.planHash,l)}}catch(s){if(!bv(s)||o===o6)throw s;await os(e.environment.relayerPollFrequencyMs)}fe(!1,"Expected collateral return submit retry loop to return")}.call(null)}function nk(e,t){return cO(e,t).then(vn(e.signer))}function z8(e){fe(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 Jse(e,t){switch(e.account.walletType){case Se.GNOSIS_SAFE:return yv(e,t,mN);case Se.POLY_PROXY:return hv(e,t,mN);default:return qd(e,t,mN)}}async function s6(e,t,n){let r=await X(e.combos.post("/v1/collateral-return/submit",{json:{envelope:n,plan_hash:t},timeout:j8}).andThen(W(ZC)));return new Lf(e,r)}function rie(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=nie.safeParse(e.order);if(t.success)return{ascending:e.ascending??!0,order:t.data,parentEntityId:e.parentEntityId,parentEntityType:e.parentEntityType}}function ok(e,t){let{cursor:n,pageSize:r,...o}=M(t,Zse),s=rie(o);return Fe(i=>{if(i===void 0)return s===void 0?i6(e,o,{offset:0,pageSize:r}):a6(e,s,r);let a=_6(i);if(a===void 0)throw new E("Invalid pagination cursor");let l=L6(a,s);return l===void 0||s===void 0?i6(e,o,N6(a,G8)):a6(e,s,r,l)},n)}function i6(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(W(jh)).map(r=>{let o=r.filter(s=>s.parentCommentID==null).length>=n.pageSize;return{items:r,hasMore:o,limitReached:o&&n.offset+n.pageSize>dO,nextCursor:o?sa({offset:n.offset+n.pageSize,pageSize:n.pageSize}):void 0}})}function a6(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(W(TI)).map(o=>({items:o.items,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor===void 0?void 0:O6(o.nextCursor,t)}))}async function ik(e,t){let n=M(t,eie);return X(e.gamma.get(`comments/${n.id}`,{params:ve({getPositions:n.getPositions},Ee())}).andThen(W(jh)))}function lk(e,t){let{address:n,cursor:r,pageSize:o,...s}=M(t,tie);return Fe(i=>{let a=Md(i,o,G8);return e.gamma.get(`comments/user_address/${n}`,{params:ve({ascending:s.ascending,limit:a.pageSize,offset:a.offset,order:s.order},Ee())}).andThen(W(jh)).map(l=>{let c=l.length>=a.pageSize;return{items:l,hasMore:c,limitReached:c&&a.offset+a.pageSize>dO,nextCursor:c?sa({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},r)}function K8(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 uk(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,oie);return Fe(s=>e.gamma.get("/events/keyset",{params:pie({...o,pageSize:r,cursor:s===void 0?void 0:aie(s,o)})}).andThen(W(kI)).map(i=>({items:i.items,hasMore:i.nextCursor!==void 0,nextCursor:i.nextCursor===void 0?void 0:O6(i.nextCursor,o)})),n)}function aie(e,t){let n=_6(e);return n===void 0?e:L6(n,t)??e}async function pk(e,t){let n=M(t,sie);if("id"in n)return X(e.gamma.get(`events/${n.id}`,{params:mie(n)}).andThen(W(ei)));let r="url"in n?K8(n.url,"event"):n.slug;return X(e.gamma.get(`events/slug/${r}`,{params:hie(n)}).andThen(W(ei)))}async function hk(e,t){let n=M(t,iie);return X(e.gamma.get(`events/${n.id}/tags`).andThen(W(xI)))}async function gk(e,t){let{conditionIds:n,eventIds:r,questionId:o}=M(t,uie);return X(nn(()=>e.data.get("/v2/resolutions",{params:tn({questionId:o,condition:n,eventId:r})})).andThen(W(m4)))}async function bk(e,t){let{eventIds:n}=M(t,die);return X(nn(()=>e.data.get("/v2/live-volume",{params:tn({eventId:n})})).andThen(W(s4)))}function pie(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 mie(e){return ve({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},Ee())}function hie(e){return ve({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},Ee())}function vk(e,t={}){let{cursor:n,pageSize:r,window:o}=M(t,fie);return Fe(s=>nn(()=>e.data.get("/v2/builders/leaderboard",{params:tn({timePeriod:o,limit:r,cursor:s})})).andThen(W(l4)),n)}async function xk(e,t={}){let{interval:n,bucketLimit:r}=M(t,gie);return X(nn(()=>e.data.get("/v2/builders/volume",{params:tn({interval:n,limit:r})})).andThen(W(c4)))}function Tk(e,t={}){let{category:n,cursor:r,pageSize:o,sortBy:s,window:i}=M(t,yie);return Fe(a=>nn(()=>e.data.get("/v2/leaderboard",{params:tn({category:n,cursor:a,limit:o,sortBy:s,timePeriod:i})})).andThen(W(u4)),r)}async function Mf(e,t){let{category:n,user:r,window:o}=M(t,bie);return X(nn(()=>e.data.get("/v2/leaderboard",{params:tn({category:n,timePeriod:o,user:r})})).andThen(W(d4)))}function Ek(e,t={}){let{category:n,cursor:r,pageSize:o,window:s}=M(t,wie);return Fe(i=>nn(()=>e.data.get("/v2/biggest-winners",{params:tn({category:n,cursor:i,limit:o,timePeriod:s})})).andThen(W(p4)),r)}function Rk(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,vie);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(W(n$)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?sa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}function Ff(e,t={}){let n=M(t,kie);return Fe(r=>e.gamma.get("/markets/keyset",{params:Uie({...n,cursor:r??n.cursor})}).andThen(W(hI)).map(o=>({items:o.items,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor})),n.cursor)}function Ck(e,t={}){let n=M(t,Eie);return Fe(r=>e.rfq.get("/v1/rfq/combo-markets",{params:Bie({...n,cursor:r??n.cursor})}).andThen(W(x4)).map(o=>({items:o.markets,hasMore:o.nextCursor!==void 0,nextCursor:o.nextCursor})),n.cursor)}async function Ok(e,t){let n=M(t,Sie);return"id"in n?Mie(e,n):"url"in n?l6(e,{includeTag:n.includeTag,locale:n.locale,slug:K8(n.url,"market")}):l6(e,n)}async function Dk(e,t){let n=M(t,Pie);return X(e.gamma.get(`markets/${n.id}/tags`).andThen(W(fI)))}function Bk(e,t){let{conditionIds:n,cursor:r,includePnl:o,minBalance:s,pageSize:i}=M(t,Rie);return Fe(a=>nn(()=>e.data.get("/v2/holders",{params:tn({condition:n,limit:i,cursor:a,includePnl:o,minBalance:s})})).andThen(W(r4)),r)}function Fk(e,t){let{assetId:n,cursor:r,pageSize:o,...s}=M(t,Lie);return Fe(i=>nn(()=>e.data.get("/v2/prices-history",{params:tn({...s,tokenId:n,limit:o,cursor:i})})).andThen(W(n4)),r)}async function Hk(e,t={}){let{conditionIds:n}=M(t,Die);return X(nn(()=>e.data.get("/v2/oi",{params:tn({condition:n})})).andThen(W(o4)))}function Uie(e){return ve(e,Ee({cursor:"after_cursor",ids:"id",pageSize:"limit"}))}function Bie(e){return ve({cursor:e.cursor,exclude:e.exclude?.join(","),pageSize:e.pageSize},{cursor:"cursor",exclude:"exclude",pageSize:"limit"})}async function l6(e,t){return X(e.gamma.get(`markets/slug/${t.slug}`,{params:ve({includeTag:t.includeTag,locale:t.locale},Ee())}).andThen(W(Nw)))}async function Mie(e,t){return X(e.gamma.get(`markets/${t.id}`,{params:ve({includeTag:t.includeTag,locale:t.locale},Ee())}).andThen(W(Nw)))}function mO(e){if(!(e instanceof O))return e;let t=Fie(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 Fie(e){if(e.status===425)return"restarting";if(e.status===503&&e.code==="post_only_mode")return"post_only"}async function Vk(e,t){let n=M(t,qie);return Qk(e,"/order",{orderID:n.orderId})}async function Wk(e,t){let n=M(t,Hie);return Qk(e,"/orders",n.orderIds)}async function Gk(e){return Qk(e,"/cancel-all")}async function Yk(e,t){let n=M(t,Vie);return Qk(e,"/cancel-market-orders",{asset_id:n.assetId??n.tokenId,market:n.market})}async function Qk(e,t,n){return X(e.secureClob.del(t,{json:n,rateLimitBucket:"cancel"}).mapErr(mO).andThen(W(L3)))}async function Jk(e,t){let n=M(t,jie),r=n.side===Ue.BUY?n.amount:n.shares;return hO(e,{amount:r,assetId:n.assetId,orderType:n.orderType,side:n.side})}async function hO(e,t){let n=await Hd(e,{assetId:t.assetId});return Zk({amount:t.amount,orderBook:n,orderType:t.orderType,side:t.side})}function Zk(e){let{orderBook:t}=e,n=e.side===Ue.BUY?zie(t.asks,e.amount,e.orderType):Gie(t.bids,e.amount,e.orderType);return fe(Wie(n,t.tickSize),`Resolved market price fell outside the valid range for tick size ${t.tickSize}.`),n}function Wie(e,t){return e>=t&&e<=1-t}function zie(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 Gie(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){M(t,Z8);let n=e5(e,t);return X(e.secureClob.post("/order",{json:n,rateLimitBucket:"order"}).mapErr(mO).andThen(W(DC)))}}function nx(e){return async function(t){M(t,Qie);let n=t.map(r=>e5(e,r));return X(e.secureClob.post("/orders",{json:n,rateLimitBucket:"order"}).mapErr(mO).andThen(W(X3)))}}function e5(e,t){return fe(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 Xie(e){try{let t=BigInt(e);return t>=0n&&t<=Kie}catch{return!1}}function r5(e){let t=Wt.encode([{name:"legs",type:"uint256[]"}],[e]),n=Je.keccak256(Wt.encode([{name:"moduleId",type:"uint256"},{name:"data",type:"bytes"}],[n5,t])),r=z_(`0x03${n.slice(34)}0000000000000000000000000000`);return{conditionId:r,positionIds:[BigInt(`${r}00`).toString(),BigInt(`${r}01`).toString()]}}function o5(e){if(e.length===0||e.length>d6)throw new E(`Combo legs must include 1 to ${d6} position IDs`);let t=e.map(n=>{let r=fO(n),o=r.toString(16).padStart(t5*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 rx(e){try{return(fO(e)&tae)===0n}catch{return!1}}function nae(e){let t=fO(e).toString(16).padStart(t5*2,"0"),n=BigInt(`0x${t.slice(0,2)}`),r=Number.parseInt(t.slice(-2),16);if(n!==Jie&&n!==Zie&&n!==n5)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:Oh(`0x${t.slice(0,-2)}`),outcomeIndex:r}}function fO(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>eae)throw new E("Position ID must be a uint256 value");return n}function s5(e){let t=e*Number(nc),n=Math.round(t),r=oae*Math.max(1,Math.abs(t)),o=Math.abs(t-n)<=r?n:Math.trunc(t);return BigInt(o)}function kN(e){let t=Math.round(e*Number(nc)),n=t/Number(nc);if(!Number.isSafeInteger(t)||Math.abs(e-n)>rae)throw new E("has unsupported precision.");return BigInt(t)}function i5(e){return Number(e)/Number(nc)}function gO(e){return fe(Number.isInteger(e)&&e>=0&&e<=hN,`Decimal places must be an integer between 0 and ${hN}.`),10n**BigInt(hN-e)}function yO(e,t,n,r){fe(e>=0n,"Value must be non-negative."),fe(t>=0n,"Multiplier must be non-negative."),fe(n>0n,"Denominator must be positive.");let o=e*t,s=o/n;return r==="up"&&o%n!==0n?s+1n:s}function a5(e,t,n){let r=gO(t);return yO(e,1n,r,n)*r}function l5(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}}fe(!1,`Unsupported tick size: ${e}`)}function c5(e,t){let n=kN(e),r=kN(t);if(n<r||n>nc-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 sae(e,t){return t?e.environment.contracts.negRiskExchange:e.environment.contracts.standardExchange}function qf(e,t,n){return rx(t)?e.environment.contracts.exchangeV3:sae(e,n)}function xN(e,t,n,r){let o=gO(n);return yO(e,t,nc*o,r)*o}function iae(e,t,n,r){let o=gO(n);return yO(e,nc,t*o,r)*o}function aae(e){let t=l5(e.tickSize),n=a5(s5(e.size),t.size,"down");return e.side===Ue.BUY?{offeredAmount:xN(n,e.price,t.amount,"down"),requestedAmount:n}:{offeredAmount:n,requestedAmount:xN(n,e.price,t.amount,"down")}}function lae(e){let t=l5(e.tickSize),n=a5(s5(e.amount),t.size,"down"),r=e.protectPrice?"up":"down";return e.side===Ue.BUY?{offeredAmount:n,requestedAmount:iae(n,e.price,t.amount,r)}:{offeredAmount:n,requestedAmount:xN(n,e.price,t.amount,r)}}function A0(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 p6(e,t=AN){return{expiresAt:Date.now()+t,promise:Promise.resolve(e)}}function ox(e,t){return bO(e).resolveMarket(t)}function TN(e,t){return bO(e).fetchCurrentMarket(t)}function uae(e,t){return bO(e).resolveBuilderTakerFeeRate(t)}function bO(e){let t=m6.get(e);if(t!==void 0)return t;let n=new cae({fetchBuilderTakerFeeRate:async r=>(await lO(e,{builderCode:r})).taker,fetchMarket:r=>aO(e,{conditionId:r}),resolveCondition:r=>iO(e,{assetId:r})});return m6.set(e,n),n}async function mae(e,t){let n=await hae(e,{assetId:t.assetId,price:t.price}),r=aae({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 hae(e,t){let n=await ox(e,t.assetId);try{return f6(e,t,n)}catch(r){if(!(r instanceof E))throw r;let o=await TN(e,t.assetId);return f6(e,t,o)}}function f6(e,t,n){let r=fae(t.price,n.tickSize);return{exchangeAddress:qf(e,t.assetId,n.negRisk),funderAddress:e.account.wallet,price:r,signerAddress:e.account.signer,tickSize:n.tickSize}}function fae(e,t){try{return c5(e,t)}catch(n){throw n instanceof E?new E(`Price ${n.message}`,{cause:n}):n}}async function yae(e,t){let n=await bae(e,t,t.assetId),r=lae({amount:n.resolvedAmount,price:n.price,protectPrice:p5(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 bae(e,t,n){return p5(t)?wae(e,t,n):vae(e,t,n)}async function wae(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 m5(e,n,t.builderCode);try{return b6(e,t,n,r,s,t.maxSpend,i)}catch(a){if(!(a instanceof E))throw a;let l=await TN(e,n);return b6(e,t,n,r,s,t.maxSpend,l)}}let o=await ox(e,n);try{return w6(e,t,n,r,o)}catch(s){if(!(s instanceof E))throw s;let i=await TN(e,n);return w6(e,t,n,r,i)}}function b6(e,t,n,r,o,s,i){let a=d5(t,i.tickSize),l=i5(a);return{exchangeAddress:qf(e,n,i.negRisk),funderAddress:e.account.wallet,price:a,resolvedAmount:h5({amount:r,builderTakerFeeRate:o,maxSpend:s,platformFeeExponent:i.feeInfo.exponent,platformFeeRate:i.feeInfo.rate,price:l}),signerAddress:e.account.signer,tickSize:i.tickSize}}function w6(e,t,n,r,o){let s=d5(t,o.tickSize);return{exchangeAddress:qf(e,n,o.negRisk),funderAddress:e.account.wallet,price:s,resolvedAmount:r,signerAddress:e.account.signer,tickSize:o.tickSize}}async function vae(e,t,n){let r=t.side===Ue.BUY?t.amount:t.shares,o=t.side===Ue.BUY&&t.maxSpend!==void 0?m5(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=kN(Zk({amount:r,orderBook:s,orderType:t.orderType,side:t.side}));return{exchangeAddress:qf(e,n,s.negRisk),funderAddress:e.account.wallet,price:a,resolvedAmount:kae(t,r,i5(a),i),signerAddress:e.account.signer,tickSize:s.tickSize}}function kae(e,t,n,r){return e.side!==Ue.BUY||e.maxSpend===void 0||r===void 0?t:h5({amount:t,builderTakerFeeRate:r.builderTakerFeeRate,maxSpend:e.maxSpend,platformFeeExponent:r.market.feeInfo.exponent,platformFeeRate:r.market.feeInfo.rate,price:n})}function d5(e,t){return e.side===Ue.BUY?(fe(e.maxPrice!==void 0,"Protected BUY market order requires maxPrice."),v6("maxPrice",e.maxPrice,t)):(fe(e.minPrice!==void 0,"Protected SELL market order requires minPrice."),v6("minPrice",e.minPrice,t))}function v6(e,t,n){try{return c5(t,n)}catch(r){throw r instanceof E?new E(`${e} ${r.message}`,{cause:r}):r}}function p5(e){return e.side===Ue.BUY&&e.maxPrice!==void 0||e.side===Ue.SELL&&e.minPrice!==void 0}async function m5(e,t,n){let[r,o]=await Promise.all([ox(e,t),uae(e,n)]);return{builderTakerFeeRate:o,market:r}}function h5(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 sx(e){let t=Rae(e.domain,e.order);return e.order.signatureType!==Rr.POLY_1271?t:{domain:k5(e.domain),message:{chainId:e.domain.chainId,contents:t.message,name:xae,salt:SN,verifyingContract:e.order.signer,version:Aae},primaryType:"TypedDataSign",types:{EIP712Domain:g5,Order:y5,TypedDataSign:Eae}}}function ix(e){if(e.order.signatureType!==Rr.POLY_1271)return e.signature;let t=we.toHex(we.fromString(PN)),n=PN.length.toString(16).padStart(4,"0");return lq(`0x${e.signature.slice(2)}${_ae(e.domain).slice(2)}${Iae(e.order).slice(2)}${t.slice(2)}${n}`)}function wO(e){return{chainId:e.chainId,exchange:e.exchange,protocolVersion:"3"}}function b5(e,t,n){return e===Ue.SELL?n.toString():((t*n+999999n)/1000000n).toString()}function w5(e,t,n){return e===Ue.SELL?(t*n/1000000n).toString():n.toString()}function v5(e){return{builder:e.builder??SN,maker:e.maker,makerAmount:BigInt(e.makerAmount),metadata:e.metadata??SN,salt:BigInt(e.salt),side:ax(e.side),signatureType:e.signatureType,signer:e.signer,takerAmount:BigInt(e.takerAmount),timestamp:BigInt(e.timestamp),tokenId:BigInt(e.tokenId)}}function Rae(e,t){return{domain:k5(e),message:v5(t),primaryType:"Order",types:{EIP712Domain:g5,Order:y5}}}function k5(e){return{chainId:e.chainId,name:f5,verifyingContract:e.exchange,version:e.protocolVersion}}function _ae(e){return Wn(Je.keccak256(Wt.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"address"}],[Sae,Pae,Cae(e.protocolVersion),BigInt(e.chainId),e.exchange]),{as:"Hex"}))}function Iae(e){let t=v5(e);return Wn(Je.keccak256(Wt.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"}],[Tae,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 Cae(e){return Wn(Je.keccak256(we.fromString(e),{as:"Hex"}))}function ax(e){return e===0||e===1?e:e===Ue.BUY?0:1}function x5(e,t){let n=rc(t);return{builder:e.builderCode??k6,chainId:e.chainId,exchangeAddress:e.exchangeAddress,expiration:e.expiration,maker:n.maker,makerAmount:e.offeredAmount.toString(),metadata:k6,orderType:e.orderType,protocolVersion:rx(e.assetId)?"3":"2",salt:Nae().toString(),side:e.side,signatureType:n.signatureType,signer:n.signer,takerAmount:e.requestedAmount.toString(),timestamp:Date.now().toString(),tokenId:e.assetId}}function A5(e,t){let{chainId:n,exchangeAddress:r,protocolVersion:o,...s}=e;return{...s,signature:t}}function Nae(){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 T5(e){return sx({domain:P5(e),order:e})}function S5(e,t){return ix({domain:P5(e),order:e,signature:t})}function P5(e){return{chainId:e.chainId,exchange:e.exchangeAddress,protocolVersion:e.protocolVersion}}function lx(e){return{kind:"signOrder",payload:e}}async function cx(e,t){let n=M(t,gae);return async function*(){let r=await yae(e,n),o=x5(r,e.account),s=ss(yield lx(T5(o)));return A5(o,O0(e.account,S5(o,s)))}.call(null)}async function ux(e,t){let n=M(t,pae);return async function*(){let r=await mae(e,n),o=x5(r,e.account),s=ss(yield lx(T5(o))),i=A5(o,O0(e.account,S5(o,s)));return n.postOnly===!0?{...i,postOnly:!0}:i}.call(null)}async function R5(e,t){return C5(e,cx(e,t))}async function I5(e,t){return C5(e,ux(e,t))}async function C5(e,t){let n=await t;return async function*(){let r=yield*n;return $d(e)(r)}.call(null)}function Bae(e){return e.status===Ki.Confirmed||e.status===Ki.Failed}function x6(e){return e.status===Ki.Failed}async function px(e,t,n){let{timeoutMs:r=Lae}=M(n,Uae),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=>Ef(e,{id:u}).firstPage()));for(let u of c)for(let d of u.items)o.includes(d.id)&&Bae(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 os(Oae)}let a=[...s.values()];if(a.every(x6))throw new en(`Every fill of order ${t.orderId} failed execution: ${o.join(", ")}`);return[...new Set(a.filter(l=>!x6(l)).map(l=>l.transactionHash))].map(l=>et.parse(l))}function N5(e,t){return e===Ue.BUY?ra.COLLATERAL:rx(t)?ra.CONDITIONAL_V2:ra.CONDITIONAL}async function Mae(e,t){let n=N5(t.side,t.assetId),{allowances:r}=await G0(e,t.side===Ue.BUY?{assetType:n}:{assetType:n,assetId:t.assetId});return Fae(r,t.spenderAddress)}function Fae(e,t){return Object.entries(e).find(([n])=>zt(n,t))?.[1]??0n}function Hf(e,t){return cx(e,t).then(vn(e.signer))}function fx(e,t){return Hf(e,t).then(n=>O5(e,n))}function $f(e,t){return ux(e,t).then(vn(e.signer))}function bx(e,t){return $f(e,t).then(n=>O5(e,n))}async function O5(e,t){let n=$d(e);try{return await n(t)}catch(r){if(!Hae(r))throw r;let o=await qae(e,t,n);if(o===void 0)throw r;return o}}async function qae(e,t,n){return await $ae(e,t)?n(t):void 0}function Hae(e){return e instanceof O&&e.status===400&&e.message.includes("allowance is not enough")}async function $ae(e,t){let n=t.tokenId,r=await ox(e,n),o=qf(e,n,r.negRisk),s=BigInt(t.makerAmount);return await Mae(e,{assetId:n,spenderAddress:o,side:t.side})>=s?!1:(await(t.side===Ue.BUY?await Df(e,{amount:"max",spenderAddress:o,tokenAddress:e.environment.contracts.collateralToken}):await Uf(e,{operatorAddress:o,tokenAddress:rx(n)?e.environment.contracts.positionManager:e.environment.contracts.conditionalTokens})).wait(),await UN(e,{assetType:N5(t.side,n),tokenId:t.side===Ue.SELL?n:void 0}),!0)}function Vae(e){let t=fo.getSignPayload(xO(e));return ss(ow.toHex(ad.sign({payload:t,privateKey:e.privateKey})))}function xO(e){let t={chainId:e.chainId,name:"Polymarket",version:"1"};return{domain:t,message:{data:Je.keccak256(lN(L5(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 L5(e){return Array.isArray(e)?e.filter(t=>t!==void 0).map(L5):e}function Vf(){let[e]=crypto.getRandomValues(new Uint32Array(1));return fe(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}function A6(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 vx(e,t){let n=M(t,Wae);return X(e.perps.get("/v1/info/builder",{params:ve(n,Ee())}).andThen(W(tf)))}async function Gae(e,t,n){let r=M(n,D5);if(r.builderAddress===void 0)throw new E("A builder address is required when the session has no builder attribution.");let o=Kae(await t.fetchBuilderApprovals({builder:r.builderAddress}),r.builderAddress),s={...M({builder:r.builderAddress,maxFeeRate:r.maxFeeRate,approvalVersion:o},zae),chainId:e.environment.chainId,salt:Vf(),timestamp:Date.now()},i;try{i=await e.signer.signTypedData(Yae(s))}catch(a){throw ce.fromError(a,"Could not sign builder consent")}return X(e.perps.post("/v1/account/builder-approvals",{json:Qae(s,i)}).andThen(W(zw)))}function Kae(e,t){return(e.find(n=>n.builder.toLowerCase()===t.toLowerCase())?.approvalVersion??0)+1}function Yae(e){return xO({chainId:e.chainId,op:["approveBuilder",[e.builder,e.maxFeeRate,e.approvalVersion]],salt:e.salt,timestamp:e.timestamp})}function Qae(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 Xae(e,t){let n=T6(e.get("Poly-RateLimit-Remaining"),/^-?\d+$/),r=T6(e.get("Poly-RateLimit-Reset"),/^\d+$/),o=Jae(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 T6(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 Jae(e){if(!(e===null||e.trim()===""))return e}function cle(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 I("WebSocket headers require a header-capable WebSocket implementation.",{cause:n})}throw new I("WebSocket headers require a header-capable WebSocket implementation.")}function ule(e,t){let n=Math.min(t.baseMs*2**e,t.maxMs);return Math.random()*n}function dle(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 hle(e){return await X(e.get("/v1/account/balances").andThen(W(CI)))}async function fle(e){return await X(e.get("/v1/account/portfolio").andThen(W(OI)))}async function gle(e){return await X(e.get("/v1/account/stats").andThen(W(NI)))}async function yle(e){return await X(e.get("/v1/account/auto-cancel").andThen(W(I4)))}async function wle(e,t){let n=M(t,ble);return await X(e.get("/v1/account/config",{params:Jr(n)}).andThen(W(UI)))}async function kle(e,t){let n=M(t,vle);return await X(e.get("/v1/account/open-orders",{params:Jr(n)}).andThen(W(xC)))}async function Tle(e,t){let n=M(t,Ale);return await X(e.get("/v1/account/orders",{params:Jr(n)}).andThen(W(kC)))}function Ple(e,t={}){let n=M(t,Sle);return Fe(r=>e.get("/v1/account/fills",{params:Jr({startTimestamp:n.start,endTimestamp:n.end,sort:n.sort,cursor:r??n.cursor})}).andThen(W(TC)).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 Ile(e,t={}){let{cursor:n,params:r}=M(t,_le);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps funding payment params."),s={kind:"perpsFundingPayments",seenKeys:[],...r}):s=_o(o,EO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/funding",{params:Jr(l)}).andThen(W(LI)).map(u=>{let d=u.data.filter(p=>!c.has(`${p.instrumentId}:${p.timestamp}:${p.funding}`));return RO({getKey:p=>`${p.instrumentId}:${p.timestamp}:${p.funding}`,getTimestamp:p=>p.timestamp,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Lle(e,t={}){let{cursor:n,params:r}=M(t,Ole);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps deposit params."),s={kind:"perpsDeposits",seenKeys:[],...r}):s=_o(o,EO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/deposits",{params:Jr(l)}).andThen(W(zI)).map(u=>{let d=u.data.filter(p=>!c.has(p.hash));return RO({getKey:p=>p.hash,getTimestamp:cce,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Mle(e,t={}){let{cursor:n,params:r}=M(t,Ble);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps withdrawal params."),s={kind:"perpsWithdrawals",seenKeys:[],...r}):s=_o(o,EO,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s,c=new Set(s.seenKeys);return e.get("/v1/account/withdrawals",{params:Jr(l)}).andThen(W(KI)).map(u=>{let d=u.data.filter(p=>!c.has(String(p.withdrawalId)));return RO({getKey:p=>String(p.withdrawalId),getTimestamp:uce,items:d,responseData:u.data,responseMore:u.more,state:s})})},n)}function Vle(e,t={}){let{cursor:n,params:r}=M(t,$le);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps internal-transfer params."),s={kind:"perpsInternalTransfers",seenKeys:[],...r}):s=_o(o,qle,"Invalid Perps account pagination cursor");let{kind:i,seenKeys:a,...l}=s;return e.get("/v1/account/internal-transfers",{params:Jr(l)}).andThen(W(XI)).map(c=>dle(c.data,c.more,s))},n)}function Gle(e,t){let{cursor:n,params:r}=M(t,zle);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps equity history params."),s={kind:"perpsEquityHistory",...r}):s=_o(o,q5,"Invalid Perps account pagination cursor");let{kind:i,...a}=s;return e.get("/v1/account/equity",{params:Jr(a)}).andThen(W(BI)).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+$5(s.interval)}):void 0}})},n)}function Xle(e,t){let{cursor:n,params:r}=M(t,Qle);return Fe(o=>{let s;o===void 0?(fe(r!==void 0,"Expected initial Perps PnL history params."),s={kind:"perpsPnlHistory",...r}):s=_o(o,q5,"Invalid Perps account pagination cursor");let{kind:i,...a}=s;return e.get("/v1/account/pnl",{params:Jr(a)}).andThen(W(MI)).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+$5(s.interval)}):void 0}})},n)}function nce(e,t={}){let{cursor:n,params:r}=M(t,tce);return Fe(o=>{let s;o===void 0?fe(r!==void 0,"Expected initial Perps notifications params."):s=_o(o,Jle,"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:Jr({cursor:s?.cursor,limit:a,sinceSeq:i})}).andThen(W(mC)).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 rce(e){return(await X(e.get("/v1/account/notifications",{params:Jr({limit:1})}).andThen(W(hC)))).unread}async function ace(e,t){let n=M(t,ice),r=await X(e.post("/v1/account/notifications/read",{json:n}).andThen(W(fC)));if(r.status==="err")throw new O(r.error??"Perps notifications read request was rejected.",{status:200})}function lce(e){return btoa(JSON.stringify({ts:e.timestamp,id:e.id})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ax(e,t){let n=Date.now(),{end:r,start:o,...s}=e;return{...s,endTimestamp:r??n,startTimestamp:o??n-t}}function H5(e){return{endTimestamp:e.end??Date.now(),interval:e.interval,startTimestamp:e.start}}function Jr(e){return ve(e,Ee())}function cce(e){return e.confirmedTimestamp??e.createdTimestamp}function uce(e){return e.confirmedTimestamp??e.createdTimestamp}function RO(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 $5(e){switch(e){case"1h":return 3600*1e3;case"4h":return 14400*1e3;case"1d":return E0;case"1w":return 7*E0}fe(!1,`Unsupported Perps account history interval: ${String(e)}`)}async function pce(e,t){let n=M(t,dce);return(await X(e.get("/v1/account/builder-approvals",{params:ve(n,Ee())}).andThen(W($I)))).data}function hce(e,t){let n=M(t,V5);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(W(jI)).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 fce(e,t){let n=M(t,V5);return X(e.get("/v1/account/builder-earnings-summary",{params:ve(n,{start:"start_timestamp",end:"end_timestamp",asOfSequence:"as_of_sequence"})}).andThen(W(WI)))}async function kce(e,t){let n=M(t,vce),r=e.builderAttribution;return await e.executeCommand({op:["createOrders",n.orders.map(o=>CO(o,r))],expiresAt:n.expiresAt},h.z.array(cf))}function Tce(e){return e.takeProfit!==void 0||e.stopLoss!==void 0}async function Sce(e,t){if(Tce(t))return await Pce(e,t);let n=M(t,Ace),r=e.builderAttribution,[,o]=await e.executeCommandWithEvent({op:["createOrders",[CO(n,r)]],expiresAt:n.expiresAt},j5,z5(n.clientOrderId));return{order:o.payload}}async function Pce(e,t){let n=M(t,xce),r=e.builderAttribution,o=[CO(n,r)],s=n.side===Ue.SELL;n.takeProfit!==void 0&&o.push(I0({buy:s,instrumentId:n.instrumentId,kind:ta.TakeProfit,quantity:n.quantity,builderAttribution:r,trigger:n.takeProfit})),n.stopLoss!==void 0&&o.push(I0({buy:s,instrumentId:n.instrumentId,kind:ta.StopLoss,quantity:n.quantity,builderAttribution:r,trigger:n.stopLoss}));let[i,a]=await e.executeCommandWithEvent({op:["createOrders",o,vd.Order],expiresAt:n.expiresAt},j5,z5(n.clientOrderId)),l=1,c={};return n.takeProfit!==void 0&&(c.takeProfit=_0(Qs(i[l++],"Expected Perps take-profit acknowledgement."))),n.stopLoss!==void 0&&(c.stopLoss=_0(Qs(i[l],"Expected Perps stop-loss acknowledgement."))),{order:a.payload,tpSl:c}}async function _ce(e,t){let n=M(t,Rce),r=e.builderAttribution,o=Jce(await e.fetchPortfolio(),n.instrumentId),s=[];n.takeProfit!==void 0&&s.push(I0({buy:o,instrumentId:n.instrumentId,kind:ta.TakeProfit,quantity:"0",builderAttribution:r,trigger:n.takeProfit})),n.stopLoss!==void 0&&s.push(I0({buy:o,instrumentId:n.instrumentId,kind:ta.StopLoss,quantity:"0",builderAttribution:r,trigger:n.stopLoss}));let i=await e.executeCommand({op:["createOrders",s,vd.Position],expiresAt:n.expiresAt},h.z.array(cf));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=_0(Qs(i[a++],"Expected Perps take-profit acknowledgement."))),n.stopLoss!==void 0&&(l.stopLoss=_0(Qs(i[a],"Expected Perps stop-loss acknowledgement."))),{tpSl:l}}async function Lce(e,t){let n=M(t,Oce),[r]=n.orderId!==void 0?await _N(e,{orderIds:[n.orderId],expiresAt:n.expiresAt,retry:n.retry,signal:n.signal}):await _N(e,{clientOrderIds:[n.clientOrderId],expiresAt:n.expiresAt,retry:n.retry,signal:n.signal});return Qs(r,"Expected Perps cancel order result.")}async function _N(e,t){let n=M(t,Dce);return n.orderIds!==void 0?await S6(n.orderIds,n,async r=>await e.executeCommand({op:["cancelOrders",r],expiresAt:n.expiresAt},h.z.array(Yw))):await S6(n.clientOrderIds,n,async r=>await e.executeCommand({op:["cancelOrdersCOID",r],expiresAt:n.expiresAt},h.z.array(Yw)))}async function S6(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(Fce(t.signal);i.length>0;){if(a>0){let u=o-Date.now(),d=Bce(a);if(u<=0||d>=u||!await Mce(d,t.signal)||t.signal?.aborted||Date.now()>=o)break}let l;try{l=await n(i.map(({identifier:d})=>d));let u=Uce(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 Zw("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 Uce(e){let[t]=e;if(!(e.length!==1||t?.status!=="err"||t.orderId!==void 0||t.clientOrderId!==void 0))return t.error}function Bce(e){let t=Math.min(Ice*2**(e-1),Cce);return Math.random()*t}function Mce(e,t){if(t?.aborted)return Promise.resolve(!1);if(e<=0)return Promise.resolve(!0);if(t===void 0)return new Promise(r=>yn(()=>r(!0),e));let n=t;return new Promise(r=>{let o=yn(()=>{n.removeEventListener("abort",s),r(!0)},e);function s(){clearTimeout(o),r(!1)}n.addEventListener("abort",s,{once:!0})})}function Fce(e){if(e?.aborted)throw Jw.fromReason(e.reason)}async function Hce(e,t){let n=M(t,qce),r=["cancelAll",n.instrumentId===void 0?[]:[n.instrumentId]];await e.executeDeleteCommand({path:"/v1/trade/orders/all",op:r,responseSchema:bC,expiresAt:n.expiresAt})}async function Wce(e,t,n){let r=M(n,Vce),o=["autoCancel",[r.cancelAt]],s=t(o,r.expiresAt);await X(e.patch("/v1/trade/auto-cancel",{json:{...s,op:C0(o)}}).andThen(W(sN)).mapErr(i=>i instanceof O&&i.message.startsWith(`${jce} (`)?new df("Auto-cancel daily trigger limit reached.",{cause:i}):i))}async function Gce(e,t,n){let r=M(n,zce),o=["autoCancel",[0]],s=t(o,r.expiresAt);await X(e.patch("/v1/trade/auto-cancel",{json:{...s,op:C0(o)}}).andThen(W(sN)))}async function Yce(e,t){let n=M(t,Kce);return await e.executeCommand({op:["updateLeverage",[n.instrumentId,n.leverage,n.crossMargin]]},wC)}async function Xce(e,t){let n=M(t,Qce),r=n.amount,o=await e.executeCommand({op:["updateMargin",[n.instrumentId,r]]},lf);if(o.status==="err")throw new O(o.error,{status:200})}function W5(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16));return Er.parse(Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""))}function z5(e){return t=>t.type==="order"&&t.payload.clientOrderId===e}function _0(e){if(e.status==="err")throw new O(e.error,{status:200});return{orderId:e.orderId}}function Jce(e,t){let n=e.positions.find(o=>o.instrumentId===t),r=n===void 0?0:Zce(n.size);if(r===0)throw new E(`No open Perps position for instrument ${t}.`);return r<0}function Zce(e){let t=e.trim(),n=t.replace(/^[+-]/,"").replace(".","");return/^0*$/.test(n)?0:t.startsWith("-")?-1:1}function CO(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 C0(e){let[t,n,r]=e;switch(t){case"createOrders":return nue({args:n.map(eue),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:fe(!1,`Unsupported Perps command: ${String(t)}`)}}function eue(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=tue(e[8])),e[10]!==void 0&&(t.builder={address:e[10][0],fee_rate:e[10][1]}),t}function tue(e){let t={tpsl:e[2],trp:e[1]};return e[0]!==void 0&&(t.market=e[0]),t}function nue(e,t){return t!==void 0&&(e.grp=t),e}function lue(e){let t,n;return{promise:new Promise((r,o)=>{t=r,n=o}),reject:n,resolve:t,schema:e}}function cue(e){return Array.isArray(e)?!1:NO(e)!==void 0}function NO(e){if(Array.isArray(e)){for(let n of e){let r=NO(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 uue(){let[e]=globalThis.crypto.getRandomValues(new Uint32Array(1));return fe(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}async function due(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 Nx(e,t){let n=M(t,pue);return X(e.perps.get("/v1/info/instruments",{params:ve(n,Ee())}).andThen(W(ZI)))}async function Lx(e,t){let n=M(t,mue),[r]=await jf(e,n);if(r===void 0)throw new C(`Perps ticker ${n.instrumentId} was not returned by the API`);return r}async function jf(e,t){let n=M(t,hue),r=ve(n,Ee()),[o,s]=await Promise.all([X(e.perps.get("/v1/info/tickers",{params:r}).andThen(W(eC))),X(e.perps.get("/v1/info/statistics",{params:r}).andThen(W(nC)))]),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 Bx(e,t){let n=M(t,gue);return X(e.perps.get("/v1/info/book",{params:ve(n,Ee())}).andThen(W(oC)))}function Fx(e,t){let{cursor:n,params:r}=M(t,wue);return Fe(o=>{let s=o===void 0?Iue(r):Oue(o);return e.perps.get("/v1/info/klines",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,interval:s.interval,startTimestamp:s.startTimestamp},Ee())}).andThen(W(dC)).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+Uue(s.interval)}):void 0}})},n)}function Hx(e,t){let{cursor:n,params:r}=M(t,xue);return Fe(o=>{let s=o===void 0?Cue(r):Lue(o);return e.perps.get("/v1/info/funding",{params:ve({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},Ee())}).andThen(W(cC)).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 Vx(e,t){let{cursor:n,params:r}=M(t,Sue);return Fe(o=>{let s=o===void 0?Nue(r):Due(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(W(lC)).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?[]:Bue(s,l,u)}):void 0}})},n)}async function Wx(e){return(await X(e.perps.get("/v1/info/fees").andThen(W(uC)))).feeSchedule}function _ue(e){let t=Date.now();return{endTimestamp:e.end??t,instrumentId:e.instrumentId,interval:e.interval,startTimestamp:e.start??t-K5}}function Q5(e){let t=Date.now();return{endTimestamp:e.end??t,instrumentId:e.instrumentId,startTimestamp:e.start??t-K5}}function Iue(e){return fe(e!==void 0,"Expected initial Perps candles params."),{kind:"perpsCandles",...e}}function Cue(e){return fe(e!==void 0,"Expected initial Perps funding params."),{kind:"perpsFundingHistory",...e}}function Nue(e){return fe(e!==void 0,"Expected initial Perps trades params."),{kind:"perpsTrades",seenTradeIds:[],...e}}function Oue(e){return _o(e,Pue,"Invalid Perps pagination cursor")}function Lue(e){return _o(e,Eue,"Invalid Perps pagination cursor")}function Due(e){return _o(e,Rue,"Invalid Perps pagination cursor")}function Uue(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}fe(!1,`Unsupported Perps kline interval: ${String(e)}`)}function Bue(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 Xx(e,t={}){let n=M(t,Vue),r="credentials"in n?await Jue(e,n.credentials):await Xue(e,n);return e.webSockets.perpsSession.connect(r,n.builderAttribution,Gae.bind(null,e),n.includeBuilderFills)}async function Jx(e,t){let n=M(t,Wue),r={type:"deleteProxy",args:{proxy:n.proxy}},o=["deleteProxy",[n.proxy]],s=Vf(),i=Date.now(),a=await eV(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(W(HI)));if(l.status==="err")throw new O(l.error??"Perps credentials revocation was rejected.",{status:200})}async function OO(e,t){let n=M(t,zue),{contracts:r}=e.environment,o=zN(r.perpsDepositContract,r.collateralToken,n.amount,e.account.signer);return async function*(){return e.account.walletType===Se.EOA?wn(yield ade(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 Zx(e,t){return OO(e,t).then(vn(e.signer))}async function eA(e,t){let n=M(t,Gue),r=Math.floor(Date.now()/1e3),o=Vf(),s={type:"withdraw",args:{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:n.amount.toString(),to:e.account.wallet}},i=await ede(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(W(YI)));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 tA(e,t){sde(e);let n=M(t,Que);if(zt(n.recipient,e.account.signer))throw new E("Perps collateral cannot be transferred to the authenticated account.");return due({signTransfer({account:r,token:o,amount:s,recipient:i,salt:a,timestamp:l}){return eV(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(W(JI)))).transferId}},{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:n.amount,recipient:n.recipient,label:n.label,salt:Vf(),timestamp:Date.now()})}async function Xue(e,t){let n=rde(),r=tV(n),o=e.account.signer,s=Date.now()+t.expiresIn,i=Date.now(),a=Vf(),l={args:{expiry:s,owner:o,proxy:r},type:"createProxy"},c=await Zue(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(W(qI))),p={expiresAt:s,privateKey:n,proxy:r,secret:d.secret};return Z5(e,p)}async function Jue(e,t){return ode(t),Z5(e,t)}async function Z5(e,t){let n=await X(e.perps.get("/v1/account/credentials",{headers:ide(t)}).andThen(W(FI)));if(!zt(n.address,e.account.signer))throw new C("Perps credentials belong to a different signer account.");let r=n.keys.find(o=>zt(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 Zue(e,t){try{return await e.signer.signTypedData(nde({chainId:e.environment.chainId,...t}))}catch(n){throw ce.fromError(n,"Could not sign the Perps proxy credentials request")}}async function eV(e,t){try{return await e.signer.signTypedData(xO({chainId:e.environment.chainId,op:t.signedOp,salt:t.salt,timestamp:t.timestamp}))}catch(n){throw ce.fromError(n,"Could not sign the Perps operation request")}}async function ede(e,t){try{return await e.signer.signTypedData(tde({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 ce.fromError(n,"Could not sign the Perps withdrawal request")}}function tde(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 nde(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 rde(){return aq(ad.randomPrivateKey(),"Generated invalid Perps proxy key.")}function tV(e){return Be(Jo.fromPublicKey(ad.getPublicKey({privateKey:e})))}function ode(e){let t=tV(e.privateKey);if(!zt(t,e.proxy))throw new E("Perps credentials private key does not match the proxy address.")}function sde(e){if(e.account.signerType!=="OWNER")throw new E("Perps collateral transfers must be signed by the account owner.")}function ide(e){return{"POLYMARKET-PROXY":e.proxy,"POLYMARKET-SECRET":e.secret}}function ade(e){return{kind:"sendPerpsDepositTransaction",request:e}}function Wf(e,t){let{cursor:n,pageSize:r,window:o,...s}=M(t,lde);return Fe(i=>nn(()=>e.data.get("/v2/positions",{params:tn({...s,...o,limit:r,cursor:i})})).andThen(W(W$)),n)}function zf(e,t){let{cursor:n,pageSize:r,...o}=M(t,dde);return Fe(s=>nn(()=>e.data.get("/v2/positions/combos",{params:tn({...o,limit:r,cursor:s})})).andThen(W(Q$)),n)}async function Gf(e,t){let{conditionIds:n,...r}=M(t,pde);return X(nn(()=>e.data.get("/v2/value",{params:tn({...r,condition:n})})).andThen(W(z$)))}async function Kf(e,t){let n=M(t,mde);return X(nn(()=>e.data.get("/v2/user-stats",{params:tn(n)})).andThen(W(G$)))}async function Yf(e,t){let n=M(t,hde);return X(nn(()=>e.data.get("/v2/user-pnl",{params:tn(n)})).andThen(W(K$)))}async function Qf(e,t){let{window:n,...r}=M(t,fde);return X(nn(()=>e.data.get("/v2/user-volume",{params:tn({...r,...n})})).andThen(W(Y$)))}async function Xf(e,t){let n=M(t,gde);return X(e.data.get("/v1/accounting/snapshot",{params:goe(n)}).andThen(jre))}function yde(e,t){if(!Kr(e.conditionId))throw new C(`Missing condition ID for ${t}`);if(!Kr(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===Zi.V2){if(Kr(o)!==Kr(s))throw new C(`Incomplete market position IDs for ${t}`);if(!Kr(o)||!Kr(s))throw new C(`Missing market position IDs for ${t}`);return{marketId:e.id,conditionId:e.conditionId,protocol:"v2",outcomeIds:[o,s]}}if(Kr(n)!==Kr(r))throw new C(`Incomplete market token IDs for ${t}`);if(Kr(n)&&Kr(r)){if(!Kr(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 uA(e,t){let n=M(t,nV),r=await MO(e,{conditionId:n.conditionId}),o=r.protocol==="ctf"?GN(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId,n.amount):uv(e.environment.contracts.protocolV2Router,r.conditionId,n.amount);return async function*(){return e.account.walletType===Se.EOA?wn(yield IN(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 dA(e,t){let n=M(t,oV),r=o5(n.legs),o=pv(e.environment.contracts.combinatorialModule,r),s=r5(r),i=uv(e.environment.contracts.protocolV2Router,s.conditionId,n.amount);return async function*(){return e.account.walletType===Se.EOA?(await wn(yield IN(Qn(e.environment.chainId,o))).wait(),wn(yield IN(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 LO(e,t){let n=M(t,bde);return n.legs!==void 0?dA(e,n):uA(e,n)}function aV(e,t){return uA(e,t).then(vn(e.signer))}function cV(e,t){return dA(e,t).then(vn(e.signer))}function pA(e,t){return LO(e,t).then(vn(e.signer))}async function hA(e,t){let n=M(t,uV),r=await MO(e,{conditionId:n.conditionId}),o=Cf(await e.rpc.ethCall(If(r.positionErc1155Address,e.account.wallet,r.outcomeIds))),s=TV(r.conditionId,o,n.amount),i=r.protocol==="ctf"?KN(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId,s):dv(e.environment.contracts.protocolV2Router,r.conditionId,s);return async function*(){return e.account.walletType===Se.EOA?wn(yield CN(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 fA(e,t){let n=M(t,pV),r=o5(n.legs),o=pv(e.environment.contracts.combinatorialModule,r),s=r5(r),i=Cf(await e.rpc.ethCall(If(e.environment.contracts.positionManager,e.account.wallet,s.positionIds))),a=TV(s.conditionId,i,n.amount),l=dv(e.environment.contracts.protocolV2Router,s.conditionId,a);return async function*(){return e.account.walletType===Se.EOA?(await wn(yield CN(Qn(e.environment.chainId,o))).wait(),wn(yield CN(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 DO(e,t){let n=M(t,wde);return n.legs!==void 0?fA(e,n):hA(e,n)}function fV(e,t){return hA(e,t).then(vn(e.signer))}function yV(e,t){return fA(e,t).then(vn(e.signer))}function gA(e,t){return DO(e,t).then(vn(e.signer))}async function UO(e,t){let n=M(t,vde),r=await MO(e,n.conditionId!==void 0?{conditionId:n.conditionId,closed:!0}:{marketId:n.marketId,closed:!0}),o=await Tde(e,r);return async function*(){return e.account.walletType===Se.EOA?yield*xde(e,o):yield*await Or(e,{calls:o,metadata:n.metadata??`Redeem positions for market ${r.marketId} (condition ${r.conditionId})`})}.call(null)}async function bA(e,t){let n=M(t,kV),r=nae(n.positionId),o=VN(await e.rpc.ethCall($N(e.environment.contracts.positionManager,e.account.wallet,n.positionId)));if(o===0n)throw new E("Position has no balance to redeem");let s=xf(e.environment.contracts.protocolV2Router,r.conditionId,r.outcomeIndex,o);return async function*(){return e.account.walletType===Se.EOA?wn(yield NN(Qn(e.environment.chainId,s))):yield*await Or(e,{calls:[s],metadata:n.metadata??`Redeem position ${n.positionId}`})}.call(null)}function AV(e,t){return bA(e,t)}async function BO(e,t){let n=M(t,kde);return n.positionId!==void 0?bA(e,n):UO(e,n)}function vA(e,t){return BO(e,t).then(vn(e.signer))}function IN(e){return{kind:"sendSplitPositionTransaction",request:e}}function CN(e){return{kind:"sendMergePositionsTransaction",request:e}}function NN(e){return{kind:"sendRedeemPositionsTransaction",request:e}}async function*xde(e,t){let[n,...r]=t;fe(n!==void 0,"Expected at least one redemption call");let o=n;for(let s of r)await wn(yield NN(Qn(e.environment.chainId,o))).wait(),o=s;return wn(yield NN(Qn(e.environment.chainId,o)))}async function MO(e,t){let n=t.conditionId!==void 0?`condition ${t.conditionId}`:`market ${t.marketId}`,r=await Ff(e,t.conditionId!==void 0?{conditionIds:[t.conditionId],closed:t.closed,pageSize:1}:{ids:[Ade(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=yde(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 Ade(e){let t=Number(e);if(!Number.isInteger(t))throw new E(`Market ID must be an integer, received ${e}`);return t}async function Tde(e,t){if(t.protocol==="ctf")return[YN(t.adapterAddress,e.environment.contracts.collateralToken,t.conditionId)];let n=Cf(await e.rpc.ethCall(If(t.positionErc1155Address,e.account.wallet,t.outcomeIds)));if(n.length!==2)throw new C("Expected two position balances");let[r,o]=n;fe(r!==void 0,"Expected YES position balance"),fe(o!==void 0,"Expected NO position balance");let s=[];if(r>0n&&s.push(xf(e.environment.contracts.protocolV2Router,t.conditionId,0,r)),o>0n&&s.push(xf(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 TV(e,t,n){let r=Sde(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 Sde(e){if(e.length!==2)throw new C("Expected two position balances");let[t,n]=e;return fe(t!==void 0,"Expected YES position balance"),fe(n!==void 0,"Expected NO position balance"),t<n?t:n}async function xA(e,t){let n=M(t,Pde);return X(e.gamma.get("/public-profile",{params:ve(n,Ee())}).andThen(W(r$)).orElse(r=>r instanceof O&&r.status===404?go(null):Sr(r)))}async function EA(e){return Jf(e),e.webSockets.rfqQuoter.connect()}function qO(e){return e instanceof O?new fs(e.message,{cause:e,code:SV(e.code),status:e.status}):e}function SV(e){return e!==void 0&&Lde.has(e)?e:li.RequestFailed}function PV(e){if(!e.hasBuilderApiKey)throw new E("Combo RFQ requests require a Builder API Key in the client configuration, via builderApiKey(...) or remoteBuilderSigning(...).")}function Dde(e,t){return BigInt(e)*1000000n+BigInt(t.padEnd(6,"0"))}async function _A(e,t){Jf(e);let n=M(t,Ude);PV(e);let r=rc(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:Xr.Notional,value_e6:n.amount}:{unit:Xr.Shares,value_e6:n.size},side:Eo.Yes,signature_type:r.signatureType,signer_address:r.signer},s=await X(e.builderGateway.post(FO,{json:o,timeout:Ede}).andThen(W(S4)).mapErr(qO));if("quote"in s){Bde(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 Mde(s)}function Bde(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 Mde(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 fs(e.error?.message??"The combo quote request failed.",{code:SV(e.error?.code),status:200,...e.error===void 0?{}:{cause:e.error}})}}async function CA(e,t){Jf(e);let n=M(t,qde);PV(e);let r=wO({chainId:e.environment.chainId,exchange:e.environment.contracts.exchangeV3}),o=Vde(e,n),s=await Wde(e,r,o),i={quote_id:n.quoteId,signed_order:s};function a(){return e.builderGateway.post(`${FO}/${encodeURIComponent(n.rfqId)}/accept`,{json:i,timeout:Rde}).andThen(W(rN))}let l=await a();if(l.isErr()&&(l.error instanceof I||l.error instanceof C)&&(l=await a()),l.isErr()){let p=Hde(n.rfqId,l.error);if(p!==void 0)return p;throw qO(l.error)}let c=l.value,u=l.value.takerOrderHash,d=Date.now()+_de;for(;c.status===mn.AwaitingMakerConfirmation;){if(Date.now()>=d)throw new tt(`Timed out waiting for the acceptance outcome of RFQ ${n.rfqId}.`);await os(Ide),c=await DA(e,{rfqId:n.rfqId})}return c.status===mn.Failed||c.status===mn.Expired||c.status===mn.Canceled?{reason:$de(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 Hde(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 $de(e,t){return e===mn.Expired||t===Cr.ExpiredRfq?Ro.AcceptanceWindowExpired:t===Cr.MakerDeclined?Ro.MakerDeclined:Ro.ExecutionFailed}function Vde(e,t){let n=rc(e.account);return{builder:t.builderCode,maker:n.maker,makerAmount:t.makerAmount,metadata:Ode,salt:jde().toString(),side:ax(t.direction),signatureType:n.signatureType,signer:n.signer,takerAmount:t.takerAmount,timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.positionId}}function jde(){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 Wde(e,t,n){let r;try{r=await e.signer.signTypedData(sx({domain:t,order:n}))}catch(o){throw o instanceof vt?o:ce.fromError(o,"Could not sign the combo quote acceptance order.")}return{...n,signature:ix({domain:t,order:n,signature:r})}}async function OA(e,t){Jf(e);let n=M(t,zde),r=n.timeoutMs??Cde,o=n.pollingIntervalMs??Nde,s=Date.now()+r;for(;;){let i=await DA(e,{rfqId:n.rfqId});if(i.status===mn.Filled||i.status===ps.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 os(o)}}function DA(e,t){Jf(e);let n=M(t,Gde);return X(e.builderGateway.get(`${FO}/${encodeURIComponent(n.rfqId)}`).andThen(W(rN)).mapErr(qO))}function Jf(e){if(e.account.signerType==="SESSION_KEY")throw new E("Combos is not supported with Session Keys")}function BA(e,t){let{cursor:n,pageSize:r,...o}=M(t,Kde);return Fe(s=>{let i=Md(s,r,{maxOffset:E6});return e.gamma.get("/public-search",{params:ve({...o,limitPerType:i.pageSize,page:i.offset},Ee({excludeTagIds:"exclude_tag_id"}))}).andThen(W(o$)).map(a=>({items:Yde(a),hasMore:a.pagination?.hasMore??!1,limitReached:(a.pagination?.hasMore??!1)&&i.offset+1>E6,totalCount:a.pagination?.totalResults??void 0,nextCursor:a.pagination?.hasMore?sa({offset:i.offset+1,pageSize:i.pageSize}):void 0}))},n??sa({offset:1,pageSize:r}),{events:[],profiles:[],tags:[]})}function Yde(e){return{events:e.events??[],profiles:e.profiles??[],tags:e.tags??[]}}function FA(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,Qde);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/series",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(W(i$)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?sa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function HA(e,t){let n=M(t,Xde);return X(e.gamma.get(`series/${n.id}`,{params:ve({locale:n.locale},Ee())}).andThen(W(FC)))}function EV(e){if(e.kind==="authorization"?e.status===Od.FAILED||e.status===Od.SUPERSEDED||e.status===Od.REPAIR_REQUIRED:e.status===g0.FAILED)throw new en(`Session-key ${e.kind} reached terminal status ${e.status}`)}async function zd(e){HO(e);let t=await X(e.secureClob.get("/v1/user/session-signers").andThen(W(e$)));if(!zt(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 jA(e,t){if(HO(e),!e.hasBuilderApiKey)throw new E("Session-key authorization requires builder API-key authentication.");let n=M(t,epe),r=Math.floor(Date.now()/1e3)+Zde,o=await vn(e.signer)(qd(e,[jN(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:RV}).andThen(W(h4)));EV({kind:"authorization",status:i.status});let a=await new Lf(e,i).wait();return{sessionKey:await rpe(e,{address:n.address,scopes:n.scopes,validUntil:r}),transaction:a}}async function zA(e,t){if(HO(e),!e.supportsGasless)throw new E("Session-key revocation requires API-key authentication that supports gasless transactions.");let n=M(t,tpe),r=await vn(e.signer)(qd(e,[WN(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:RV}).andThen(W(f4)));EV({kind:"revocation",status:s.status}),await npe(e,n.address)}async function npe(e,t){for(let n=0;n<e.environment.relayerMaxPolls;n+=1){if(!(await zd(e)).some(r=>zt(r.address,t)))return;await os(e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for session key ${t} to be revoked`)}async function rpe(e,t){for(let n=0;n<e.environment.relayerMaxPolls;n+=1){let r=(await zd(e)).find(o=>zt(o.address,t.address)&&o.validUntil===t.validUntil&&ope(o.scopes,t.scopes));if(r!==void 0)return r;await os(e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for session key ${t.address} to become active`)}function ope(e,t){let n=new Set(t);return new Set(e).size===n.size&&e.every(r=>n.has(r))}function HO(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 KA(e){return X(e.gamma.get("/sports").andThen(W(wI)))}async function QA(e){return X(e.gamma.get("/sports/market-types").andThen(W(vI)))}function ape(e){return M(e,ipe)}async function Zf(e,t){let n=t.map(i=>{switch(M(i,lpe),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 ape(i);case"prices.crypto.chainlink.twap":M(i,cpe);break;case"market":M(i,upe);break}return i}),r=await Promise.allSettled(n.map(async i=>dpe(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 ppe(o)}function dpe(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 fe(e.isSecureClient(),"A 'user' subscription requires a secure client instance."),e.webSockets.clobUser.subscribe(t)}}function ppe(e){let t;async function n(){t===void 0&&(t=Promise.all(e.map(o=>o.close())).then(()=>{})),await t}let r=J4(...e);return{close:n,[Symbol.asyncIterator](){return r[Symbol.asyncIterator]()}}}function ZA(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,mpe);return Fe(s=>{let i=Md(s,r);return e.gamma.get("/tags",{params:ve({...o,limit:i.pageSize,offset:i.offset},Ee())}).andThen(W(s$)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?sa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function tT(e,t){let n=M(t,hpe);return"id"in n?X(e.gamma.get(`tags/${n.id}`,{params:ve({includeTemplate:n.includeTemplate,locale:n.locale},Ee())}).andThen(W(_d))):X(e.gamma.get(`tags/slug/${n.slug}`,{params:ve({locale:n.locale},Ee())}).andThen(W(_d)))}async function rT(e,t){if("id"in t){let r=M(t,fpe);return X(e.gamma.get(`tags/${r.id}/related-tags`,{params:ve({omitEmpty:r.omitEmpty,status:r.status},Ee())}).andThen(W(BC)))}let n=M(t,gpe);return X(e.gamma.get(`tags/slug/${n.slug}/related-tags`).andThen(W(BC)))}async function sT(e,t){if("id"in t){let r=M(t,ype);return X(e.gamma.get(`tags/${r.id}/related-tags/tags`,{params:ve({locale:r.locale,omitEmpty:r.omitEmpty,status:r.status},Ee())}).andThen(W(MC)))}let n=M(t,bpe);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(W(MC)))}function aT(e,t={}){let{cursor:n,pageSize:r,...o}=M(t,wpe);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(W(bI)).map(a=>{let l=a.length>=i.pageSize;return{items:a,hasMore:l,nextCursor:l?sa({offset:i.offset+i.pageSize,pageSize:i.pageSize}):void 0}})},n)}async function $O(e,t){let n=M(t,vpe);return async function*(){return e.account.walletType===Se.EOA?wn(yield kpe(Qn(e.environment.chainId,P0(n.tokenAddress,n.recipientAddress,n.amount)))):yield*await Or(e,{calls:[P0(n.tokenAddress,n.recipientAddress,n.amount)],metadata:n.metadata??`Transfer ${n.amount} of ${n.tokenAddress} to ${n.recipientAddress}`})}.call(null)}function cT(e,t){return $O(e,t).then(vn(e.signer))}function kpe(e){return{kind:"sendErc20TransferTransaction",request:e}}var h,Ot,C6,$re,ON,LN,Kre,Yre,Xre,toe,noe,roe,ooe,soe,ioe,aoe,loe,q6,wf,D0,H6,U0,woe,voe,M0,koe,q0,xoe,Aoe,$0,V0,Toe,W0,V6,Soe,j6,Poe,W6,Eoe,K0,Roe,Q0,z6,J0,ev,_oe,nv,ov,Ioe,iv,Coe,lv,Noe,cv,Ooe,Loe,Doe,BN,Uoe,G6,Boe,Moe,Foe,qoe,Hoe,K6,Y6,Q6,$oe,Voe,joe,Woe,zoe,Goe,Koe,Yoe,Qoe,X6,Xoe,lr,J6,Z6,e8,t8,n8,r8,o8,s8,i8,a8,l8,ise,ase,lse,cse,use,dse,pse,mse,u8,hse,fse,d8,ur,r6,p8,yse,bse,m8,b8,Lf,Ese,w8,wv,Rse,v8,vv,k8,_se,kv,xv,S8,P8,E8,R8,_8,I8,N8,L8,Cse,Nse,Ev,Ose,_v,Lse,Cv,Dse,B8,Use,F8,Bse,H8,Mse,$8,Fse,V8,qse,Ov,Hse,Dv,$se,Bv,Vse,Mv,jse,qv,Wse,$v,zse,jv,Gse,zv,Kse,Kv,Yse,Qv,j8,Zv,Xse,o6,mN,W8,tk,uO,dO,G8,Zse,eie,tie,rk,nie,sk,ak,oie,sie,iie,ck,dk,mk,lie,cie,uie,fk,die,yk,fie,wk,gie,kk,pO,yie,Ak,bie,Sk,wie,Pk,vie,Y8,kie,xie,Aie,Tie,Sie,Pie,_k,Eie,Ik,Nk,Lk,Rie,Uk,_ie,Iie,vN,Q8,X8,Cie,Nie,Oie,Lie,Mk,Die,qk,qie,Hie,$ie,Vie,$k,jk,zk,Kk,Tf,Sf,J8,c6,u6,jie,Xk,Kie,Yie,Z8,Qie,ex,tx,t5,Jie,Zie,n5,d6,eae,tae,nc,rae,hN,oae,fN,AN,cae,m6,dae,h6,pae,u5,g6,y6,gae,f5,xae,Aae,SN,PN,Tae,Sae,Pae,g5,y5,Eae,k6,vO,kO,E5,_5,Oae,Lae,Dae,Uae,dx,mx,hx,gx,yx,AO,jae,Wae,wx,zae,D5,kx,kn,Zae,ele,tle,nle,rle,ole,sle,TO,U5,B5,SO,M5,ile,ale,lle,la,mi,E0,PO,cr,xx,F5,ple,mle,EO,q5,ble,vle,xle,Ale,Sle,Ele,Rle,_le,Cle,Nle,Ole,Dle,Ule,Ble,Fle,qle,Hle,$le,jle,Wle,zle,Kle,Yle,Qle,Jle,Zle,ece,tce,oce,sce,ice,dce,Tx,mce,gN,V5,Sx,Px,_O,gce,yce,bce,IO,T0,S0,wce,vce,xce,Ace,j5,Ece,Rce,EN,RN,Ice,Cce,Nce,R0,Oce,Dce,qce,$ce,Vce,Ex,jce,zce,Kce,Rx,Qce,_x,rue,yN,oue,sue,iue,aue,bN,Ix,G5,sc,ms,K5,pue,Cx,mue,Ox,hue,Dx,fue,gue,Ux,yue,bue,wue,Mx,Y5,vue,kue,xue,Aue,Tue,qx,Sue,$x,jx,Pue,Eue,Rue,Mue,Fue,que,Hue,$ue,Vue,jue,Wue,X5,zue,Gue,Kue,Yue,Que,zx,Gx,J5,Kx,Yx,Qx,lde,nA,cde,ude,dde,rA,pde,oA,mde,sA,hde,iA,fde,aA,gde,lA,cA,nV,rV,oV,sV,bde,Vd,iV,lV,mA,uV,dV,pV,mV,wde,jd,hV,gV,yA,bV,wV,vde,vV,kV,xV,kde,wA,Pde,kA,ic,AA,ac,TA,lc,SA,PA,FO,Ede,Rde,_de,Ide,Cde,Nde,Ode,fs,Lde,P6,N0,Ude,RA,Fde,qde,IA,zde,NA,Gde,LA,Wd,E6,Kde,UA,Qde,Xde,MA,qA,$A,Jde,Zde,RV,epe,VA,tpe,WA,GA,YA,spe,R6,_V,ipe,XA,IV,lpe,cpe,upe,mpe,hpe,fpe,gpe,ype,bpe,JA,eT,nT,oT,wpe,iT,vpe,CV,lT,uT=L(()=>{"use strict";e0();pf();pf();UC();Al();h=require("zod");s0();fw();D$();f0();f0();k4();y0();y0();iN();W4();Xw();dN();Z4();Ot=h.z.number().int().positive();C6=h.z.strictObject({offset:h.z.number().int().min(0),pageSize:Ot});$re=h.z.object({kind:h.z.literal("keyset"),fingerprint:h.z.string(),cursor:h.z.string().min(1)});ON=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(!M6(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=n6(e.gasPrice)),e.value!==void 0&&(t.value=n6(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(t6(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 t6(i.result)})}async#s(e){let t;try{t=await d0.post(this.#e,{json:e,throwHttpErrors:!1})}catch(r){throw I.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(!e6(n))throw new C("Unexpected JSON-RPC response shape");return n}async#n(e){let t;try{t=await d0.post(this.#e,{json:e,throwHttpErrors:!1})}catch(r){throw I.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=>e6(r)))throw new C("Unexpected JSON-RPC response shape");return n}};LN=(e=>(e.OWNER="OWNER",e.SESSION_KEY="SESSION_KEY",e))(LN||{}),Kre="0x0000000000000000000000000000000000000000000000000000000000000000",Yre="0x6492649264926492649264926492649264926492649264926492649264926492";Xre="3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000";toe="0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",noe="0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",roe=0x61003d3d8160233d3973n;ooe="0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",soe="0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",ioe="0x60195155f3363d3d373d3d363d602036600436635c60da",aoe=0x6100523d8160233d3973n,loe="0x49493a4d";q6=h.z.string().transform(e=>e);wf=h.z.union([h.z.number().int().min(0),h.z.date()]).transform(e=>e instanceof Date?Math.floor(e.getTime()/1e3):e),D0=h.z.union([h.z.literal("full"),h.z.object({start:wf.optional(),end:wf.optional()}).refine(e=>!e.end||e.end>=(e.start??0),"end must not precede start")]).transform(e=>e==="full"?{start:1}:e),H6=Gt.refine(e=>/^[1-9]\d*$/.test(e)&&BigInt(e)<=2147483647n,"Expected a positive 32-bit event ID");U0=B($,O,ce,I,C);woe=h.z.object({cursor:ye.optional(),id:h.z.string().optional(),market:h.z.string().optional()}),voe=Fd(woe.shape).default({}),M0=B($,O,ce,I,C,E);koe=h.z.object({orderId:h.z.string()}),q0=B($,O,ce,I,C,E);xoe={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()},Aoe=Fd(xoe).default({}),$0=B($,O,ce,I,C,E);V0=B($,O,ce,I,C),Toe=h.z.object({ids:h.z.array(h.z.string()).min(1)});W0=B($,O,ce,I,C,E);V6=h.z.object({assetType:k3}),Soe=Fd(V6.shape),j6=B($,O,ce,I,C,E);Poe=Fd(V6.shape),W6=B($,O,ce,I,C,E);Eoe=h.z.object({orderId:h.z.string()}),K0=B($,O,ce,I,C,E);Roe=h.z.object({orderIds:h.z.array(h.z.string())}),Q0=B($,O,ce,I,C,E);z6=h.z.object({cursor:ye.optional(),date:h.z.string()}),J0=B($,O,ce,I,C,E);ev=B($,O,ce,I,C,E);_oe=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()}),nv=B($,O,ce,I,C,E);ov=B($,O,ce,I,C);Ioe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J.optional(),takerOnly:h.z.boolean().optional(),filterType:M$.optional(),filterAmount:h.z.number().min(0).optional(),conditionId:h.z.union([xe,aa(xe,20)]).optional(),eventId:h.z.array(Gt).min(1).optional(),side:Nt.optional(),window:D0.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),iv=B($,O,I,C,E);Coe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([xe,aa(xe,20)]).optional(),eventId:h.z.array(Gt).min(1).optional(),type:h.z.array(XC).min(1).optional(),side:Nt.optional(),sortDirection:h0.optional(),window:D0.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),lv=B($,O,I,C,E);Noe=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([Zt,aa(Zt,20)]).optional()}),cv=B($,O,I,C,E);Ooe=64,Loe=/^0x[0-9a-fA-F]{62}$/,Doe=/^0x[0-9a-fA-F]{64}$/,BN="0x0000000000000000000000000000000000000000000000000000000000000000",Uoe=Ie.from("function approve(address spender, uint256 amount)"),G6=Ie.from("function allowance(address owner, address spender) view returns (uint256)"),Boe=Ie.from("function transfer(address recipient, uint256 amount)"),Moe=Ie.from("function authorizeSessionSigner(address sessionSigner, uint256 validUntil)"),Foe=Ie.from("function revokeSessionSigner(address sessionSigner)"),qoe=Ie.from("function deposit(address token, uint256 amount, address to)"),Hoe=Ie.from("function setApprovalForAll(address operator, bool approved)"),K6=Ie.from("function isApprovedForAll(address account, address operator) view returns (bool)"),Y6=Ie.from("function balanceOf(address account, uint256 id) view returns (uint256)"),Q6=Ie.from("function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])"),$oe=Ie.from("function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Voe=Ie.from("function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),joe=Ie.from("function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)"),Woe=Ie.from("function split(bytes31 conditionId, uint256 amount)"),zoe=Ie.from("function merge(bytes31 conditionId, uint256 amount)"),Goe=Ie.from("function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)"),Koe=Ie.from("function prepareCondition(uint256[] legs) returns (bytes31)"),Yoe=Ie.from("function multiSend(bytes)"),Qoe=Ie.from("function proxy((uint8 typeCode, address to, uint256 value, bytes data)[] calls) returns (bytes[])"),X6=[1n,2n],Xoe=[1n,2n],lr=(1n<<256n)-1n,J6=B(E);Z6=B(E);e8=B(E);t8=B(E);n8=B(E);r8=B(E);o8=B(E);s8=B(E);i8=B(E);a8=B(E);l8=B($,O,tt,en,I,C,E);B(vt,ce);B(vt,ce);ise=[{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],ase=[{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"}],lse="DepositWallet",cse="1",use=600,dse=[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],pse=[{name:"wallet",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"calls",type:"Call[]"}],mse=h.z.object({address:h.z.string(),type:h.z.enum(Ir)}),u8=B($,O,I,C,E);hse=h.z.object({transactionId:Ji}),fse=h.z.object({wallet:J,type:h.z.enum(Se)}),d8=B($,O,I,C,E);ur=h.z.string().max(500),r6=10,p8=B($,O,I,C,E);yse=h.z.object({data:h.z.custom(ln),to:J,value:h.z.bigint().optional()}),bse=h.z.object({calls:h.z.array(yse).min(1).transform(e=>iq(e)),metadata:ur}),m8=B($,O,I,C,E);b8=B($,O,I,C,E,tt,en),Lf=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 eO(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 os(this.#e.environment.relayerPollFrequencyMs)}throw new tt(`Timed out waiting for transaction ${this.transactionId} to settle`)}},Ese=h.z.object({amount:h.z.union([h.z.bigint(),h.z.literal("max")]),metadata:ur.optional(),spenderAddress:J,tokenAddress:J}),w8=B(E);wv=B(vt,$,O,ce,I,C,E);Rse=h.z.object({approved:h.z.boolean().default(!0),metadata:ur.optional(),operatorAddress:J,tokenAddress:J}),v8=B(E);vv=B(vt,$,O,ce,I,C,E);k8=B(O,I,C,E),_se=h.z.object({user:J}),kv=B(O,I,C,E);xv=B(vt,$,O,ce,tt,en,I,C,E);S8=B($,O,I,C);P8=B($,O,I,C);E8=B($,O,I,C);R8=B($,O,ce,I,C);_8=B($,O,ce,I,C);I8=B($,O,ce,I,C);N8=B($,O,ce,I,C);L8=B($,O,ce,I,C);Cse=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()}),Nse=Fd(Cse.shape),Ev=B($,O,I,C,E);Ose=Nr({}),_v=B($,O,I,C,E);Lse=h.z.array(Nr({})).min(1),Cv=B($,O,I,C,E);Dse=Nr({}),B8=B($,O,I,C,E);Use=Nr({}),F8=B($,O,I,C,E);Bse=Nr({}),H8=B($,O,I,C,E);Mse=h.z.object({conditionId:xe}),$8=B($,O,I,C,E);Fse=h.z.object({builderCode:bo}),V8=B($,O,I,C,E);qse=Nr({side:Nt}),Ov=B($,O,I,C,E);Hse=h.z.array(Nr({side:Nt})).min(1),Dv=B($,O,I,C,E);$se=Nr({}),Bv=B($,O,I,C,E);Vse=h.z.array(Nr({})).min(1),Mv=B($,O,I,C,E);jse=Nr({}),qv=B($,O,I,C,E);Wse=h.z.array(Nr({})).min(1),$v=B($,O,I,C,E);zse=Nr({}),jv=B($,O,I,C,E);Gse=h.z.array(Nr({})).min(1),zv=B($,O,I,C,E);Kse=h.z.object({cursor:ye.optional(),sponsored:h.z.boolean().optional()}).default({}),Kv=B($,O,I,C,E);Yse=h.z.object({conditionId:xe,cursor:ye.optional(),sponsored:h.z.boolean().optional()}),Qv=B($,O,I,C,E);j8=2*6e4,Zv=B($,O,I,C);Xse=h.z.object({plan:E4}),o6=10,mN="Collateral return",W8=B(O,I,C,E);tk=B(vt,$,O,ce,I,C,E);uO=100,dO=200,G8={maxOffset:dO,maxPageSize:uO},Zse=h.z.object({ascending:h.z.boolean().optional(),cursor:ye.optional(),pageSize:Ot.max(uO).default(20),getPositions:h.z.boolean().optional(),holdersOnly:h.z.boolean().optional(),order:h.z.string().optional(),parentEntityId:h.z.union([Gt,Hh]),parentEntityType:Js}),eie=h.z.object({getPositions:h.z.boolean().optional(),id:Xs}),tie=h.z.object({address:h.z.string(),ascending:h.z.boolean().optional(),cursor:ye.optional(),order:h.z.string().optional(),pageSize:Ot.max(uO).default(20)}),rk=B(Nl,$,O,I,C,E),nie=h.z.enum(["id","createdAt"]);sk=B($,O,I,C,E);ak=B(Nl,$,O,I,C,E);oie=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:re.optional(),endDateMin:re.optional(),ended:h.z.boolean().optional(),eventDate:zn.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:re.optional(),startDateMin:re.optional(),startTimeMax:re.optional(),startTimeMin:re.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()}),sie=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()})]),iie=h.z.object({id:h.z.string()}),ck=B($,O,I,C,E);dk=B($,O,I,C,E);mk=B($,O,I,C,E);lie=h.z.array(Fl).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct condition ids"),cie=h.z.array(H6).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct event ids"),uie=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:lie,eventIds:h.z.never().optional()}),h.z.object({questionId:h.z.never().optional(),conditionIds:h.z.never().optional(),eventIds:cie})]),fk=B($,O,I,C,E);die=h.z.object({eventIds:h.z.array(H6).min(1).transform(e=>[...new Set(e)])}),yk=B($,O,I,C,E);fie=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),window:bf.optional()}),wk=B($,O,I,C,E);gie=h.z.object({interval:i4.optional(),bucketLimit:h.z.number().int().positive().max(90).optional()}),kk=B($,O,I,C,E);pO=h.z.string().min(1),yie=h.z.object({category:pO.optional(),cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),sortBy:a4.optional(),window:bf.optional()}),Ak=B($,O,I,C,E);bie=h.z.object({category:pO.optional(),user:J,window:bf.optional()}),Sk=B($,O,I,C,E);wie=h.z.object({category:pO.optional(),cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),window:bf.optional()}),Pk=B($,O,I,C,E);vie=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(mf),h.z.array(h.z.enum(mf))]).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)}),Y8=B($,O,I,C,E);kie=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:re.optional(),endDateMin:re.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:re.optional(),startDateMin:re.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()}),xie=h.z.object({id:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),Aie=h.z.object({slug:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),Tie=h.z.object({url:h.z.string(),includeTag:h.z.boolean().optional(),locale:h.z.string().optional()}),Sie=h.z.union([xie,Aie,Tie]),Pie=h.z.object({id:h.z.string()}),_k=B($,O,I,C,E);Eie=h.z.object({cursor:ye.optional(),pageSize:Ot.max(100).optional(),exclude:h.z.array(xe).optional()}),Ik=B($,O,I,C,E);Nk=B($,O,I,C,E);Lk=B($,O,I,C,E);Rie=h.z.object({conditionIds:aa(Fl,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"]}))}),Uk=B($,O,I,C,E);_ie=360*60*60,Iie=253402300799,vN=wf.pipe(h.z.number().int().positive().max(Iie)),Q8=h.z.string().min(1).pipe(Me),X8={assetId:Q8,bucketSeconds:h.z.number().int().min(60).max(86400).optional(),cursor:ye.optional(),pageSize:Ot.max(1e4).default(1e4)},Cie=h.z.object({...X8,interval:t4,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"]})}),Nie=h.z.object({...X8,start:vN,end:vN.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>_ie&&n.addIssue({code:"custom",message:"start to end must span at most 15 days",path:["end"]})}),Oie=h.z.object({assetId:Q8,asOf:vN,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()}),Lie=h.z.union([Cie,Nie,Oie]),Mk=B($,O,I,C,E);Die=h.z.object({conditionIds:aa(Fl,20).optional()}),qk=B($,O,I,C,E);qie=h.z.object({orderId:h.z.string()}),Hie=h.z.object({orderIds:h.z.array(h.z.string()).min(1).max(3e3)}),$ie=h.z.object({market:h.z.string().optional()}),Vie=Fd($ie.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"]}),$k=B(O,$,ce,I,C,E);jk=B(O,$,ce,I,C,E);zk=B(O,$,ce,I,C);Kk=B(O,$,ce,I,C,E);Tf=h.z.object({assetId:Me,tokenId:h.z.never().optional()}),Sf=h.z.object({assetId:h.z.never().optional(),tokenId:Me}),J8=h.z.object({orderType:h.z.union([h.z.literal(cn.FAK),h.z.literal(cn.FOK)]).default(cn.FOK)}),c6=J8.extend({side:h.z.literal(Ue.BUY),amount:ko}),u6=J8.extend({side:h.z.literal(Ue.SELL),shares:ko}),jie=h.z.union([c6.extend(Tf.shape),c6.extend(Sf.shape),u6.extend(Tf.shape),u6.extend(Sf.shape)]).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t})),Xk=B(So,$,O,I,C,E);Kie=BigInt(Number.MAX_SAFE_INTEGER),Yie=h.z.string().refine(Xie,{message:"Order salt must be a non-negative JavaScript-safe integer."}),Z8=h.z.looseObject({salt:Yie}),Qie=h.z.array(Z8).min(1).max(15),ex=B($,O,ce,I,C,E),tx=B($,O,ce,I,C,E);t5=32,Jie=1n,Zie=2n,n5=3n,d6=50,eae=(1n<<256n)-1n,tae=(1n<<64n)-1n<<40n;nc=1000000n,rae=8*Number.EPSILON,hN=6,oae=8*Number.EPSILON;fN=600*1e3,AN=Number.POSITIVE_INFINITY,cae=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:A0(this.#t,e,fN,()=>this.#e.fetchBuilderTakerFeeRate(e))}async fetchCurrentMarket(e){let t=await A0(this.#r,e,AN,()=>this.#e.resolveCondition(e)),n=await this.#i(t);return this.#o(e,t,n),this.#s.set(t,p6(n,fN)),{feeInfo:n.feeInfo,negRisk:n.negRisk,tickSize:n.tickSize}}async#n(e){let t=await A0(this.#r,e,AN,()=>this.#e.resolveCondition(e)),n=await A0(this.#s,t,fN,()=>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,p6(e));return{feeInfo:t.feeInfo,negRisk:t.negRisk,tickSize:t.tickSize,assetIds:n}}};m6=new WeakMap;dae=180,h6=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()}),pae=h.z.union([h6.extend(Tf.shape),h6.extend(Sf.shape)]).superRefine((e,t)=>{if(e.expiration!==void 0){let n=Math.floor(Date.now()/1e3)+dae;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}));u5=h.z.object({builderCode:bo.optional(),orderType:h.z.union([h.z.literal(cn.FAK),h.z.literal(cn.FOK)]).default(cn.FAK)}),g6=u5.extend({side:h.z.literal(Ue.BUY),amount:ko,maxSpend:ko.optional(),maxPrice:ko.optional()}),y6=u5.extend({side:h.z.literal(Ue.SELL),shares:ko,minPrice:ko.optional()}),gae=h.z.union([g6.extend(Tf.shape),g6.extend(Sf.shape),y6.extend(Tf.shape),y6.extend(Sf.shape)]).transform(({assetId:e,tokenId:t,...n})=>({...n,assetId:e??t}));f5="Polymarket CTF Exchange",xae="DepositWallet",Aae="1",SN="0x0000000000000000000000000000000000000000000000000000000000000000",PN="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",Tae=Je.keccak256(we.fromString(PN),{as:"Hex"}),Sae=Je.keccak256(we.fromString("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),{as:"Hex"}),Pae=Je.keccak256(we.fromString(f5),{as:"Hex"}),g5=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],y5=[{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"}],Eae=[{name:"contents",type:"Order"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"}];k6="0x0000000000000000000000000000000000000000000000000000000000000000";vO=B(So,$,O,ce,I,C,E);kO=B($,O,ce,I,C,E);E5=vO;_5=kO;Oae=250,Lae=3e4,Dae={timeoutMs:h.z.number().int().positive().optional()},Uae=h.z.object(Dae).default({}),dx=B($,O,ce,tt,en,I,C,E);mx=B(vt,So,$,O,ce,I,C,E);hx=B(vt,So,$,O,ce,tt,en,I,C,E);gx=B(vt,$,O,ce,I,C,E);yx=B(vt,$,O,ce,tt,en,I,C,E);AO=h.z.string().regex(/^\d+(?:\.\d{1,28})?$/,"Expected a non-negative fixed-point fee rate with at most 28 fractional digits."),jae=h.z.object({builderAddress:J,feeRate:AO});Wae=h.z.object({address:J}),wx=B($,O,I,C,E);zae=h.z.strictObject({builder:J,maxFeeRate:AO,approvalVersion:h.z.number().int().positive().max(Number.MAX_SAFE_INTEGER)}),D5=h.z.strictObject({builderAddress:J.optional(),maxFeeRate:AO}),kx=B($,O,ce,I,C,E);kn=class{#e;#t;#r;#s;constructor({root:e,headers:t,resolveHeaders:n,onRateLimitUpdate:r}){this.#e=d0.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 In.fromPromise(e.then(async n=>{let r=Xae(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:I.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`}}},Zae=1e4,ele=3e4,tle=5e3,nle=10*6e4,rle=3e4,ole=25e3,sle=65e3,TO=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e("PING")},Zae)}handleMessage(e){return e!=="PONG"?!1:(this.#e=Date.now(),!0)}isStale(e){return e-this.#e>ele}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},U5=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=ud(()=>{e("PING")},tle)}handleMessage(){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>nle}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},B5=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>rle}},SO=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"}}))},ole)}handleMessage(){return this.#e=Date.now(),!1}isStale(e){return e-this.#e>sle}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0)}},M5=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}},ile=5e3,ale=250,lle=3e4,la=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)??ule(this.#t,{baseMs:ale,maxMs:lle});this.#t+=1,this.#e=yn(()=>{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:yn(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=cle(e.url,e.headers),s,i=()=>{o.removeEventListener("open",a),clearTimeout(s),this.#s=void 0,r(new I("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 I(`WebSocket connection failed: ${e.url}`,{cause:c}))};o.addEventListener("open",a,{once:!0}),this.#t!==void 0&&(this.#s=i,s=yn(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()},ile))}#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,()=>{})}};E0=1440*60*1e3,PO=90*E0,cr=h.z.number().int().nonnegative(),xx=h.z.object({start:cr.optional(),end:cr.optional()}),F5=h.z.object({interval:Vw,start:cr,end:cr.optional()}),ple=h.z.enum(["perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),mle=h.z.enum(["perpsEquityHistory","perpsPnlHistory"]),EO=h.z.object({kind:ple,startTimestamp:cr,endTimestamp:cr,instrumentId:Ae.optional(),depositStatus:kd.optional(),withdrawalStatus:xd.optional(),hash:et.optional(),seenKeys:h.z.array(h.z.string())}),q5=h.z.object({kind:mle,startTimestamp:cr,endTimestamp:cr,interval:Vw});ble=h.z.object({instrumentId:Ae.optional()}).default({});vle=h.z.object({instrumentId:Ae.optional()}).default({});xle=h.z.object({orderId:Cn.optional(),clientOrderId:Er.optional(),instrumentId:Ae.optional(),start:cr.optional(),end:cr.optional()}).default({}),Ale=xle.transform(({end:e,start:t,...n})=>({...n,endTimestamp:e,startTimestamp:t}));Sle=h.z.object({start:cr.optional(),end:cr.optional(),sort:II.optional(),cursor:ye.optional()});Ele=xx.extend({cursor:ye.optional(),instrumentId:Ae.optional()}),Rle=h.z.object({cursor:ye}),_le=h.z.union([Ele.transform(({cursor:e,...t})=>({cursor:e,params:Ax(t,E0)})),Rle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Cle=xx.extend({cursor:ye.optional(),depositStatus:kd.optional(),hash:et.optional()}),Nle=h.z.object({cursor:ye}),Ole=h.z.union([Cle.transform(({cursor:e,...t})=>({cursor:e,params:Ax(t,PO)})),Nle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Dle=xx.extend({cursor:ye.optional(),withdrawalStatus:xd.optional(),hash:et.optional()}),Ule=h.z.object({cursor:ye}),Ble=h.z.union([Dle.transform(({cursor:e,...t})=>({cursor:e,params:Ax(t,PO)})),Ule.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Fle=xx.extend({cursor:ye.optional()}),qle=h.z.object({kind:h.z.literal("perpsInternalTransfers"),startTimestamp:cr,endTimestamp:cr,seenKeys:h.z.array(h.z.string())}),Hle=h.z.object({cursor:ye}),$le=h.z.union([Fle.transform(({cursor:e,...t})=>({cursor:e,params:Ax(t,PO)})),Hle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);jle=F5.extend({cursor:ye.optional()}),Wle=h.z.object({cursor:ye}),zle=h.z.union([jle.transform(({cursor:e,...t})=>({cursor:e,params:H5(t)})),Wle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Kle=F5.extend({cursor:ye.optional()}),Yle=h.z.object({cursor:ye}),Qle=h.z.union([Kle.transform(({cursor:e,...t})=>({cursor:e,params:H5(t)})),Yle.transform(({cursor:e})=>({cursor:e,params:void 0}))]);Jle=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()}),Zle=h.z.object({sinceSeq:h.z.number().int().nonnegative().optional(),limit:h.z.number().int().positive().optional(),cursor:ye.optional()}),ece=h.z.object({cursor:ye}),tce=h.z.union([Zle.transform(({cursor:e,...t})=>({cursor:e,params:t})),ece.transform(({cursor:e})=>({cursor:e,params:void 0}))]);oce=h.z.object({ids:h.z.array(h.z.string().min(1)).min(1)}),sce=h.z.object({upTo:h.z.object({id:h.z.string().min(1),timestamp:h.z.number().int().nonnegative()})}),ice=h.z.union([oce.transform(({ids:e})=>({ids:e})),sce.transform(({upTo:e})=>({before:lce(e)}))]);dce=h.z.object({builder:J.optional()}).default({}),Tx=B($,O,I,C,E);mce=2160*60*60*1e3,gN=h.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),V5=h.z.object({start:gN.optional(),end:gN.optional(),asOfSequence:gN.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<=mce,{message:"The reporting window must not exceed 90 days",path:["end"]}).default({}),Sx=B($,O,I,C,E);Px=B($,O,I,C,E);_O=h.z.object({instrumentId:Ae,side:Nt,quantity:Ao,reduceOnly:h.z.boolean().default(!1),clientOrderId:Er.optional()}),gce=_O.extend({price:Ao,timeInForce:h.z.literal(ti.GTC),postOnly:h.z.boolean().default(!1)}),yce=_O.extend({price:Ao.optional(),timeInForce:h.z.literal(ti.IOC),postOnly:h.z.never().optional()}),bce=_O.extend({price:Ao.optional(),timeInForce:h.z.literal(ti.FOK),postOnly:h.z.never().optional()}),IO=h.z.discriminatedUnion("timeInForce",[gce,yce,bce]),T0=h.z.object({triggerPrice:Ao,limitPrice:Ao.optional()}),S0=h.z.object({triggerPrice:Ao}),wce=h.z.union([h.z.object({takeProfit:T0,stopLoss:T0.optional()}),h.z.object({takeProfit:T0.optional(),stopLoss:T0})]),vce=h.z.object({orders:h.z.array(IO).min(1),expiresAt:h.z.number().int().positive().optional()});xce=h.z.intersection(IO,h.z.intersection(wce,h.z.object({clientOrderId:Er.default(W5),expiresAt:h.z.number().int().positive().optional()}))),Ace=h.z.intersection(IO,h.z.object({clientOrderId:Er.default(W5),expiresAt:h.z.number().int().positive().optional(),takeProfit:h.z.never().optional(),stopLoss:h.z.never().optional()})),j5=h.z.array(cf).min(1).refine(e=>e.every(t=>t.status==="ok"),"Expected successful Perps order acknowledgements.");Ece=h.z.union([h.z.object({takeProfit:S0,stopLoss:S0.optional()}),h.z.object({takeProfit:S0.optional(),stopLoss:S0})]),Rce=h.z.intersection(Ece,h.z.object({instrumentId:Ae,expiresAt:h.z.number().int().positive().optional()}));EN=4,RN=2e3,Ice=100,Cce=1e3,Nce=h.z.object({maxAttempts:h.z.number().int().positive().default(EN),maxElapsedMs:h.z.number().int().positive().default(RN)}).default({maxAttempts:EN,maxElapsedMs:RN}),R0=h.z.object({expiresAt:h.z.number().int().positive().optional(),retry:h.z.union([h.z.literal(!1),Nce]).default({maxAttempts:EN,maxElapsedMs:RN}),signal:h.z.custom(e=>e instanceof AbortSignal,"Expected an AbortSignal.").optional()}),Oce=h.z.union([R0.extend({orderId:Cn,clientOrderId:h.z.undefined().optional()}),R0.extend({clientOrderId:Er,orderId:h.z.undefined().optional()})]);Dce=h.z.union([R0.extend({orderIds:h.z.array(Cn).min(1),clientOrderIds:h.z.undefined().optional()}),R0.extend({clientOrderIds:h.z.array(Er).min(1),orderIds:h.z.undefined().optional()})]);qce=h.z.object({instrumentId:Ae.optional(),expiresAt:h.z.number().int().positive().optional()}).default({});$ce=5e3,Vce=h.z.object({cancelAt:h.z.number().int().positive(),expiresAt:h.z.number().int().positive().optional()}).superRefine((e,t)=>{let n=Date.now()+$ce;e.cancelAt<n&&t.addIssue({code:"custom",message:"cancelAt must be at least 5 seconds in the future.",path:["cancelAt"]})}),Ex=B(df,$,O,ce,I,C,E),jce="auto_cancel_daily_limit_reached";zce=h.z.object({expiresAt:h.z.number().int().positive().optional()}).default({});Kce=h.z.object({instrumentId:Ae,leverage:h.z.number().int().positive(),crossMargin:h.z.boolean()}),Rx=B(O,ce,I,E);Qce=h.z.object({instrumentId:Ae,amount:Ao}),_x=B(O,ce,I,E);rue=3e4,yN=3e4,oue=2e3,sue=["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications","tpsl"],iue=new Set(["notifications","builderFills"]),aue=h.z.object({id:h.z.number().int().positive().optional(),data:h.z.unknown().optional()}).passthrough(),bN=h.z.union([lf,h.z.array(lf)]).transform(e=>Array.isArray(e)?e.find(t=>t.status==="err")??e[0]:e),Ix=B($,O,ce,I,C,E),G5=class{credentials;#e;#t;#r;#s;#n;#o;#i=new mi({heartbeat:new SO});#a=Bd({objectMode:!0});#u=new Map;#l=new Set;#c=new la;#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(M(e.builderAttribution,jae)),this.#d=typeof e.builderAttribution=="string"?M(e.builderAttribution,J):this.#m?.builderAddress,this.#t=new kn({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(W(tf)));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=A6(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=M(e,D5);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 I("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(W(tf)));this.#d=n.builder;let o=A6(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 pce(this.#t,e)}listBuilderEarnings(e){return hce(this.#t,e)}async fetchBuilderEarningsSummary(e){return await fce(this.#t,e)}async fetchBalances(){return await hle(this.#t)}async fetchPortfolio(){return await fle(this.#t)}async fetchStats(){return await gle(this.#t)}async fetchAccountConfig(e){return await wle(this.#t,e)}async fetchAutoCancelStatus(){return await yle(this.#t)}async fetchOpenOrders(e){return await kle(this.#t,e)}async fetchOrders(e){return await Tle(this.#t,e)}listFills(e={}){return Ple(this.#t,e)}listFundingPayments(e={}){return Ile(this.#t,e)}listDeposits(e={}){return Lle(this.#t,e)}listInternalTransfers(e={}){return Vle(this.#t,e)}listWithdrawals(e={}){return Mle(this.#t,e)}listEquityHistory(e){return Gle(this.#t,e)}listPnlHistory(e){return Xle(this.#t,e)}listNotifications(e={}){return nce(this.#t,e)}async fetchUnreadNotificationsCount(){return await rce(this.#t)}async markNotificationsRead(e){await ace(this.#t,e)}async placeOrder(e){return await Sce(this,e)}async postOrders(e){return await kce(this,e)}async placePositionTpSl(e){return await _ce(this,e)}async cancelOrder(e){return await Lce(this,e)}async cancelOrders(e){return await _N(this,e)}async cancelAllOrders(e){await Hce(this,e)}async armAutoCancel(e){await Wce(this.#t,(t,n)=>this.#k(t,n),e)}async disarmAutoCancel(e){await Gce(this.#t,(t,n)=>this.#k(t,n),e)}async updateLeverage(e){return await Yce(this,e)}async updateMargin(e){await Xce(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"},bN,rue,"Perps session authentication timed out.")}async#v(){await this.#w({id:this.#f++,req:"sub",chs:sue},bN,yN,"Perps session subscription timed out."),this.#h&&this.#w({id:this.#f++,req:"sub",chs:["builderFills"]},bN,yN,"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=C0(e.op),r=this.#k(e.op,e.expiresAt);return await this.#w({...r,id:this.#f++,op:n,req:"post"},t,yN,"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,oue),()=>{});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:C0(e.op)}}).andThen(W(e.responseSchema)))}#k(e,t){let n=uue(),r=Date.now(),o;try{o=Vae({chainId:this.#r,op:e,privateKey:this.credentials.privateKey,salt:n,timestamp:r})}catch(i){throw ce.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=lue(t);this.#u.set(e.id,o);let s=yn(()=>{o.reject(new I(r))},n);try{if(!this.#i.send(e))throw new I("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 I("Perps session closed.")),this.#I(new I("Perps session closed.")),this.#a.end(),await this.#i.close(),this.#n(this)}#S(e){if(this.#C(e)||HH.safeParse(e).success)return;let t=$H.safeParse(e);if(!t.success)return;let n=t.data;this.#O(n),this.#_(n)}#C(e){let t=aue.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=NO(t.data.data??t.data);return o!==void 0?n.reject(new O(o.error,{status:200})):n.reject(new I("Perps session unexpected response.")),!0}return cue(r.data)?n.reject(new O(r.data.error,{status:200})):n.resolve(r.data),!0}#N(){this.#R(new I("Perps session connection closed.")),this.#I(new I("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(iue.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.#_({channel:e.channel,previousSequence:t,reason:"sequence_gap",sequence:e.sequence,type:"resync"})}#_(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=yn(()=>{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)}#I(e){for(let t of Array.from(this.#l))this.#E(t),t.reject(e)}};sc=B($,O,I,C,E),ms=h.z.number().int().nonnegative(),K5=1440*60*1e3,pue=h.z.object({instrumentId:Ae.optional(),category:ef.optional()}).default({}),Cx=sc;mue=h.z.object({instrumentId:Ae}),Ox=sc;hue=h.z.object({instrumentId:Ae.optional()}).default({}),Dx=sc;fue=h.z.union([h.z.literal(10),h.z.literal(100),h.z.literal(500),h.z.literal(1e3)]),gue=h.z.object({instrumentId:Ae,depth:fue.default(100)}),Ux=sc;yue=h.z.object({instrumentId:Ae,interval:$w,start:ms.optional(),end:ms.optional(),cursor:ye.optional()}),bue=h.z.object({cursor:ye}),wue=h.z.union([yue.transform(({cursor:e,...t})=>({cursor:e,params:_ue(t)})),bue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Mx=sc;Y5=h.z.object({instrumentId:Ae,start:ms.optional(),end:ms.optional()}),vue=Y5.extend({cursor:ye.optional()}),kue=h.z.object({cursor:ye}),xue=h.z.union([vue.transform(({cursor:e,...t})=>({cursor:e,params:Q5(t)})),kue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Aue=Y5.extend({cursor:ye.optional()}),Tue=h.z.object({cursor:ye}),qx=sc;Sue=h.z.union([Aue.transform(({cursor:e,...t})=>({cursor:e,params:Q5(t)})),Tue.transform(({cursor:e})=>({cursor:e,params:void 0}))]),$x=sc;jx=B($,O,I,C);Pue=h.z.object({kind:h.z.literal("perpsCandles"),instrumentId:Ae,interval:$w,startTimestamp:ms,endTimestamp:ms}),Eue=h.z.object({kind:h.z.literal("perpsFundingHistory"),instrumentId:Ae,startTimestamp:ms,endTimestamp:ms}),Rue=h.z.object({kind:h.z.literal("perpsTrades"),instrumentId:Ae,startTimestamp:ms,endTimestamp:ms,seenTradeIds:h.z.array(ea)});Mue=h.z.custom(e=>$_(e),"Expected a hex-encoded 32-byte private key."),Fue=h.z.object({proxy:h.z.string().transform(e=>Be(e)),privateKey:Mue,secret:h.z.string().min(1),expiresAt:h.z.number().int().positive()}),que=10080*60*1e3,Hue=h.z.strictObject({builderAttribution:J.optional(),includeBuilderFills:h.z.boolean().optional(),expiresIn:h.z.number().int().positive().default(que),label:h.z.string().min(1).optional()}),$ue=h.z.strictObject({builderAttribution:J.optional(),includeBuilderFills:h.z.boolean().optional(),credentials:Fue}),Vue=h.z.union([Hue,$ue]),jue=h.z.object({proxy:h.z.string()}),Wue=jue.transform(e=>({proxy:Be(e.proxy)})),X5=h.z.bigint().positive().max(lr),zue=h.z.object({amount:X5,metadata:ur.optional()}),Gue=h.z.object({amount:X5}),Kue=Ao.refine(e=>/^\d+(?:\.\d+)?$/.test(e)&&/[1-9]/.test(e),"Expected a positive fixed-point decimal amount."),Yue=h.z.string().min(1).refine(e=>new TextEncoder().encode(e).byteLength<=64,"Expected a label no longer than 64 UTF-8 bytes."),Que=h.z.object({recipient:J,amount:Kue,label:Yue.optional()}),zx=B($,O,ce,I,C,E),Gx=B($,O,ce,I,C,E),J5=B(E),Kx=B(vt,$,O,ce,I,C,E),Yx=B($,O,ce,I,C,E),Qx=B($,O,ce,I,C,E);lde=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J.optional(),conditionId:h.z.union([Fl,aa(Fl,20)]).optional(),status:F$.optional(),eventId:h.z.array(Gt).min(1).optional(),filterType:H$.optional(),filterAmount:h.z.number().min(0).optional(),includeArchived:h.z.boolean().optional(),sortBy:q$.optional(),sortDirection:h0.optional(),window:D0.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"]}),nA=B($,O,I,C,E);cde=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"})]),ude=h.z.object({cursor:ye.optional(),pageSize:Ot.max(1e3).default(100),user:J,conditionId:h.z.union([Zt,aa(Zt,20)]).optional(),status:cde.optional(),sortBy:$$.optional(),sortDirection:h0.optional(),updatedAfter:wf.optional(),updatedBefore:wf.optional()}),dde=ude.refine(e=>e.updatedBefore===void 0||e.updatedAfter===void 0||e.updatedBefore>=e.updatedAfter,{message:"updatedBefore must not precede updatedAfter",path:["updatedBefore"]}),rA=B($,O,I,C,E);pde=h.z.object({user:J,conditionIds:aa(Fl,20).optional()}),oA=B($,O,I,C,E);mde=h.z.object({user:J}),sA=B($,O,I,C,E);hde=h.z.object({user:J,interval:JC.optional(),fidelity:p0.optional()}),iA=B($,O,I,C,E);fde=h.z.object({user:J,window:D0.optional()}),aA=B($,O,I,C,E);gde=h.z.object({user:h.z.string()}),lA=B($,O,I,C,E);cA=B($,O,I,C,E),nV=h.z.object({amount:h.z.bigint().min(0n),conditionId:xe,metadata:ur.optional()}),rV=cA;oV=h.z.object({amount:h.z.bigint().positive(),legs:h.z.array(Xe).min(1).max(50),metadata:ur.optional()}),sV=cA;bde=h.z.union([nV.extend({legs:h.z.never().optional()}),oV.extend({conditionId:h.z.never().optional()})]);Vd=B(vt,$,O,ce,tt,en,I,C,E),iV=Vd;lV=Vd;mA=B($,O,I,C,E),uV=h.z.object({amount:h.z.union([h.z.bigint().positive(),h.z.literal("max")]),conditionId:xe,metadata:ur.optional()}),dV=mA;pV=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()}),mV=mA;wde=h.z.union([uV.extend({legs:h.z.never().optional()}),pV.extend({conditionId:h.z.never().optional()})]);jd=B(vt,$,O,ce,tt,en,I,C,E),hV=jd;gV=jd;yA=B($,O,I,C,E),bV=h.z.object({conditionId:xe,marketId:h.z.never().optional(),amount:h.z.never().optional(),positionId:h.z.never().optional(),metadata:ur.optional()}),wV=h.z.object({conditionId:h.z.never().optional(),marketId:Qi,amount:h.z.never().optional(),positionId:h.z.never().optional(),metadata:ur.optional()}),vde=h.z.union([bV,wV]),vV=yA;kV=h.z.object({positionId:Xe,conditionId:h.z.never().optional(),marketId:h.z.never().optional(),metadata:ur.optional()});xV=yA;kde=h.z.union([bV,wV,kV]);wA=B(vt,$,O,ce,tt,en,I,C,E);Pde=h.z.object({address:h.z.string()}),kA=B($,O,I,C,E);ic=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}},AA=B(Qr,ic,ce,tt,I,E),ac=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}},TA=B(Qr,ac,tt,I),lc=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}},SA=B(Qr,lc,tt,I),PA=B(Qr,I,E);FO="/v1/builder/rfq/requests",Ede=3e4,Rde=3e4,_de=3e4,Ide=500,Cde=3e4,Nde=1e3,Ode="0x0000000000000000000000000000000000000000000000000000000000000000",fs=class extends Ct{name="RfqRequestRejectedError";status;code;constructor(e,t){super(e,t),this.status=t.status,this.code=t.code}};Lde=new Set(Object.values(li));P6=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})),N0=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=Dde(r,o);return s<=0n?(t.addIssue({code:"custom",message:"Value must be greater than 0."}),h.z.NEVER):s.toString()});Ude=h.z.discriminatedUnion("direction",[h.z.object({amount:N0,direction:h.z.literal(Ue.BUY),legPositionIds:P6,side:h.z.literal(Eo.Yes).optional()}),h.z.object({direction:h.z.literal(Ue.SELL),legPositionIds:P6,side:h.z.literal(Eo.Yes).optional(),size:N0})]),RA=B($,fs,I,C,E);Fde=Nt,qde=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(xw),direction:Fde,expiresAt:h.z.number().int().nonnegative(),makerAmount:N0.transform(Tl),netReceive:h.z.string().optional(),positionId:h.z.string().regex(/^\d+$/,"positionId must be a numeric string.").transform(Tw),quoteId:h.z.string().min(1).transform(Sw),rfqId:h.z.string().min(1).transform(md),takerAmount:N0.transform(Tl),totalRequired:h.z.string()}),IA=B(vt,$,fs,ce,tt,I,C,E);zde=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()}),NA=B($,fs,tt,I,C,E);Gde=h.z.object({rfqId:h.z.string().min(1).transform(md)}),LA=B($,fs,I,C,E);Wd=(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))(Wd||{}),E6=100,Kde=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(Wd).optional()}),UA=B(Nl,$,O,I,C,E);Qde=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()}),Xde=h.z.object({id:h.z.string(),locale:h.z.string().optional()}),MA=B($,O,I,C,E);qA=B($,O,I,C,E);$A=B($,O,ce,I,C,E);Jde=[yo.ALL],Zde=4315*60*60,RV=300*1e3,epe=h.z.object({address:J,idempotencyKey:h.z.string().trim().min(1).optional(),scopes:h.z.array(Nh).min(1).default(Jde)}).superRefine((e,t)=>{zt(e.address,rs)&&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())})),VA=B(vt,$,O,ce,tt,en,I,C,E);tpe=h.z.object({address:J,idempotencyKey:h.z.string().trim().min(1).optional()}).superRefine((e,t)=>{zt(e.address,rs)&&t.addIssue({code:"custom",message:"Session key address must not be the zero address.",path:["address"]})}).transform(e=>({...e,address:Be(e.address.toLowerCase())})),WA=B(vt,$,O,ce,tt,en,I,C,E);GA=B($,O,I,C);YA=B($,O,I,C);spe=h.z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._:/-]+$/),R6=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."}),_V=(e=>(e.Update="update",e.Subscribe="subscribe",e))(_V||{}),ipe=h.z.discriminatedUnion("topic",[h.z.strictObject({topic:h.z.literal("prices.crypto"),symbols:h.z.array(R6).min(1)}),h.z.strictObject({topic:h.z.literal("prices.crypto.twap"),symbols:h.z.array(R6).min(1)}),h.z.strictObject({topic:h.z.literal("prices.equity"),symbol:spe,types:h.z.array(h.z.enum(_V)).optional()})]);XA=B(I,E,O,Qr),IV=(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))(IV||{}),lpe=h.z.object({topic:h.z.enum(IV)}),cpe=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()}),upe=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()})]);mpe=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)}),hpe=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()})]),fpe=h.z.object({id:h.z.string(),omitEmpty:h.z.boolean().optional(),status:h.z.enum(["active","closed","all"]).optional()}),gpe=h.z.object({slug:h.z.string()}),ype=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()}),bpe=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()}),JA=B($,O,I,C,E);eT=B($,O,I,C,E);nT=B($,O,I,C,E);oT=B($,O,I,C,E);wpe=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()}),iT=B($,O,I,C,E);vpe=h.z.object({amount:h.z.bigint(),metadata:ur.optional(),recipientAddress:J,tokenAddress:J}),CV=B(E);lT=B(vt,$,O,ce,I,C,E)});var rj={};fr(rj,{AcceptComboQuoteError:()=>IA,ActivityType:()=>m0,ApproveErc1155ForAllError:()=>vv,ApproveErc20Error:()=>wv,ApprovePerpsBuilderFeeError:()=>kx,ArmPerpsAutoCancelError:()=>Ex,AssetType:()=>ra,AuthorizeSessionKeyError:()=>VA,AutoCancelDailyLimitError:()=>df,BiggestWinnerKind:()=>Yl,BuilderVolumeInterval:()=>Gl,CancelAllError:()=>zk,CancelMarketOrdersError:()=>Kk,CancelOrderError:()=>$k,CancelOrdersError:()=>jk,CancelledSigningError:()=>vt,CollateralReturnKnownOperationKind:()=>Dd,CombinatorialPrepareConditionCallError:()=>a8,ComboAcceptFailureReason:()=>Ro,ComboActivityType:()=>Wl,ComboKnownStatus:()=>Iw,ComboPositionSortBy:()=>$l,ComboPositionStatus:()=>ii,ComboQuoteUnavailableReason:()=>ci,CommentParentEntityType:()=>Ch,ConnectionLostError:()=>Qr,CreateLimitOrderError:()=>gx,CreateMarketOrderError:()=>mx,CreateSecureClientError:()=>Mme,CtfMergePositionsCallError:()=>n8,CtfRedeemPositionsCallError:()=>r8,CtfSplitPositionCallError:()=>t8,DepositToPerpsError:()=>Kx,DownloadAccountingSnapshotError:()=>lA,DropNotificationsError:()=>W0,Erc20ApprovalCallError:()=>J6,Erc20TransferCallError:()=>Z6,EstimateMarketPriceError:()=>Xk,ExecuteCollateralReturnPlanError:()=>tk,FetchBuilderVolumeError:()=>kk,FetchClosedOnlyModeError:()=>U0,FetchCommentsByIdError:()=>sk,FetchEventError:()=>dk,FetchEventLiveVolumeError:()=>yk,FetchEventTagsError:()=>mk,FetchLastTradePriceError:()=>jv,FetchLastTradePricesError:()=>zv,FetchMarketError:()=>Nk,FetchMarketTagsError:()=>Lk,FetchMidpointError:()=>_v,FetchMidpointsError:()=>Cv,FetchNotificationsError:()=>V0,FetchOpenInterestError:()=>qk,FetchOrderBookError:()=>Bv,FetchOrderBooksError:()=>Mv,FetchOrderError:()=>q0,FetchOrderScoringError:()=>K0,FetchOrdersScoringError:()=>Q0,FetchPerpsBookError:()=>Ux,FetchPerpsBuilderApprovalsError:()=>Tx,FetchPerpsBuilderEarningsSummaryError:()=>Px,FetchPerpsBuilderStatusError:()=>wx,FetchPerpsFeesError:()=>jx,FetchPerpsInstrumentsError:()=>Cx,FetchPerpsTickerError:()=>Ox,FetchPerpsTickersError:()=>Dx,FetchPortfolioValueError:()=>oA,FetchPriceError:()=>Ov,FetchPricesError:()=>Dv,FetchPublicProfileError:()=>kA,FetchRelatedTagResourcesError:()=>oT,FetchRelatedTagsError:()=>nT,FetchResolutionsError:()=>fk,FetchRewardPercentagesError:()=>ov,FetchRfqStatusError:()=>LA,FetchSeriesError:()=>qA,FetchSessionKeysError:()=>$A,FetchSportsMarketTypesError:()=>YA,FetchSpreadError:()=>qv,FetchSpreadsError:()=>$v,FetchTagError:()=>eT,FetchTotalEarningsForUserForDayError:()=>ev,FetchTraderLeaderboardStandingError:()=>Sk,FetchTradingApprovalsStateError:()=>kv,FetchUserPnlError:()=>iA,FetchUserStatsError:()=>sA,FetchUserVolumeError:()=>aA,InsufficientLiquidityError:()=>So,LeaderboardWindow:()=>zl,ListAccountTradesError:()=>$0,ListActivityError:()=>lv,ListBiggestWinnersError:()=>Pk,ListBuilderLeaderboardError:()=>wk,ListBuilderTradesError:()=>Ev,ListComboActivityError:()=>cv,ListComboMarketsError:()=>Ik,ListComboPositionsError:()=>rA,ListCommentsByUserAddressError:()=>ak,ListCommentsError:()=>rk,ListCurrentRewardsError:()=>Kv,ListEventsError:()=>ck,ListMarketHoldersError:()=>Uk,ListMarketRewardsError:()=>Qv,ListMarketsError:()=>_k,ListOpenOrdersError:()=>M0,ListPerpsBuilderEarningsError:()=>Sx,ListPerpsCandlesError:()=>Mx,ListPerpsFundingHistoryError:()=>qx,ListPerpsTradesError:()=>$x,ListPositionsError:()=>nA,ListPriceHistoryError:()=>Mk,ListSeriesError:()=>MA,ListSportsError:()=>GA,ListTagsError:()=>JA,ListTeamsError:()=>iT,ListTraderLeaderboardError:()=>Ak,ListTradesError:()=>iv,ListUserEarningsAndMarketsConfigError:()=>nv,ListUserEarningsForDayError:()=>J0,MAX_UINT256:()=>lr,MergePositionsError:()=>jd,NotificationType:()=>n0,OpenPerpsSessionError:()=>zx,OpenRfqSessionError:()=>PA,OperationAbortedError:()=>Jw,OrderPostStatus:()=>r0,OrderResponseErrorCode:()=>o0,OrderSide:()=>Ue,OrderType:()=>cn,PaginationLimitError:()=>Nl,PerpsCancelRetryError:()=>Zw,PerpsDepositCallError:()=>e8,PerpsDepositStatus:()=>Qh,PerpsInstrumentCategory:()=>Kh,PerpsInstrumentType:()=>Gh,PerpsInternalTransferDirection:()=>Xh,PerpsKlineInterval:()=>Jh,PerpsKnownCancelOrderErrorCode:()=>Sd,PerpsKnownInternalTransferType:()=>Hw,PerpsKnownWithdrawalStatus:()=>qw,PerpsLiquidityRole:()=>nf,PerpsMarginType:()=>sf,PerpsNotificationOrderType:()=>of,PerpsNotificationType:()=>rf,PerpsOrderStatus:()=>af,PerpsSide:()=>Yh,PerpsSortDirection:()=>Zh,PerpsTimeInForce:()=>ti,PlaceLimitOrderError:()=>yx,PlaceMarketOrderError:()=>hx,PlanCollateralReturnError:()=>Zv,PositionFilterType:()=>Hl,PositionSortBy:()=>ql,PositionStatus:()=>ai,PostOrderError:()=>ex,PostOrdersError:()=>tx,PriceHistoryInterval:()=>Po,ProtocolVersion:()=>Zi,RateLimitError:()=>$,RealtimeKnownErrorCode:()=>Ed,RedeemPositionsError:()=>wA,RequestComboQuoteError:()=>RA,RequestRejectedError:()=>O,ResolutionMarketType:()=>Xl,ResolutionReporter:()=>Zl,ResolutionSource:()=>Jl,ResolutionStatus:()=>Ql,RevokePerpsBuilderFeeError:()=>Ix,RevokePerpsCredentialsError:()=>Gx,RevokeSessionKeyError:()=>WA,RfqCancelQuoteError:()=>TA,RfqCancelQuoteRejectedError:()=>ac,RfqConfirmationDecision:()=>ds,RfqConfirmationError:()=>SA,RfqConfirmationRejectedError:()=>lc,RfqDirection:()=>Nn,RfqExecutionStatus:()=>ps,RfqKnownErrorCode:()=>Cr,RfqQuoteError:()=>AA,RfqQuoteRejectedError:()=>ic,RfqRejectionCode:()=>li,RfqRequestRejectedError:()=>fs,RfqRequestedSizeUnit:()=>Xr,RfqSide:()=>Eo,RfqStatus:()=>mn,RouterMergeCallError:()=>s8,RouterRedeemCallError:()=>i8,RouterSplitCallError:()=>o8,SearchError:()=>UA,SearchSort:()=>Wd,SessionKeyKnownScope:()=>yo,SetupGaslessWalletError:()=>Fme,SetupTradingApprovalsError:()=>xv,SignatureType:()=>Rr,SignerType:()=>LN,SigningError:()=>ce,SortDirection:()=>Bl,SplitPositionError:()=>Vd,SubscribeError:()=>XA,TeamOrdering:()=>$h,TimeoutError:()=>tt,TipSide:()=>Ul,TradeFilterType:()=>Ml,TraderLeaderboardSort:()=>Kl,TradingRestriction:()=>_C,TransactionFailedError:()=>en,TransferErc20Error:()=>lT,TransferPerpsCollateralError:()=>Qx,TransportError:()=>I,UnexpectedResponseError:()=>C,UpdatePerpsLeverageError:()=>Rx,UpdatePerpsMarginError:()=>_x,UserInputError:()=>E,UserPnlFidelity:()=>jl,UserPnlInterval:()=>Vl,WaitForComboFillError:()=>NA,WaitForOrderFillSettlementError:()=>dx,WaitForTransactionError:()=>l8,WalletType:()=>Se,WebSocketKnownCloseCode:()=>RC,WithdrawFromPerpsError:()=>Yx,accountActions:()=>WO,allActions:()=>WV,analyticsActions:()=>zO,authorizeSessionSignerCall:()=>jN,buildHmacSignature:()=>GV,combinatorialPrepareConditionCall:()=>pv,createPublicClient:()=>nj,createSecureClient:()=>qme,ctfMergePositionsCall:()=>KN,ctfRedeemPositionsCall:()=>YN,ctfSplitPositionCall:()=>GN,dataActions:()=>GO,decodeErc1155BalanceOfBatchResult:()=>Cf,decodeErc1155BalanceOfResult:()=>VN,decodeErc1155IsApprovedForAllResult:()=>HN,decodeErc20AllowanceResult:()=>FN,discoveryActions:()=>KO,encodeProxyCall:()=>XN,encodeSafeMultisendCall:()=>JN,erc1155ApprovalForAllCall:()=>kf,erc1155BalanceOfBatchCall:()=>If,erc1155BalanceOfCall:()=>$N,erc1155IsApprovedForAllCall:()=>qN,erc20AllowanceCall:()=>MN,erc20ApprovalCall:()=>vf,erc20TransferCall:()=>P0,expectTransactionHandle:()=>wn,forkEnvironmentConfig:()=>zV,makeErrorGuard:()=>B,perpsActions:()=>YO,perpsDepositCall:()=>zN,preproduction:()=>Cpe,production:()=>ZO,relayerApiKey:()=>Tpe,remoteBuilderSigning:()=>Ape,revokeSessionSignerCall:()=>WN,rewardsActions:()=>QO,rfqActions:()=>$V,routerMergeCall:()=>dv,routerRedeemCall:()=>xf,routerSplitCall:()=>uv,sessionKeyActions:()=>VV,subscriptionsActions:()=>XO,tradingActions:()=>jV,walletActions:()=>JO});function Ape(e){return new Spe(e)}function Tpe(e){return new Ppe(e)}function Epe(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 Rpe(e){return{listPositions:Wf.bind(null,e),listComboPositions:zf.bind(null,e),fetchPortfolioValue:Gf.bind(null,e),fetchTraderLeaderboardStanding:Mf.bind(null,e),fetchUserStats:Kf.bind(null,e),fetchUserPnl:Yf.bind(null,e),fetchUserVolume:Qf.bind(null,e),downloadAccountingSnapshot:Xf.bind(null,e),listActivity:Rf.bind(null,e),listComboActivity:_f.bind(null,e)}}function gs(e,t={}){return t===null||typeof t!="object"||Array.isArray(t)?t:{...t,user:t.user===void 0?e.account.wallet:t.user}}function WO(e){let t=Rpe(e);return e.isPublicClient()?t:{...t,listPositions:n=>Wf(e,gs(e,n)),listComboPositions:n=>zf(e,gs(e,n)),fetchPortfolioValue:n=>Gf(e,gs(e,n)),fetchTraderLeaderboardStanding:n=>Mf(e,gs(e,n)),fetchUserStats:n=>Kf(e,gs(e,n)),fetchUserPnl:n=>Yf(e,gs(e,n)),fetchUserVolume:n=>Qf(e,gs(e,n)),downloadAccountingSnapshot:n=>Xf(e,gs(e,n)),listActivity:n=>Rf(e,gs(e,n)),listComboActivity:n=>_f(e,gs(e,n)),listAccountTrades:Ef.bind(null,e),fetchNotifications:j0.bind(null,e),dropNotifications:z0.bind(null,e),fetchClosedOnlyMode:B0.bind(null,e)}}function zO(e){return{listBuilderTrades:Rv.bind(null,e),listBuilderLeaderboard:vk.bind(null,e),fetchBuilderVolume:xk.bind(null,e),listTraderLeaderboard:Tk.bind(null,e),listBiggestWinners:Ek.bind(null,e)}}function GO(e){return{fetchEventLiveVolume:bk.bind(null,e),fetchResolutions:gk.bind(null,e),fetchMidpoint:Iv.bind(null,e),fetchMidpoints:Nv.bind(null,e),fetchPrice:Lv.bind(null,e),fetchPrices:Uv.bind(null,e),fetchOrderBook:Hd.bind(null,e),fetchOrderBooks:Fv.bind(null,e),fetchSpread:Hv.bind(null,e),fetchSpreads:Vv.bind(null,e),fetchLastTradePrice:Wv.bind(null,e),fetchLastTradePrices:Gv.bind(null,e),listPriceHistory:Fk.bind(null,e),estimateMarketPrice:Jk.bind(null,e),fetchOpenInterest:Hk.bind(null,e),listMarketHolders:Bk.bind(null,e),listTrades:av.bind(null,e)}}function KO(e){return{listEvents:uk.bind(null,e),fetchEvent:pk.bind(null,e),fetchEventTags:hk.bind(null,e),listMarkets:Ff.bind(null,e),listComboMarkets:Ck.bind(null,e),fetchMarket:Ok.bind(null,e),fetchMarketTags:Dk.bind(null,e),listSeries:FA.bind(null,e),fetchSeries:HA.bind(null,e),listMarketClarifications:Rk.bind(null,e),listTags:ZA.bind(null,e),fetchTag:tT.bind(null,e),fetchRelatedTags:rT.bind(null,e),fetchRelatedTagResources:sT.bind(null,e),search:BA.bind(null,e),listSports:KA.bind(null,e),fetchSportsMarketTypes:QA.bind(null,e),listTeams:aT.bind(null,e),fetchPublicProfile:xA.bind(null,e),listComments:ok.bind(null,e),fetchCommentsById:ik.bind(null,e),listCommentsByUserAddress:lk.bind(null,e)}}function YO(e){let t={fetchPerpsBuilderStatus:vx.bind(null,e),fetchPerpsBook:n=>Bx(e,n),fetchPerpsFees:()=>Wx(e),fetchPerpsInstruments:n=>Nx(e,n),fetchPerpsTicker:n=>Lx(e,n),fetchPerpsTickers:n=>jf(e,n),listPerpsCandles:n=>Fx(e,n),listPerpsFundingHistory:n=>Hx(e,n),listPerpsTrades:n=>Vx(e,n)};return e.isSecureClient()?{...t,depositToPerps:n=>Zx(e,n),openPerpsSession:n=>Xx(e,n),revokePerpsCredentials:n=>Jx(e,n),transferPerpsCollateral:tA.bind(null,e),withdrawFromPerps:n=>eA(e,n)}:t}function _pe(e){return{listCurrentRewards:Yv.bind(null,e),listMarketRewards:Xv.bind(null,e)}}function QO(e){let t=_pe(e);return e.isPublicClient()?t:{...t,fetchOrderScoring:Y0.bind(null,e),fetchOrdersScoring:X0.bind(null,e),listUserEarningsForDay:Z0.bind(null,e),fetchTotalEarningsForUserForDay:tv.bind(null,e),listUserEarningsAndMarketsConfig:rv.bind(null,e),fetchRewardPercentages:sv.bind(null,e)}}function $V(e){return{openRfqSession(){return EA(e)},requestComboQuote(t){return _A(e,t)},acceptComboQuote(t){return CA(e,t)},waitForComboFill(t){return OA(e,t)}}}function VV(e){return{authorizeSessionKey:jA.bind(null,e),fetchSessionKeys:zd.bind(null,e),revokeSessionKey:zA.bind(null,e)}}function XO(e){return e.isSecureClient()?{subscribe(t){return Zf(e,t)}}:{subscribe(t){return Zf(e,t)}}}function jV(e){return{createMarketOrder:Hf.bind(null,e),placeMarketOrder:fx.bind(null,e),createLimitOrder:$f.bind(null,e),placeLimitOrder:bx.bind(null,e),postOrder:$d(e),postOrders:nx(e),waitForOrderFillSettlement:px.bind(null,e),cancelOrder:Vk.bind(null,e),cancelOrders:Wk.bind(null,e),cancelAll:Gk.bind(null,e),cancelMarketOrders:Yk.bind(null,e),listOpenOrders:F0.bind(null,e),fetchOrder:H0.bind(null,e)}}function Ipe(e){return{fetchTradingApprovalsState:Bf.bind(null,e)}}function JO(e){let t=Ipe(e);return e.isPublicClient()?t:{...t,fetchTradingApprovalsState:()=>Bf(e,{user:e.account.wallet}),setupTradingApprovals:Av.bind(null,e),approveErc20:Df.bind(null,e),approveErc1155ForAll:Uf.bind(null,e),transferErc20:cT.bind(null,e),splitPosition:pA.bind(null,e),mergePositions:gA.bind(null,e),redeemPositions:vA.bind(null,e),planCollateralReturn:ek.bind(null,e),executeCollateralReturnPlan:nk.bind(null,e)}}function WV(e){return e.isSecureClient()?{...WO(e),...zO(e),...GO(e),...KO(e),...YO(e),...QO(e),...$V(e),...VV(e),...XO(e),...jV(e),...JO(e)}:{...WO(e),...zO(e),...GO(e),...KO(e),...YO(e),...QO(e),...XO(e),...JO(e)}}function zV(e,t=ZO){return{...t,...e,walletDerivation:{...t.walletDerivation,...e.walletDerivation},contracts:{...t.contracts,...e.contracts},clob:{...Gd(t.clob,e.clob),market:eg(t.clob.market,e.clob?.market),user:eg(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:{...NV(t.combos,e.combos),builderGateway:Gd(t.combos.builderGateway,e.combos?.builderGateway),collateralReturn:Gd(t.combos.collateralReturn,e.combos?.collateralReturn)},perps:NV(t.perps,e.perps),realtime:eg(t.realtime,e.realtime),rtds:eg(t.rtds,e.rtds),sports:eg(t.sports,e.sports)}}function Gd(e,t){return{...e,...t,headers:eL(e.headers,t?.headers)}}function eg(e,t){return{...e,...t,headers:eL(e.headers,t?.headers)}}function NV(e,t){return{...e,...t,headers:eL(e.headers,t?.headers)}}function eL(e,t){if(!(e===void 0&&t===void 0))return{...e,...t}}async function GV(e,t,n,r,o){let s=`${t}${n}${r}`;o!==void 0&&(s+=o);let i=await globalThis.crypto.subtle.importKey("raw",Npe(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(s));return Lpe(Ope(a))}function Npe(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 Ope(e){let t=new Uint8Array(e),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function Lpe(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}function ng(e,t){let n;return{close:()=>(n===void 0&&(n=Promise.resolve(e.return()).then(()=>t())),n),[Symbol.asyncIterator](){return e[Symbol.asyncIterator]()}}}function OV(e,t,n){let r=pT(n.assetsIds,t.assetsIds),o=pT(t.assetsIds,n.assetsIds);r.length>0&&e(DV(r,n.customFeatureEnabled));let s=n.assetsIds[0];r.length===0&&t.customFeatureEnabled!==n.customFeatureEnabled&&s!==void 0&&e(DV([s],n.customFeatureEnabled)),o.length>0&&e(Mpe(o))}function LV(e,t,n){if(n.includeAllMarkets){!t.includeAllMarkets&&t.markets.length>0&&e(BV(t.markets));return}if(t.includeAllMarkets){n.markets.length>0&&e(UV(n.markets));return}let r=pT(n.markets,t.markets),o=pT(t.markets,n.markets);r.length>0&&e(UV(r)),o.length>0&&e(BV(o))}function Dpe(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 Upe(e){let t=!1,n=new Set;for(let{subscription:r}of e){if(KV(r)){t=!0;continue}for(let o of r.markets??[])n.add(o)}return{includeAllMarkets:t,markets:t?[]:Array.from(n)}}function Bpe(e){return{assets_ids:e.assetsIds,custom_feature_enabled:e.customFeatureEnabled,type:"market"}}function DV(e,t){return{assets_ids:e,custom_feature_enabled:t,operation:"subscribe"}}function Mpe(e){return{assets_ids:e,operation:"unsubscribe"}}function Fpe(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 UV(e){return{markets:e,operation:"subscribe"}}function BV(e){return{markets:e,operation:"unsubscribe"}}function qpe(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 Hpe(e){if(KV(e))return()=>!0;let t=new Set((e.markets??[]).map(n=>n.toLowerCase()));return n=>t.has(n.payload.market.toLowerCase())}function KV(e){return(e.markets?.length??0)===0}function pT(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}function jpe(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(Wpe(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 MV(e,t){return Array.from(t).filter(n=>!e.has(n))}function FV(e,t){return Array.from(e).filter(n=>!t.has(n))}function Wpe(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:fe(!1,`Unknown Perps topic: ${String(e)}`)}}function zpe(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:fe(!1,`Unknown Perps topic: ${String(e)}`)}}function Gpe(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 Kpe(e,t){return Math.random()*(e===4003?1e4:Math.min(1e3*2**t,3e4))}function Qpe(e){return new Promise((t,n)=>{let r=yn(()=>{n(new I("Realtime subscription was not accepted within 30 seconds."))},3e4);e.then(()=>{clearTimeout(r),t()},o=>{clearTimeout(r),n(o)})})}function Xpe(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 Zpe(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 nme(e,t){return{...t,quote:n=>e.quote(t,n)}}function rme(e,t){let n=t.rfqId,r=t.quoteId;return{...t,confirm:()=>e.respondToConfirmation(n,r,ds.Confirm),decline:()=>e.respondToConfirmation(n,r,ds.Decline)}}function ome(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function sme(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function ime(e){return{quoteId:e.quoteId,rfqId:e.rfqId}}function ame(e,t){let n=rc(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 lme(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 cme(e,t,n){let r=rc(e);return{maker_address:r.maker,quote_id:n,rfq_id:t,signer_address:r.signer,type:"RFQ_QUOTE_CANCEL"}}function ume(e,t,n){return{decision:n,quote_id:t,rfq_id:e,type:"RFQ_CONFIRMATION_RESPONSE"}}function pme(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}async function mme(e){let t=rc(e.account),n=wO({chainId:e.chainId,exchange:e.exchange}),r={builder:qV,maker:t.maker,makerAmount:b5(e.orderSide,e.orderPrice,e.size),metadata:qV,salt:hme().toString(),side:ax(e.orderSide),signatureType:t.signatureType,signer:t.signer,takerAmount:w5(e.orderSide,e.orderPrice,e.size),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:e.tokenId},o;try{o=await e.signer.signTypedData(sx({domain:n,order:r}))}catch(s){throw ce.fromError(s,"Could not sign the RFQ quote order.")}return{...r,signature:ix({domain:n,order:r,signature:o})}}function hme(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)}function gme(e){return M(e,fme)}async function yme(e){let t=e.response.price,n=e.response.size===void 0?kme(e.request.requestedSize,t):e.response.size,r=await mme({account:e.account,chainId:e.chainId,exchange:e.exchange,orderPrice:wme(e.request,e.response.source,t),orderSide:vme(e.response.source),signer:e.signer,size:n,tokenId:bme(e.request,e.response.source)});return{price:t,signedOrder:r,size:n}}function bme(e,t){return e.direction===Nn.Buy?t==="collateral"?e.noPositionId:e.yesPositionId:t==="collateral"?e.yesPositionId:e.noPositionId}function wme(e,t,n){return e.direction===Nn.Buy&&t==="collateral"||e.direction===Nn.Sell&&t==="inventory"?1000000n-n:n}function vme(e){return e==="collateral"?Ue.BUY:Ue.SELL}function kme(e,t){let n=XV(e.value);return e.unit===Xr.Shares?n:n*1000000n/t}function XV(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 dT(e){return`ACK_RFQ_QUOTE:${e}`}function VO(e,t){return`ACK_RFQ_QUOTE_CANCEL:${e}:${t}`}function jO(e,t){return`ACK_RFQ_CONFIRMATION_RESPONSE:${e}:${t}`}function Pme(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}function Eme(e,t){return Array.from(t).flatMap(([n,r])=>e.has(n)?[]:[r])}function Rme(e,t){return Array.from(e).flatMap(([n,r])=>t.has(n)?[]:[r])}function _me(e){let t=new Map;for(let{subscription:n}of e)for(let r of Nme(n))t.has(r.key)||t.set(r.key,r);return t}function Ime(e){return{action:"subscribe",subscriptions:e.map(({topic:t,type:n})=>({topic:t,type:n}))}}function Cme(e){return{action:"unsubscribe",subscriptions:e.map(({topic:t,type:n})=>({topic:t,type:n}))}}function Nme(e){switch(e.topic){case"comments":return(e.types??["comment_created"]).map(t=>tg("comments",t));case"prices.crypto.binance":return[tg("crypto_prices","update")];case"prices.crypto.chainlink":return[tg("crypto_prices_chainlink","update")];case"prices.crypto.chainlink.twap":return[tg(Ome(e.windowSeconds),"update")];case"prices.equity.pyth":return[tg("equity_prices","update")];default:fe(!1,`Unknown RTDS topic: ${String(e)}`)}}function Ome(e){switch(e){case 30:return"crypto_prices_twap_thirty";case 60:return"crypto_prices_twap_sixty";default:fe(!1,`Unknown TWAP window: ${String(e)}`)}}function tg(e,t){return{key:`${e}:${t}`,topic:e,type:t}}function Lme(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:fe(!1,`Unknown RTDS topic: ${String(e)}`)}}function nj(e={}){return new tj({environment:e.environment??ZO,apiKey:e.apiKey,onRateLimitUpdate:e.onRateLimitUpdate}).extend(WV)}async function qme(e){let t=nj({environment:e.environment,apiKey:e.apiKey,onRateLimitUpdate:e.onRateLimitUpdate}),n=await Hme(t,e),r=await t.beginAuthentication({wallet:n,credentials:e.credentials,nonce:e.nonce},e.signer).then(c8(e.signer));if(r.account.walletType===Se.EOA||await Of(r,{wallet:r.account.wallet,type:r.account.walletType}))return r;if(r.account.walletType===Se.DEPOSIT_WALLET)return await $me(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 Hme(e,t){if(t.wallet!==void 0)return t.wallet;let n=Be(await t.signer.getAddress()),r=L0(n,e.environment.walletDerivation);return await Of(e,{wallet:r,type:Se.DEPOSIT_WALLET})?r:Pf(n,e.environment.walletDerivation)}async function $me(e){let t=Pf(e.account.signer,e.environment.walletDerivation);if(!zt(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 mv(e)).wait()}var Lr,xpe,Spe,Ppe,ZO,Cpe,rg,YV,$pe,Vpe,QV,Ype,Jpe,eme,tme,dme,qV,HV,fme,xme,Ame,Tme,Sme,JV,ZV,ej,Dme,Ume,tj,Bme,Mme,Fme,oj=L(()=>{"use strict";uT();uT();e0();e0();pf();pf();UC();f0();s0();s0();iN();Lr=require("zod");Al();fw();Xw();dN();y0();xpe=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)});Spe=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 ce.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 xpe.parse(await t.json())}},Ppe=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})}};ZO={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};Cpe=zV({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"}});rg=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)}};YV=class{#e;#t;#r;#s=new mi({heartbeat:new TO});#n=new la;#o=new rg({deriveServerState:Dpe});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#o.add(e,{matches:qpe(e)});return await this.#i(n,t),ng(n.subscriber.queue,()=>this.#a(n))}async#i(e,t){let{before:n,after:r}=t;try{(await this.#l()).reusedOpenSocket&&OV(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}OV(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=BH.safeParse(n);r.success&&this.#o.dispatch(r.data)}}#d(){this.#o.hasActiveSubscriptions()&&this.#h()}#m(){}#y(){this.#s.send(Bpe(this.#o.serverState()))}#h(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}},$pe=class{#e;#t;#r;#s;#n=new mi({heartbeat:new TO});#o=new la;#i=new rg({deriveServerState:Upe});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:Hpe(e)});return await this.#a(n,t),ng(n.subscriber.queue,()=>this.#u(n))}async#a(e,t){let{before:n,after:r}=t;try{(await this.#c()).reusedOpenSocket&&LV(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}LV(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=MH.safeParse(n);r.success&&this.#i.dispatch(r.data)}}#m(){this.#i.hasActiveSubscriptions()&&this.#f()}#y(){}#h(e){this.#n.send(Fpe(this.#i.serverState(),e))}#f(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()})}},Vpe=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 I("Perps session manager has been shut down."));let o=new G5({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 I("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)}},QV=class{#e;#t;#r;#s=1;#n=new mi({heartbeat:new SO});#o=new la;#i=new rg({deriveServerState:jpe});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#i.add(e,{matches:zpe(e)});return await this.#a(n,t),ng(n.subscriber.queue,()=>this.#u(n))}async#a(e,t){try{(await this.#c()).reusedOpenSocket&&(this.#h(MV(t.before,t.after)),this.#f(FV(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(MV(t,n)),this.#f(FV(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=qH.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()})}};Ype=class{#e;#t=new la;#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(),Qpe(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 I("Realtime subscription closed.")),this.#i&&this.#f("unsubscribe",[n]),this.#r.size===0&&(this.#o=yn(()=>{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),I.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=yn(()=>{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=Xpe(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 Qr("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=>Kpe(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=yn(()=>{this.close()},1e3))}async close(){if(this.#a)return;this.#a=!0,this.#t.stop(),clearTimeout(this.#o);let e=new I("Realtime connection closed.");this.#v();for(let t of this.#r.values())t.reject(e);this.#r.clear(),await this.#e.close()}};Jpe=class{#e;#t=new mi({heartbeat:new M5,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 Qr("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}},Cl.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=Zpe(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"?Cl.Subscribed:Cl.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=yn(()=>{i.timer=yn(()=>{this.#r.delete(r),s(new I("Realtime acknowledgement timed out after 10 seconds."))},1e4),this.#o=Date.now();try{if(!this.#t.send({...e,rid:r}))throw new I("Realtime connection is not open.")}catch(a){clearTimeout(i.timer),this.#r.delete(r),s(I.fromError(a))}},Math.max(0,110-(Date.now()-this.#o)))})}#u(e){let t=jH.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===Cl.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=WH.safeParse(e);if(!n.success)return;let r=KH(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 I("Realtime connection closed.")),await this.#t.close()}};eme=class{#e;#t=new Set;#r=new Set;constructor(e){this.#e=e}async subscribe(e){let t=[...new Map(Gpe(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 Ype(new Jpe(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()))}},tme=class{#e;constructor(e){this.#e=new eme(e)}async subscribe(e){return this.#e.subscribe(e)}async close(){await this.#e.close()}};dme=class{#e=new Map;#t;constructor(e){this.#t=e}waitFor(e,t){let n=pme(),r,o=yn(()=>{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()}};qV="0x0000000000000000000000000000000000000000000000000000000000000000";HV=H.transform(e=>XV(e)).refine(e=>e<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),fme=Lr.z.strictObject({price:HV.refine(e=>e<1000000n,{message:"Price must be less than 1."}),size:HV.optional(),source:Lr.z.enum(["collateral","inventory"]).default("collateral")});xme=3e4,Ame=3e4,Tme=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 I("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 Sme({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 I("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)}},Sme=class{#e;#t;#r;#s;#n;#o;#i;#a;#u=new mi;#l=Bd({objectMode:!0});#c=new dme(Ame);#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=Pme();this.#d=e;let t=yn(()=>{e.reject(new I("RFQ quoter authentication timed out."))},xme);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 I("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 I("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(ame(this.#e,this.#r))}#x(e){if(this.#p!==void 0)return;let t=A4.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(nme(this,n));return;case"quote_ack":this.#c.resolve(dT(n.rfqId),ome(n));return;case"quote_cancel_ack":this.#c.resolve(VO(n.rfqId,n.quoteId),sme(n));return;case"confirmation_request":this.#l.push(rme(this,n));return;case"confirmation_ack":this.#c.resolve(jO(n.rfqId,n.quoteId),ime(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 I(`RFQ quoter authentication failed: ${e.error}`))}#v(e){this.#h(new Qr("RFQ quoter connection lost.",e))}#T(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new I("Uncorrelated RFQ quoter error."));return}this.#c.reject(dT(e.rfqId),new ic(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 I("Uncorrelated RFQ quoter error."));return}this.#c.reject(VO(e.rfqId,e.quoteId),new ac(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 I("Uncorrelated RFQ quoter error."));return}this.#c.reject(jO(e.rfqId,e.quoteId),new lc(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}))}}async quote(e,t){let n=gme(t),r=await yme({account:this.#e,chainId:this.#t,exchange:this.#s,request:e,response:n,signer:this.#i}),o=this.#c.waitFor(dT(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#m(lme(e,r)),await o}catch(s){throw this.#c.remove(dT(e.rfqId),o),s}}async cancelQuote(e){let t=VO(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(cme(this.#e,e.rfqId,e.quoteId)),await n}catch(r){throw this.#c.remove(t,n),r}}async respondToConfirmation(e,t,n){let r=jO(e,t),o=this.#c.waitFor(r,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#m(ume(e,t,n)),await o}catch(s){throw this.#c.remove(r,o),s}}};JV=class{#e;#t;#r;#s=new mi({heartbeat:new U5});#n=new la;#o=new rg({deriveServerState:_me});constructor(e){this.#e=e.headers,this.#t=e.url}async subscribe(e){let{change:t,entry:n}=this.#o.add(e,{matches:Lme(e)});return await this.#i(n,t),ng(n.subscriber.queue,()=>this.#a(n))}async#i(e,t){try{if((await this.#l()).reusedOpenSocket){let{before:n,after:r}=t,o=Eme(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=Rme(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=t3.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(Ime(e))}#f(e){e.length!==0&&this.#s.send(Cme(e))}#g(){this.#n.schedule({reconnect:()=>this.#l(),shouldReconnect:()=>this.#o.hasActiveSubscriptions()})}};ZV=class{#e;#t;#r;#s=new mi({heartbeat:new B5});#n=new la;#o=new rg;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),ng(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=n3.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()})}},ej=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)}},Dme=Lr.z.object({key:is,passphrase:Lr.z.string(),secret:Lr.z.string()}),Ume=Lr.z.object({wallet:J,credentials:Dme.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}),tj=class extends ej{constructor(e){super({apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,data:new kn({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new kn({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new kn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:t=>this.resolveClobHeaders(t)}),relayer:new kn({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:t=>this.resolveRelayerHeaders(t)}),rfq:new kn({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new kn({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new ON({url:e.environment.rpc}),webSockets:{clobMarket:new YV({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new ZV({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new JV({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new QV({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=M(e,Ume);return Promise.resolve(async function*(){let r=Math.floor(Date.now()/1e3),o=n?.nonce??0,s=Be(yield ZN()),i=Be(n.wallet),a=F6(this.environment,s,i);if(n.credentials!==void 0){let u=this.#e(n.credentials,a,t);try{if((await Sv(u)).includes(n.credentials.key))return u}catch(d){if(!(d instanceof O)||d.status!==401)throw d}}let l=yield{kind:"signAuthMessage",payload:Epe({address:s,chainId:this.environment.chainId,nonce:o,timestamp:r})},c=await Tv(this,{address:s,nonce:o,signature:ss(l),timestamp:r});return this.#e(c,a,t)}.call(this))}#e(e,t,n){let r=new Bme({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}},Bme=class extends ej{#e=!1;get context(){return fe(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=!0}constructor(e){let t=new tme({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 kn({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:n=>this.resolveClobHeaders(n)}),relayer:new kn({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:n=>this.resolveRelayerHeaders(n)}),rpc:new ON({url:e.environment.rpc}),gamma:new kn({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new kn({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new kn({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new kn({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new kn({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 kn({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:n=>this.resolveRelayerHeaders(n),root:e.environment.combos.collateralReturn.rest}),builderGateway:new kn({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 YV({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new $pe({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new Tme({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 ZV({headers:e.environment.sports.headers,url:e.environment.sports.ws}),realtime:t,rtds:new JV({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new QV({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new Vpe({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 Pv(this)}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,t,n]).then(()=>{})}let i=new tj({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 GV(this.credentials.secret,t,e.method,e.path,e.body),POLY_TIMESTAMP:`${t}`}}catch(t){throw ce.fromError(t,"Could not sign the L2-authenticated request")}}};Mme=B(vt,$,O,ce,tt,en,I,C,E),Fme=B(E)});var sj={};fr(sj,{AcceptComboQuoteError:()=>IA,ApproveErc1155ForAllError:()=>vv,ApproveErc20Error:()=>wv,ApprovePerpsBuilderFeeError:()=>kx,ArmPerpsAutoCancelError:()=>Ex,AuthorizeSessionKeyError:()=>VA,BiggestWinnerKind:()=>Yl,BuilderVolumeInterval:()=>Gl,CancelAllError:()=>zk,CancelMarketOrdersError:()=>Kk,CancelOrderError:()=>$k,CancelOrdersError:()=>jk,CollateralReturnKnownOperationKind:()=>Dd,ComboAcceptFailureReason:()=>Ro,ComboActivityType:()=>Wl,ComboPositionSortBy:()=>$l,ComboPositionStatus:()=>ii,ComboQuoteUnavailableReason:()=>ci,CreateApiKeyError:()=>S8,CreateBuilderApiKeyError:()=>I8,CreateLimitOrderError:()=>gx,CreateMarketOrderError:()=>mx,CreateOrDeriveApiKeyError:()=>E8,DeleteApiKeyError:()=>_8,DeployDepositWalletError:()=>p8,DepositToPerpsError:()=>Kx,DeriveApiKeyError:()=>P8,DownloadAccountingSnapshotError:()=>lA,DropNotificationsError:()=>W0,EstimateMarketPriceError:()=>Xk,ExecuteCollateralReturnPlanError:()=>tk,FetchApiKeysError:()=>R8,FetchBalanceAllowanceError:()=>j6,FetchBuilderApiKeysError:()=>N8,FetchBuilderFeeRatesError:()=>V8,FetchBuilderVolumeError:()=>kk,FetchClosedOnlyModeError:()=>U0,FetchCommentsByIdError:()=>sk,FetchEventError:()=>dk,FetchEventLiveVolumeError:()=>yk,FetchEventTagsError:()=>mk,FetchExecuteParamsError:()=>u8,FetchLastTradePriceError:()=>jv,FetchLastTradePricesError:()=>zv,FetchMarketError:()=>Nk,FetchMarketInfoError:()=>$8,FetchMarketTagsError:()=>Lk,FetchMidpointError:()=>_v,FetchMidpointsError:()=>Cv,FetchNegRiskError:()=>F8,FetchNotificationsError:()=>V0,FetchOpenInterestError:()=>qk,FetchOrderBookError:()=>Bv,FetchOrderBooksError:()=>Mv,FetchOrderError:()=>q0,FetchOrderScoringError:()=>K0,FetchOrdersScoringError:()=>Q0,FetchPerpsBookError:()=>Ux,FetchPerpsBuilderApprovalsError:()=>Tx,FetchPerpsBuilderEarningsSummaryError:()=>Px,FetchPerpsBuilderStatusError:()=>wx,FetchPerpsFeesError:()=>jx,FetchPerpsInstrumentsError:()=>Cx,FetchPerpsTickerError:()=>Ox,FetchPerpsTickersError:()=>Dx,FetchPortfolioValueError:()=>oA,FetchPriceError:()=>Ov,FetchPricesError:()=>Dv,FetchPublicProfileError:()=>kA,FetchRelatedTagResourcesError:()=>oT,FetchRelatedTagsError:()=>nT,FetchResolutionsError:()=>fk,FetchRewardPercentagesError:()=>ov,FetchRfqStatusError:()=>LA,FetchSeriesError:()=>qA,FetchSessionKeysError:()=>$A,FetchSportsMarketTypesError:()=>YA,FetchSpreadError:()=>qv,FetchSpreadsError:()=>$v,FetchTagError:()=>eT,FetchTickSizeError:()=>B8,FetchTotalEarningsForUserForDayError:()=>ev,FetchTraderLeaderboardStandingError:()=>Sk,FetchTradingApprovalsStateError:()=>kv,FetchUserPnlError:()=>iA,FetchUserStatsError:()=>sA,FetchUserVolumeError:()=>aA,GaslessTransactionHandle:()=>Lf,GaslessTransactionMetadataSchema:()=>ur,IsWalletDeployedError:()=>d8,LeaderboardWindow:()=>zl,ListAccountTradesError:()=>$0,ListActivityError:()=>lv,ListBiggestWinnersError:()=>Pk,ListBuilderLeaderboardError:()=>wk,ListBuilderTradesError:()=>Ev,ListComboActivityError:()=>cv,ListComboMarketsError:()=>Ik,ListComboPositionsError:()=>rA,ListCommentsByUserAddressError:()=>ak,ListCommentsError:()=>rk,ListCurrentRewardsError:()=>Kv,ListEventsError:()=>ck,ListMarketClarificationsError:()=>Y8,ListMarketHoldersError:()=>Uk,ListMarketRewardsError:()=>Qv,ListMarketsError:()=>_k,ListOpenOrdersError:()=>M0,ListPerpsBuilderEarningsError:()=>Sx,ListPerpsCandlesError:()=>Mx,ListPerpsFundingHistoryError:()=>qx,ListPerpsTradesError:()=>$x,ListPositionsError:()=>nA,ListPriceHistoryError:()=>Mk,ListSeriesError:()=>MA,ListSportsError:()=>GA,ListTagsError:()=>JA,ListTeamsError:()=>iT,ListTraderLeaderboardError:()=>Ak,ListTradesError:()=>iv,ListUserEarningsAndMarketsConfigError:()=>nv,ListUserEarningsForDayError:()=>J0,MergeComboPositionError:()=>gV,MergeMarketPositionError:()=>hV,MergePositionsError:()=>jd,OpenPerpsSessionError:()=>zx,OpenRfqSessionError:()=>PA,PlaceLimitOrderError:()=>yx,PlaceMarketOrderError:()=>hx,PlanCollateralReturnError:()=>Zv,PositionFilterType:()=>Hl,PositionSortBy:()=>ql,PositionStatus:()=>ai,PostOrderError:()=>ex,PostOrdersError:()=>tx,PrepareCollateralReturnExecutionError:()=>W8,PrepareErc1155ApprovalForAllError:()=>v8,PrepareErc20ApprovalError:()=>w8,PrepareErc20TransferError:()=>CV,PrepareGaslessTransactionError:()=>m8,PrepareLimitOrderError:()=>kO,PrepareLimitOrderPostingError:()=>_5,PrepareMarketOrderError:()=>vO,PrepareMarketOrderPostingError:()=>E5,PrepareMergeComboPositionError:()=>mV,PrepareMergeMarketPositionError:()=>dV,PrepareMergePositionsError:()=>mA,PreparePerpsDepositError:()=>J5,PrepareRedeemComboPositionError:()=>xV,PrepareRedeemMarketPositionsError:()=>vV,PrepareRedeemPositionsError:()=>yA,PrepareSplitComboPositionError:()=>sV,PrepareSplitMarketPositionError:()=>rV,PrepareSplitPositionError:()=>cA,PrepareTradingApprovalsError:()=>k8,PriceHistoryInterval:()=>Po,RedeemPositionsError:()=>wA,RequestComboQuoteError:()=>RA,ResolutionMarketType:()=>Xl,ResolutionReporter:()=>Zl,ResolutionSource:()=>Jl,ResolutionStatus:()=>Ql,ResolveConditionByTokenError:()=>H8,RevokeBuilderApiKeyError:()=>L8,RevokePerpsBuilderFeeError:()=>Ix,RevokePerpsCredentialsError:()=>Gx,RevokeSessionKeyError:()=>WA,RfqCancelQuoteError:()=>TA,RfqCancelQuoteRejectedError:()=>ac,RfqConfirmationDecision:()=>ds,RfqConfirmationError:()=>SA,RfqConfirmationRejectedError:()=>lc,RfqDirection:()=>Nn,RfqExecutionStatus:()=>ps,RfqKnownErrorCode:()=>Cr,RfqQuoteError:()=>AA,RfqQuoteRejectedError:()=>ic,RfqRejectionCode:()=>li,RfqRequestRejectedError:()=>fs,RfqRequestedSizeUnit:()=>Xr,RfqSide:()=>Eo,RfqStatus:()=>mn,SearchError:()=>UA,SearchSort:()=>Wd,SessionKeyKnownScope:()=>yo,SetupTradingApprovalsError:()=>xv,SortDirection:()=>Bl,SplitComboPositionError:()=>lV,SplitMarketPositionError:()=>iV,SplitPositionError:()=>Vd,SubscribeError:()=>XA,TipSide:()=>Ul,TradeFilterType:()=>Ml,TraderLeaderboardSort:()=>Kl,TransferErc20Error:()=>lT,TransferPerpsCollateralError:()=>Qx,UpdateBalanceAllowanceError:()=>W6,UpdatePerpsLeverageError:()=>Rx,UpdatePerpsMarginError:()=>_x,UserPnlFidelity:()=>jl,UserPnlInterval:()=>Vl,WaitForComboFillError:()=>NA,WaitForGaslessTransactionError:()=>b8,WaitForOrderFillSettlementError:()=>dx,WithdrawFromPerpsError:()=>Yx,acceptComboQuote:()=>CA,approveErc1155ForAll:()=>Uf,approveErc20:()=>Df,authorizeSessionKey:()=>jA,buildDepositWalletExecuteRequest:()=>qd,buildProxyWalletExecuteRequest:()=>hv,buildSafeWalletExecuteRequest:()=>yv,cancelAll:()=>Gk,cancelMarketOrders:()=>Yk,cancelOrder:()=>Vk,cancelOrders:()=>Wk,createApiKey:()=>oO,createBuilderApiKey:()=>C8,createLimitOrder:()=>$f,createMarketOrder:()=>Hf,createOrDeriveApiKey:()=>Tv,deleteApiKey:()=>Pv,deployDepositWallet:()=>mv,depositToPerps:()=>Zx,deriveApiKey:()=>sO,downloadAccountingSnapshot:()=>Xf,dropNotifications:()=>z0,estimateMarketPrice:()=>Jk,executeCollateralReturnPlan:()=>nk,extractOnChainNonceFromSubmitError:()=>fv,fetchApiKeys:()=>Sv,fetchBalanceAllowance:()=>G0,fetchBuilderApiKeys:()=>O8,fetchBuilderFeeRates:()=>lO,fetchBuilderVolume:()=>xk,fetchClosedOnlyMode:()=>B0,fetchCommentsById:()=>ik,fetchEvent:()=>pk,fetchEventLiveVolume:()=>bk,fetchEventTags:()=>hk,fetchExecuteParams:()=>Nf,fetchLastTradePrice:()=>Wv,fetchLastTradePrices:()=>Gv,fetchMarket:()=>Ok,fetchMarketInfo:()=>aO,fetchMarketTags:()=>Dk,fetchMidpoint:()=>Iv,fetchMidpoints:()=>Nv,fetchNegRisk:()=>q8,fetchNotifications:()=>j0,fetchOpenInterest:()=>Hk,fetchOrder:()=>H0,fetchOrderBook:()=>Hd,fetchOrderBooks:()=>Fv,fetchOrderScoring:()=>Y0,fetchOrdersScoring:()=>X0,fetchPerpsBook:()=>Bx,fetchPerpsBuilderStatus:()=>vx,fetchPerpsFees:()=>Wx,fetchPerpsInstruments:()=>Nx,fetchPerpsTicker:()=>Lx,fetchPerpsTickers:()=>jf,fetchPortfolioValue:()=>Gf,fetchPrice:()=>Lv,fetchPrices:()=>Uv,fetchPublicProfile:()=>xA,fetchRelatedTagResources:()=>sT,fetchRelatedTags:()=>rT,fetchResolutions:()=>gk,fetchRewardPercentages:()=>sv,fetchRfqStatus:()=>DA,fetchSeries:()=>HA,fetchSessionKeys:()=>zd,fetchSportsMarketTypes:()=>QA,fetchSpread:()=>Hv,fetchSpreads:()=>Vv,fetchTag:()=>tT,fetchTickSize:()=>M8,fetchTotalEarningsForUserForDay:()=>tv,fetchTraderLeaderboardStanding:()=>Mf,fetchTradingApprovalsState:()=>Bf,fetchTransaction:()=>eO,fetchUserPnl:()=>Yf,fetchUserStats:()=>Kf,fetchUserVolume:()=>Qf,isRetryableGaslessSubmitError:()=>bv,isWalletDeployed:()=>Of,listAccountTrades:()=>Ef,listActivity:()=>Rf,listBiggestWinners:()=>Ek,listBuilderLeaderboard:()=>vk,listBuilderTrades:()=>Rv,listComboActivity:()=>_f,listComboMarkets:()=>Ck,listComboPositions:()=>zf,listComments:()=>ok,listCommentsByUserAddress:()=>lk,listCurrentRewards:()=>Yv,listEvents:()=>uk,listMarketClarifications:()=>Rk,listMarketHolders:()=>Bk,listMarketRewards:()=>Xv,listMarkets:()=>Ff,listOpenOrders:()=>F0,listPerpsCandles:()=>Fx,listPerpsFundingHistory:()=>Hx,listPerpsTrades:()=>Vx,listPositions:()=>Wf,listPriceHistory:()=>Fk,listSeries:()=>FA,listSports:()=>KA,listTags:()=>ZA,listTeams:()=>aT,listTraderLeaderboard:()=>Tk,listTrades:()=>av,listUserEarningsAndMarketsConfig:()=>rv,listUserEarningsForDay:()=>Z0,mergeComboPosition:()=>yV,mergeMarketPosition:()=>fV,mergePositions:()=>gA,openPerpsSession:()=>Xx,openRfqSession:()=>EA,placeLimitOrder:()=>bx,placeMarketOrder:()=>fx,planCollateralReturn:()=>ek,postOrder:()=>$d,postOrders:()=>nx,prepareCollateralReturnExecution:()=>cO,prepareErc1155ApprovalForAll:()=>nO,prepareErc20Approval:()=>tO,prepareErc20Transfer:()=>$O,prepareGaslessTransaction:()=>Or,prepareLimitOrder:()=>ux,prepareLimitOrderPosting:()=>I5,prepareMarketOrder:()=>cx,prepareMarketOrderPosting:()=>R5,prepareMergeComboPosition:()=>fA,prepareMergeMarketPosition:()=>hA,prepareMergePositions:()=>DO,preparePerpsDeposit:()=>OO,prepareRedeemComboPosition:()=>AV,prepareRedeemMarketPositions:()=>UO,prepareRedeemPosition:()=>bA,prepareRedeemPositions:()=>BO,prepareSplitComboPosition:()=>dA,prepareSplitMarketPosition:()=>uA,prepareSplitPosition:()=>LO,prepareTradingApprovals:()=>rO,redeemPositions:()=>vA,requestComboQuote:()=>_A,resignDepositWalletExecuteRequest:()=>gv,resolveConditionByToken:()=>iO,resolveEstimatedMarketPrice:()=>hO,resolveMarketPriceFromOrderBook:()=>Zk,revokeBuilderApiKey:()=>D8,revokePerpsCredentials:()=>Jx,revokeSessionKey:()=>zA,search:()=>BA,setupTradingApprovals:()=>Av,signOrder:()=>lx,splitComboPosition:()=>cV,splitMarketPosition:()=>aV,splitPosition:()=>pA,subscribe:()=>Zf,transferErc20:()=>cT,transferPerpsCollateral:()=>tA,updateBalanceAllowance:()=>UN,waitForComboFill:()=>OA,waitForOrderFillSettlement:()=>px,withdrawFromPerps:()=>eA});var ij=L(()=>{"use strict";uT()});var gye={};fr(gye,{AI_AGENT_TOOL_NAMES:()=>rS,AbortError:()=>Ni,AgentCore:()=>dS,ApproveTokenTool:()=>Kp,BRIDGE_NON_EVM_CHAIN_FAMILY:()=>Ya,BRIDGE_STATUS_POLL_MS:()=>EY,BRIDGE_SUPPORT_URL:()=>RY,BUILDER_CODE:()=>IP,BaseNftAiTool:()=>ws,BaseSwapProvider:()=>Aa,BaseTool:()=>K,BaseWalletActionTool:()=>to,BuyTokenTool:()=>Yp,CachedResource:()=>xs,ChatHistory:()=>Jp,CoinpoolConfigApi:()=>ig,DEFAULT_CHAIN:()=>er,DEFAULT_PROVIDER:()=>gi,DEFAULT_RPC_BY_CHAIN:()=>Fr,DEFILLAMA_EXTRA_SIGNALS:()=>Lo,DEFILLAMA_POOL_CHAIN_HEXES:()=>Mp,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION:()=>hr,DELAYED_ORDER:()=>Ny,DEPOSIT_REFERENCE_USD:()=>oL,DEPOSIT_STABLE_SYMBOLS:()=>Hm,DebridgeProvider:()=>Sp,DefiLlamaEstimatePoolYieldTool:()=>jp,DefiLlamaPoolByAddressTool:()=>Vp,DefiLlamaPoolCandidateResolver:()=>Wp,DefiLlamaPoolDetailTool:()=>$p,DefiLlamaPoolSearchTool:()=>Hp,DefiLlamaPoolService:()=>Jn,DefiLlamaTopPoolsTool:()=>qp,ERC1967_INIT_CODE:()=>Ds,EstimatePoolYieldTool:()=>Ip,GAMES_TAG_ID:()=>BP,GeminiProvider:()=>jt,GeminiSearchAiTool:()=>hp,HEX_TO_PANTOGRAPH:()=>nD,HIDE_FROM_NEW_TAG_ID:()=>MP,KeyringSettingApi:()=>cg,KnowledgeBase:()=>em,LendingMarketDetailTool:()=>Iu,LendingMarketsTool:()=>_u,LendingReadService:()=>Eu,LendingService:()=>io,LendingSupplyService:()=>Ru,MARKET_ORDER:()=>Vm,MARKET_STREAM:()=>jm,MULTICALL3_ADDRESS:()=>xt,ManageLiquidityRedirectTool:()=>bc,MoralisService:()=>De,NATIVE_GAS_LIMIT:()=>CW,NATIVE_TOKEN_PLACEHOLDER:()=>NP,NFC_AGENT_TOOL_NAMES:()=>nS,NFC_AMAZON_DEFAULT_DOMAIN:()=>bL,NFC_AMAZON_DOMAINS:()=>yL,NFTContractInfoTool:()=>cp,NFTMetadataTool:()=>up,NFT_AGENT_TOOL_NAMES:()=>tS,NfcBuyTool:()=>mp,NfcInfoTool:()=>pp,NoFormTool:()=>yg,ONBOARDING_STEP:()=>on,ONBOARDING_TRACKING:()=>Cy,ORDER_INPUT_ERROR:()=>Us,OpenAddLiquidityFormTool:()=>fc,OpenSupplyFormTool:()=>Nu,PERPS_DEPOSIT_CONTRACT:()=>LP,POLYGON_CHAIN_ID:()=>qm,POLYGON_HEX_CHAIN_ID:()=>Hi,POLYMARKET_API:()=>Fi,POLYMARKET_LIVE_DATA_WS:()=>OP,POLYMARKET_WEB_URL:()=>qi,POOL_UNISWAP_AGENT_TOOL_NAMES:()=>sS,POSITION_DUST_SHARES:()=>qP,PREDICTION_ACTIVITY_TYPES:()=>FP,PREDICTION_AGENT_TOOL_NAMES:()=>ZT,PREDICTION_CATEGORIES:()=>$i,PREDICTION_SORTS:()=>$m,PUSD_ADDRESS:()=>Ls,PUSD_DECIMALS:()=>zo,PantographService:()=>Ft,PolymarketApiError:()=>Ys,PolymarketOnboardingError:()=>hi,PolymarketRedeemError:()=>ma,PolymarketService:()=>Ye,PolymarketTradeError:()=>pa,PolymarketWithdrawError:()=>Io,PoolByAddressTool:()=>_p,PoolDetailTool:()=>Ep,PoolFallbackAiTool:()=>fp,PoolPriceRangesTool:()=>yc,PoolSearchTool:()=>Rp,PoolService:()=>Et,PoolSwapRouter:()=>kp,PredictionActivityTool:()=>np,PredictionDepositTool:()=>op,PredictionMarketDetailTool:()=>ep,PredictionMarketsTool:()=>Jd,PredictionPortfolioTool:()=>tp,PredictionSetupTool:()=>rp,PredictionTradeTool:()=>sp,PredictionWithdrawTool:()=>ip,PreviewAddLiquidityTool:()=>gc,PublicClient:()=>qa,REDEEM:()=>Qa,RELAYER_DEPLOY_POLL:()=>Iy,RELAYER_SUBMIT_PATH:()=>_y,RelayProvider:()=>wp,Router:()=>tm,SUPPLIABLE_TYPES:()=>xP,SUPPORTED_CHAINS:()=>eu,SUPPORTED_CHAINS_LABEL:()=>nu,SWAP_PROVIDER_CONFIG:()=>Tp,SendNativeTool:()=>zp,SendNftTool:()=>Xp,SendTokenTool:()=>Gp,Subagent:()=>ut,SubgraphAddPoolTool:()=>Bp,SubgraphCoinPoolPairsTool:()=>Up,SubgraphPoolByAddressTool:()=>Op,SubgraphPoolByPositionIdTool:()=>Lp,SubgraphPoolSearchTool:()=>Cp,SubgraphPositionDetailTool:()=>Dp,SubgraphTrendingPoolsTool:()=>Np,Summarizer:()=>Zp,SwapProviderFactory:()=>lg,SwapRouter:()=>vp,SwapRouterRegistry:()=>ag,SwapTokenTool:()=>Qp,Synthesizer:()=>nm,TOKEN_AGENT_TOOL_NAMES:()=>eS,TRADE_ERROR:()=>bt,TRADING_APPROVALS_METADATA:()=>DP,TRANSFER_TOPIC:()=>gW,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>rD,TokenAnalyticsTool:()=>du,TokenHoldersTool:()=>uu,TokenInfoTool:()=>cu,TokenScoreTool:()=>pu,ToolRegistry:()=>Zc,TopGainersTool:()=>hu,TopPoolsTool:()=>Pp,TransactionByHashTool:()=>Pu,TrendingTokensTool:()=>mu,UNISWAP_CHAIN_SLUG:()=>dg,UNRESOLVED_ASSET:()=>Ga,UP_OR_DOWN_TAG_ID:()=>UP,UpstashKnowledgeBase:()=>Ra,UserSwapRouter:()=>xp,WALLET_ACTION_AGENT_TOOL_NAMES:()=>iS,WALLET_AGENT_TOOL_NAMES:()=>JT,WALLET_DERIVATION:()=>Wr,WITHDRAW:()=>gn,WalletApprovalsTool:()=>Au,WalletDefiPositionsTool:()=>Tu,WalletDefiProtocolPositionsTool:()=>Su,WalletHistoryTool:()=>bu,WalletLendingPositionsTool:()=>Cu,WalletNFTsTool:()=>lp,WalletNftTransfersTool:()=>vu,WalletPnlSummaryTool:()=>ku,WalletPnlTool:()=>xu,WalletTokenBalancesTool:()=>yu,WalletTokenTransfersTool:()=>wu,WebsiteTrustKeyringAgent:()=>mS,ZERO_ADDRESS:()=>Pt,adjustBuyAmountForFees:()=>QP,allInBuyNotional:()=>iU,amazonDomainForLanguage:()=>wL,apiClient:()=>se,applyMarketEvent:()=>sL,applyYieldConversions:()=>fy,bestPrice:()=>cU,buildApprovalCalls:()=>nL,buildApprovals:()=>$T,buildBuilderSignature:()=>M_,buildChallenge:()=>tP,buildRangePresets:()=>SL,buildUniswapPoolUrl:()=>Ur,builderApiKey:()=>F_,buyNotional:()=>sU,buyNotionalAfterFee:()=>aU,call:()=>Fo,canDeriveV3PoolAddress:()=>IL,ceil2:()=>oU,chains:()=>Da,checkNativeGasAffordable:()=>hg,checksumAddress:()=>Sc,clampTick:()=>ks,classifyTradeError:()=>aL,classifyWithdrawError:()=>cL,clearPublicClientCache:()=>Xg,coinpoolConfigApi:()=>Sa,compareDecimal:()=>Ci,completeX402:()=>nP,configureSupportedChains:()=>ny,configureSwapProvider:()=>qT,convertSusdsShares:()=>za,createAiAgent:()=>Tg,createDefaultSubagents:()=>aS,createNfcAgent:()=>Ag,createNftAgent:()=>xg,createPolymarketSigner:()=>da,createPoolUniswapAgent:()=>Sg,createPredictionAgent:()=>vg,createPublicClient:()=>Ii,createTokenAgent:()=>kg,createTransport:()=>_i,createWalletActionAgent:()=>Pg,createWalletAgent:()=>wg,createX402SignatureProvider:()=>oP,decodeAbiParameters:()=>Dn,decodeErrorResult:()=>Ic,decodeFunctionData:()=>CS,decodeFunctionResult:()=>Uo,defiLlamaPoolInfoScope:()=>pr,defiLlamaPoolSupportsLabel:()=>mr,deployDepositWallet:()=>kw,depositPriceImpact:()=>dj,deriveBeaconDepositWallet:()=>D_,deriveDepositWallet:()=>B_,deriveSafeWallet:()=>U_,deriveUupsDepositWallet:()=>L_,deriveV3PoolAddress:()=>CL,displayFromChallenge:()=>W1,effectivePriceUSD:()=>Lm,encodeAbiParameters:()=>Ec,encodeApprove:()=>HT,encodeErrorResult:()=>PS,encodeFunctionData:()=>Le,encodeSignedHeader:()=>rP,erc1155Abi:()=>Vg,erc20Abi:()=>Ve,erc20Abi_bytes32:()=>Fc,erc721Abi:()=>qc,estimateGas:()=>Bc,estimateNativeGasReserveWei:()=>pg,estimateTransactionFeeWei:()=>OL,ethCallAt:()=>yD,ethCallByChain:()=>SK,eventHeadline:()=>My,eventUrl:()=>GP,evmDepositAssets:()=>yT,exactAmountString:()=>Ha,extractOutRaw:()=>pW,extractQuoteError:()=>mW,fallback:()=>wm,feePerShare:()=>Vi,feeWeiToNative:()=>LL,fetchOnboardingSnapshot:()=>ys,fetchTopMarketplaces:()=>vL,fetchTradingApprovalsStatus:()=>fT,fetchUnderlyingPricesUSD:()=>Bm,findWalletDepositOptions:()=>gT,floor2:()=>Ja,floorToDecimals:()=>gr,formatDefiLlamaPool:()=>Ln,getAbiItem:()=>Si,getAddress:()=>kS,getBalance:()=>Oc,getBlock:()=>Mc,getBlockNumber:()=>Cc,getCashBalance:()=>cd,getCashBalanceBaseUnits:()=>Rh,getChain:()=>xn,getChainContractAddress:()=>pm,getChainId:()=>Nc,getChainMeta:()=>No,getCode:()=>Pi,getDefaultRpcUrl:()=>zS,getGasPrice:()=>Uc,getNativeTokenInfo:()=>mc,getPolymarketBuilderCode:()=>Ou,getPublicClient:()=>Rt,getRevertReason:()=>lm,getRpcOverrides:()=>gm,getStorageAt:()=>Lc,getTokenPriceUSD:()=>py,getTransactionCount:()=>Dc,http:()=>so,humanToWei:()=>Is,ingestKnowledgeBase:()=>JW,isAbortError:()=>Va,isAddress:()=>ge,isAddressEqual:()=>xS,isBelowWithdrawMinimum:()=>kT,isEvmAddress:()=>zr,isMarketOpen:()=>Gm,isPaymentRequired:()=>hG,isShareBasedProtocol:()=>au,isShareBasedYieldToken:()=>aD,isSupplyChain:()=>vy,keyringSettingApi:()=>Ta,listCandidateChains:()=>kP,listSupplyChains:()=>wy,mapEvent:()=>By,mapMarket:()=>zP,marketFee:()=>zm,marketProtocol:()=>Wm,moneylineMarket:()=>Xa,mulDivFloor:()=>$a,multicall:()=>Qc,multicall3Abi:()=>oo,multicallRaw:()=>Ri,nativeGasShortfall:()=>OW,nfcAmazonSearchUrl:()=>OT,normaliseCountry:()=>LT,normalizeDecimal:()=>Xc,normalizeLevels:()=>Za,normalizePriceRangeToPool:()=>bp,normalizeText:()=>lt,onboardingStep:()=>lj,openSecureClient:()=>Yd,parseAbi:()=>DS,parseAbiItem:()=>Hg,parseAbiParameters:()=>um,parsePolymarketUrl:()=>Km,parsePredictionHint:()=>Ym,pickLogo:()=>yi,placePredictionOrder:()=>fj,planYieldTokenConversions:()=>bP,predictionHint:()=>rU,prepareMarketOrder:()=>lU,priceToTick:()=>pc,protocolLabelFor:()=>yr,psm3For:()=>hy,pusdFromBaseUnits:()=>lL,pusdToBaseUnits:()=>xT,quoteBuyAsPolymarket:()=>YP,quoteBuyUsd:()=>Du,quoteDeposit:()=>sg,quoteMarketOrder:()=>JP,quoteSellShares:()=>XP,quoteWithdrawal:()=>bj,readContract:()=>qo,readPaymentError:()=>V1,readPaymentRequired:()=>Zg,readProtocolFeeWei:()=>VT,readReceipt:()=>j1,readSpendableBalance:()=>gg,readTokenUsdPrice:()=>fg,redeemPredictionPositions:()=>vj,registerMaybeNoForm:()=>XT,remoteBuilderSigning:()=>KF,requestWithX402:()=>mG,resolveAccountWallet:()=>bw,resolveCategory:()=>Fy,resolveGasLimit:()=>NW,resolveNfcShopLinks:()=>dp,resolveRawYieldAsset:()=>J1,resolveRawYieldIdentity:()=>ja,resolveRawYieldProtocol:()=>X1,resolveRpcUrl:()=>$o,resolveRpcUrls:()=>Fa,resolveTokenPriceUSD:()=>Dm,roundTickToSpacing:()=>vs,rpcCall:()=>gD,runPolymarketOnboarding:()=>cj,setPolymarketBuilderCode:()=>CP,setRpcOverrides:()=>Ma,slippagePrice:()=>qy,spendableNative:()=>mg,swapProviderFactory:()=>Ap,swapRouterRegistry:()=>FT,tickToPrice:()=>Co,ticketFee:()=>KP,toBuilderAuthorization:()=>ts,toEventSelector:()=>AS,toFunctionSelector:()=>Es,toPantographChain:()=>NG,toPlainDecimal:()=>vm,unitPriceUSD:()=>lu,upDownWindow:()=>Dy,valueYieldTokens:()=>gy,walletDepositAssets:()=>rL,watchCryptoPrice:()=>eU,watchOrderBooks:()=>mj,weiToHuman:()=>Jc,withdrawDestinations:()=>vT,withdrawFromPolymarket:()=>wj});module.exports=sz(gye);var zL=jL(require("axios"));var WL="0.4.4";var az=`keyring-agent-core/${WL} (Keyring Chatbot Agent; +https://keyring.app)`,hS=null;function GL(e){hS=e}var lz=["payment-signature","x-payment"];function cz(e){return e?Object.keys(e).some(t=>lz.includes(t.toLowerCase())):!1}var gS;function om(e){gS=e}function KL(){return gS}var uz=3e4,dz=typeof process<"u"&&process.versions?.node!=null,fS=class{instance;constructor(t={}){this.instance=zL.default.create({baseURL:t.baseURL,timeout:t.timeout??uz,validateStatus:()=>!0,headers:{Accept:"application/json",...dz?{"Accept-Encoding":"gzip, deflate, br","User-Agent":t.userAgent??az}:{},...t.headers}})}async request(t,n,r,o={}){let s=o.signal??gS,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&&hS&&!cz(o.headers)){let c=await hS(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 fS;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 pz(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??pz(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 YL(this,t)}};function YL(e,t){if(t?.(e))return e;let n=e&&typeof e=="object"?e.cause:void 0;return n!=null?YL(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."]})}},_g=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: ${QL(n)}`,`Reason: ${r}`]})}},Cg=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 "${QL(t)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function QL(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 Ng=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."]})}},Og=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."]})}},Lg=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 mz=/^0x[0-9a-fA-F]*$/;function Ia(e,{strict:t=!0}={}){return typeof e!="string"?!1:t?mz.test(e):e.startsWith("0x")}function Do(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}function sm(e){return typeof e=="string"?Math.ceil(Do(e).length/2):e.length}function Ca(e,t,n){let r=Do(e),o=(t??0)*2,s=n===void 0?r.length:n*2;return`0x${r.slice(o,s)}`}function Dg(e){return`0x${e.map(Do).join("")}`}function Na(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=Do(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 yS(e){return new TextEncoder().encode(e)}function bS(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 wS(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 vS(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 Oa(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 Do(e)?Tc(xi(e),{signed:t}):0n}function Ug(e,t={}){return Number(ro(e,t))}var XL=require("js-sha3");var hz=/^0x[0-9a-fA-F]{40}$/;function ge(e){return typeof e=="string"&&hz.test(e)}function Sc(e){let t=Do(e).toLowerCase(),n=(0,XL.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 kS(e){if(!ge(e))throw new Error(`Address "${e}" is invalid.`);return Sc(e)}function xS(e,t){return ge(e)&&ge(t)&&e.toLowerCase()===t.toLowerCase()}var Bg=require("js-sha3");function Mg(e){return`0x${(0,Bg.keccak_256)(e)}`}function JL(e){return`0x${(0,Bg.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 im(e){let t=Ti(e.type);return t==="tuple"||t.startsWith("tuple[")?`(${(e.components??[]).map(im).join(",")})${t.slice(5)}`:t}function Pc(e){return`${e.name??""}(${(e.inputs??[]).map(im).join(",")})`}function Es(e){let t=typeof e=="string"?e:Pc(e);return`0x${(0,Bg.keccak_256)(new TextEncoder().encode(t)).slice(0,8)}`}function AS(e){let t=typeof e=="string"?e:Pc(e);return JL(t)}function ZL(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=>ZL(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)=>ZL(n[u],c))})??i[0]}function La(e){let t=Si(e);if(!t)throw new Lg({name:e.name,type:e.type??"function"});return t}function e1(e){let t=new Uint8Array(Math.ceil(e.length/32)*32);return t.set(e),{dynamic:!0,encoded:Na([Oa(BigInt(e.length)),t])}}function t1(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 n1(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 r1(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 Cg({type:r,value:e,min:s,max:o})}function o1(e,t){if(e instanceof Uint8Array)return e;if(typeof e=="string"){if(!Ia(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 TS(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 fz({...e,type:s},t,o,e.type)}if(e.type==="tuple")return gz(e,t);let r=Ti(e.type);if(r==="address"){if(!ge(t))throw new xc(t);return{dynamic:!1,encoded:wS(xi(Do(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=n1(t,r);return r1(o,{bits:t1(r,"uint"),signed:!1,type:r}),{dynamic:!1,encoded:Oa(o)}}if(/^int\d*$/.test(r)){let o=n1(t,r);return r1(o,{bits:t1(r,"int"),signed:!0,type:r}),o<0n&&(o+=1n<<256n),{dynamic:!1,encoded:Oa(o)}}if(/^bytes\d+$/.test(r)){let o=Number(r.slice(5));if(o<1||o>32)throw new wi(e.type);let s=o1(t,r);if(s.length!==o)throw new Ng({expectedSize:o,value:String(t)});return{dynamic:!1,encoded:vS(s)}}if(r==="bytes")return e1(o1(t,r));if(r==="string"){if(typeof t!="string"&&!(t instanceof Uint8Array))throw new no({type:r,value:t,reason:"expected a string"});return e1(typeof t=="string"?yS(t):t)}throw new wi(e.type)}function SS(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(Oa(BigInt(t+o))),r.push(i),o+=i.length):n.push(i);return Na([...n,...r])}function fz(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=TS(e,a);l.dynamic&&(s=!0),i.push(l)}if(o||s){let a=SS(i);if(!o)return{dynamic:!0,encoded:a};let l=Oa(BigInt(i.length));return{dynamic:!0,encoded:i.length>0?Na([l,a]):l}}return{dynamic:!1,encoded:Na(i.map(a=>a.encoded))}}function gz(e,t){let n=e.components??[],r=!1,o=[];for(let s=0;s<n.length;s++){let i=n[s],a=TS(i,Array.isArray(t)?t[s]:t[i.name??""]);a.dynamic&&(r=!0),o.push(a)}return{dynamic:r,encoded:r?SS(o):Na(o.map(s=>s.encoded))}}function Ec(e,t){if(e.length!==t.length)throw new _g({expectedLength:e.length,givenLength:t.length});return e.length===0?"0x":Ps(SS(e.map((n,r)=>TS(n,t[r]))))}function Le({abi:e,functionName:t,args:n=[]}){let r=La({abi:e,name:t,args:n,type:"function"}),o=Es(r),s=r.inputs??[];return s.length===0?o:Dg([o,Ec(s,n)])}function PS({abi:e,errorName:t,args:n=[]}){let r=La({abi:e,name:t,args:n,type:"error"}),o=r.inputs??[],s=Es(r);return o.length===0?s:Dg([s,Ec(o,n)])}function yz(e){let t=e.replace(/^u?int/,"");return t?Number(t):256}function am(e,t){if(t<0||t+32>e.length)throw new Ac({position:t,length:e.length});return e.subarray(t,t+32)}function _S(e,t){let n=Tc(am(e,t));if(n>BigInt(e.length))throw new Ac({position:Number(n),length:e.length});return Number(n)}function ES(e){let t=Ai(e.type);if(t){let[r,o]=t;return r===null||ES({...e,type:o})}if(e.type==="tuple")return(e.components??[]).some(ES);let n=Ti(e.type);return n==="bytes"||n==="string"}function RS(e){let t=Ai(e.type);if(t){let[n,r]=t;return n===null?32:n*RS({...e,type:r})}return e.type==="tuple"?(e.components??[]).reduce((n,r)=>n+RS(r),0):32}function IS(e,t,n){let r=[],o=t;for(let s of n)ES(s)?(r.push(s1(e,t+_S(e,o),s)),o+=32):(r.push(s1(e,o,s)),o+=RS(s));return r}function bz(e,t,n,r){let o=r===null?_S(e,t):r,s=r===null?t+32:t;return IS(e,s,new Array(o).fill(n))}function wz(e,t,n){let r=n.components??[],o=IS(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 s1(e,t,n){let r=Ai(n.type);if(r){let[s,i]=r;return bz(e,t,{...n,type:i},s)}if(n.type==="tuple")return wz(e,t,n);let o=Ti(n.type);if(o==="address")return Sc(Ps(am(e,t).subarray(12)));if(o==="bool")return Tc(am(e,t))!==0n;if(/^u?int\d*$/.test(o)){let s=o.startsWith("int"),i=Tc(am(e,t),{signed:s});return yz(o)>48?i:Number(i)}if(/^bytes\d+$/.test(o)){let s=Number(o.slice(5));return Ps(am(e,t).subarray(0,s))}if(o==="bytes"||o==="string"){let s=_S(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):bS(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 Og({data:typeof t=="string"?t:Ps(t),params:e,size:n.length});return IS(n,0,e)}function ft(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=i1(t);if(n)return n}catch{}try{let[t]=Dn([{type:"bytes32"}],e);return qg(t)}catch{return null}}function _c(e){return Fg(ft(e))}function Fg(e){let t=typeof e=="bigint"?Number(e):typeof e=="number"?e:NaN;return Number.isFinite(t)&&t>=0&&t<=36?t:null}function qg(e){return typeof e!="string"||!e.startsWith("0x")?null:i1(Buffer.from(e.slice(2),"hex").toString("utf8"))||null}function i1(e){return e.replace(/[^\x20-\x7e]/g,"").trim()}function Uo({abi:e,functionName:t,args:n,data:r}){let s=La({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 CS({abi:e,data:t}){let n=Ca(t,0,4),r=La({abi:e,name:n,type:"function"}),o=r.inputs??[];return{functionName:r.name,args:o.length===0||sm(t)<=4?[]:Dn(o,Ca(t,4))}}var a1={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},l1={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},c1={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 Ic({abi:e=[],data:t}){let n=Ca(t,0,4);if(sm(t)<4)throw new Error(`Cannot decode error result: "${t}" is too short.`);let r=[...e,a1,l1],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,Ca(t,4)):void 0}}function lm({abi:e,data:t}){if(!(!t||t==="0x"))try{let{errorName:n,args:r}=Ic({abi:e,data:t});if(n==="Error")return String(r?.[0]??"");if(n==="Panic"){let o=Number(r?.[0]??0);return c1[o]??`Panic code ${o}.`}return!r||r.length===0?n:`${n}(${r.map(o=>String(o)).join(", ")})`}catch{return}}var vz=new Set(["pure","view","nonpayable","payable"]),kz=new Set(["external","public","internal","private","calldata","memory","storage"]);function OS(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 d1(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 xz(e){let t=e.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:t?.[1]??"",rest:(t?.[2]??"").trim()}}function u1(e,t){let n=!1,r;for(let o of e)o==="indexed"?n=!0:kz.has(o)||(r=o);return{...t,...r?{name:r}:{},...n?{indexed:!0}:{}}}function LS(e){let t=e.trim();if(t.startsWith("(")){let o=OS(t,0),s=d1(t.slice(1,o)).map(LS),{suffix:i,rest:a}=xz(t.slice(o+1).trim());return u1(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 u1(r,{type:n})}function um(e){return d1(e).map(LS)}function cm(e,t,n){let r=e.indexOf("(",t);if(r===-1)throw new ki(n,"Missing parameter list.");let o=OS(e,r);return{name:e.slice(t,r).trim(),params:um(e.slice(r+1,o)),rest:e.slice(o+1).trim()}}function NS(e,t){return e.split(/[\s()]+/).find(r=>vz.has(r))??t}function Hg(e){let t=e.trim();if(t.startsWith("function ")){let{name:n,params:r,rest:o}=cm(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=um(o.slice(l+1,OS(o,l)))}return{type:"function",name:n,inputs:r,outputs:a,stateMutability:NS(i,"nonpayable")}}if(t.startsWith("event ")){let{name:n,params:r}=cm(t,6,e);return{type:"event",name:n,inputs:r}}if(t.startsWith("error ")){let{name:n,params:r}=cm(t,6,e);return{type:"error",name:n,inputs:r}}if(t.startsWith("constructor")){let{params:n,rest:r}=cm(t,11,e);return{type:"constructor",inputs:n,stateMutability:NS(r,"nonpayable")}}if(t.startsWith("fallback")){let{rest:n}=cm(t,8,e);return{type:"fallback",stateMutability:NS(n,"nonpayable")}}if(t.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new ki(e,"Expected function, event, error, constructor, fallback or receive.")}function DS(e){return e.map(Hg)}function Bo({blockNumber:e,blockTag:t="latest"}={}){return e!==void 0?Zn(e):t}function dm(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 US(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 Ug(await e.request({method:"eth_chainId"}))}async function Oc(e,{address:t,...n}){return ro(await e.request({method:"eth_getBalance",params:[t,Bo(n)]}))}async function Pi(e,{address:t,...n}){let r=await e.request({method:"eth_getCode",params:[t,Bo(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,Bo(r)]})??void 0}async function Dc(e,{address:t,...n}){return Ug(await e.request({method:"eth_getTransactionCount",params:[t,Bo(n)]}))}async function Uc(e){return ro(await e.request({method:"eth_gasPrice"}))}async function $g(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:[dm(r),Bo({blockNumber:t,blockTag:n})]}))}async function Mc(e,{includeTransactions:t=!1,...n}={}){let r=await e.request({method:"eth_getBlockByNumber",params:[Bo(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 xt="0xcA11bde05977b3631167028862bE2a173976CA11",p1={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:xt,blockCreated:14353601}}},m1={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:xt,blockCreated:4286263}}},h1={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:xt}}},f1={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:xt,blockCreated:25770160}}},g1={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:xt,blockCreated:5022}}},y1={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:xt,blockCreated:7654707}}},b1={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:xt}}},w1={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:xt}}},v1={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:xt}}},k1={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:xt}}},x1={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:xt}}},A1={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:xt}}},Da=[p1,m1,h1,f1,g1,y1,b1,w1,v1,k1,x1,A1];var T1=new Map,BS=new Map;function Az(e,t){return`${e??"unknown"}|${t.toLowerCase()}`}async function S1(e,t=xt){let n=Az(e.chain?.id??e.chain?.hexId,t),r=T1.get(n);if(r!==void 0)return r;let o=BS.get(n);if(o)return o;let s=(async()=>{try{let a=await Pi(e,{address:t})!==void 0;return T1.set(n,a),a}catch{return!0}finally{BS.delete(n)}})();return BS.set(n,s),s}async function Ua(e,t,n=!1){return n||typeof e.batch?.multicall=="object"&&e.batch.multicall.assumeMulticall3?!0:S1(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 Vg=[{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 Mo=[{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`."]})}},Ba=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 MS(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 pm({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}},FS=class extends $e{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:t,data:n,functionName:r}){let o=n?lm({abi:t,data:n}):void 0,s,i;if(n&&n!=="0x")try{let a=Ic({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}},qS=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."]})}},HS=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=>Tz(d)).join(", ")})`:void 0,u=a?.inputs?.length?`(${a.inputs.map(im).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}},mm=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 Tz(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 jg(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?jg(t.cause):void 0}function Vc(e,{abi:t,address:n,args:r,functionName:o,sender:s}){let i=jg(e),a=e instanceof vi?new qS({functionName:o}):i!==void 0?new FS({abi:t,data:i,functionName:o}):e;return new HS(a,{abi:t,address:n,args:r,functionName:o,sender:s})}var $S=new Map;function hm({fn:e,id:t,shouldSplitBatch:n,wait:r=0}){let o=()=>$S.get(t)??void 0,s=a=>$S.set(t,a),i=async a=>{o()===a&&$S.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 Sz(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 Pz(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 Ba;let l=pm({blockNumber:o,chain:e.chain,contract:"multicall3"});if(!await Ua(e,l,!1))throw new Ei({chain:e.chain.name,contract:"multicall3"});let c=o!==void 0?Zn(o):s,{schedule:u}=hm({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 Uo({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 Fo(e,t){let{blockNumber:n,blockTag:r,stateOverride:o,skipBatch:s,...i}=t;if(e.batch?.multicall&&!s&&Sz(t))try{let l=await Pz(e,{blockNumber:n,blockTag:r,data:i.data,to:i.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof Ba||l instanceof Ei))throw new mm(l,{to:i.to,data:i.data})}let a=[dm(i),Bo({blockNumber:n,blockTag:r})];o&&a.push(US(o));try{let l=await e.request({method:"eth_call",params:a});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new mm(l,{to:i.to,data:i.data})}}var VS=8;function P1(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:VS}function fm(e,t,n){if(t)return t;if(!e.chain)throw new Ba;let r=e.chain.contracts?.multicall3;return r?n!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(n)?xt:r.address:xt}async function jc(e,t,n={}){let{concurrency:r,account:o,blockNumber:s,blockTag:i,stateOverride:a}=n;return(await MS(t,P1(e,r),async c=>{let{data:u}=await Fo(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 qo(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 Fo(e,{...i,to:r,data:a});return Uo({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 Ez=1024,Rz=50;async function Ri(e,t){let{calls:n,account:r,blockNumber:o,blockTag:s,batchSize:i=Ez,maxCalls:a=Rz,multicallAddress:l,stateOverride:c,fallbackConcurrency:u}=t,d=n.map(()=>({success:!1,returnData:"0x"}));if(n.length===0)return d;let p=fm(e,l,o),m=[];if(n.forEach((w,v)=>{ge(w.target)&&Ia(w.callData)&&m.push({index:v,call:w})}),m.length===0)return d;if(!await Ua(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,A)=>{d[m[A].index]={success:v.success,returnData:v.returnData}}),d;let g=[],f;return m.forEach(({call:w,index:v})=>{let A=(w.callData.length-2)/2,k=i>0&&f!==void 0&&f.size+A>i,T=a>0&&f!==void 0&&f.calls.length>=a;(!f||(k||T)&&f.calls.length>0)&&(f={calls:[],indexes:[],size:0},g.push(f)),f.calls.push(w),f.indexes.push(v),f.size+=A}),(await Promise.allSettled(g.map(w=>qo(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((A,k)=>{let T=w.value[k];T&&(d[A]={success:!!T.success,returnData:T.returnData??"0x"})})}),d}var E1="https://wallet-api.pantograph.app/keyring/chains_v6",_z=6,Iz=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,R1={},Wc=null;function Cz(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://")||Iz.test(s))&&(r.includes(s)||r.push(s),r.length>=_z))break}return r}function _1(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=Ho(n)??(typeof o.chainId=="number"?Ho(o.chainId):void 0);if(!s)continue;let i=Cz(o);i.length>0&&(t[s]=i)}return t}function I1(e){R1=e}function jS(e){let t=Ho(e);return t?R1[t]??[]:[]}function WS(){Wc||Wg()}function Wg(e={}){let{url:t=E1,force:n=!1,debug:r=!1}=e;return Wc&&!n||(Wc=(async()=>{try{let o=await se.get(t);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=_1(o.data),i=Object.keys(s).length;if(i===0)throw new Error("catalogue contained no usable RPC endpoints");return I1(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 Wc=null,!1}})()),Wc}var Nz=new Map(Da.map(e=>[e.hexId.toLowerCase(),e])),Oz=new Map(Da.map(e=>[e.id,e]));function Ho(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 xn(e){if(typeof e=="number")return Oz.get(e);let t=Ho(e);return t?Nz.get(t):void 0}function Rs(e){return xn(e)?.nativeCurrency}var Fr=Object.fromEntries(Da.map(e=>[e.hexId,e.rpcUrls.default.http[0]]));function zS(e){return xn(e)?.rpcUrls.default.http[0]}var GS={};function Ma(e){let t={};if(e)for(let[n,r]of Object.entries(e)){if(typeof r!="string"||!r.trim())continue;let o=Ho(n)??n.toLowerCase();t[o]=r.trim()}GS=t}function gm(){return{...GS}}function Fa(e){WS();let t=Ho(e),n=t?GS[t]:void 0,r=jS(e),o=xn(e)?.rpcUrls.default.http??[];return[...new Set([...n?[n]:[],...r,...o])]}function $o(e){return Fa(e)[0]}function KS(e){let t=xn(e);if(!t)return;let n=Fa(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 _s=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}},zc=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.']})}},ym=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 qr(e,t,n){return class extends Kc{static code=t;name=e;constructor(r){super({...r,shortMessage:n})}}}var Lz=qr("ParseRpcError",-32700,"The node could not parse the JSON request."),Dz=qr("InvalidRequestRpcError",-32600,"The JSON request is not valid."),Uz=qr("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),Bz=qr("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),Mz=qr("InternalRpcError",-32603,"The node reported an internal error."),Fz=qr("InvalidInputRpcError",-32e3,"The RPC input is not valid."),qz=qr("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Hz=qr("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),$z=qr("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),Vz=qr("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),YS=qr("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),jz=qr("UserRejectedRequestError",4001,"The user rejected the request."),Wz=new Map([[-32700,Lz],[-32600,Dz],[-32601,Uz],[-32602,Bz],[-32603,Mz],[-32e3,Fz],[-32001,qz],[-32002,Hz],[-32003,$z],[-32004,Vz],[-32005,YS],[4001,jz]]);function C1(e){let t=Wz.get(e.error.code);return t?new t(e):new Kc(e)}function N1(e){return new Promise(t=>setTimeout(t,e))}async function QS(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 N1(i)}}function Gg(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 zz=new Set([408,413,429,500,502,503,504]),Gz=new Set([401,402,403]);function Kg(e){return e instanceof zc||e instanceof Gc?!0:e instanceof _s?e.status?zz.has(e.status)||e.status>=500:!0:e instanceof YS?!0:e instanceof Kc?e.code===-32603:!1}function Yg(e){return e instanceof _s&&e.status&&Gz.has(e.status)?!0:Kg(e)}function Qg(e,{retryCount:t=3,retryDelay:n=150,maxRetryAfterMs:r}={}){return function(s,i={}){return QS(()=>e(s),{retryCount:i.retryCount??t,shouldRetry:({error:a})=>{if(r!==void 0&&a instanceof _s){let l=Gg(a.headers);if(l!==void 0&&l>r)return!1}return Kg(a)},delay:({count:a,error:l})=>{let c=l instanceof _s?Gg(l.headers):void 0;return c!==void 0?c:(i.retryDelay??n)*2**(a-1)}})}}function _i({key:e,name:t,type:n,request:r,retryCount:o=3,retryDelay:s=150,maxRetryAfterMs:i,timeout:a=1e4},l){return{config:{key:e,name:t,type:n,request:r,retryCount:o,retryDelay:s,timeout:a},request:Qg(r,{retryCount:o,retryDelay:s,maxRetryAfterMs:i}),value:l}}var O1=0;function L1(){return O1+=1,O1}function Kz(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 Kz(r)?new zc({body:t,url:this.url,timeout:this.timeout}):new Gc({cause:r,url:this.url})}if(!n.ok)throw new _s({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:L1(),...t};return await this.post(n)??{id:n.id}}async requestBatch(t){let n=t.map(s=>({jsonrpc:"2.0",id:L1(),...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 D1(e,t,n){if(e.error)throw C1({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,maxRetryAfterMs:l,timeout:c}=t;return({chain:u,retryCount:d,retryDelay:p,timeout:m}={})=>{let{batchSize:g=1e3,wait:f=0}=typeof n=="object"?n:{},y=c??m??1e4,w=e??u?.rpcUrls.default.http[0];if(!w)throw new zg;let v=new Yc(w,{timeout:y,fetchOptions:r});return _i({key:o,name:s,type:"http",retryCount:i??d,retryDelay:a??p,maxRetryAfterMs:l,timeout:y,async request({method:A,params:k}){let T={method:A,params:k};if(n){let{schedule:D}=hm({id:`${w}:${g}:${f}`,wait:f,shouldSplitBatch:q=>q.length>g,fn:q=>v.requestBatch(q)});return D1(await D(T),T,w)}return D1(await v.request(T),T,w)}},{url:w})}}var U1=1e3;function bm(e){return wm(e.map((t,n)=>so(t,{retryCount:1,...n<e.length-1?{maxRetryAfterMs:U1}:{}})))}function wm(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 ym({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}),!Yg(m))throw m}throw new ym({cause:d,count:l.length})},retryCount:o,retryDelay:s,timeout:a.timeout},{transports:l})}}var Yz=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||Yz),d=new Array(n.length);if(n.length===0)return r?d:[];let p=fm(e,a,s),m=[],g;n.forEach((w,v)=>{let{abi:A,address:k,functionName:T,args:D}=w,q;try{if(!ge(k))throw new xc(k);q=Le({abi:A,functionName:T,args:D})}catch(Y){let te=Vc(Y,{abi:A,address:k,args:D,functionName:T,sender:o});if(!r)throw te;d[v]={status:"failure",error:te};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 Ua(e,p,a!==void 0)?await Promise.allSettled(m.map(w=>qo(e,{abi:oo,address:p,functionName:"aggregate3",args:[w.calls],account:o,blockNumber:s,blockTag:i,stateOverride:l}))):await(async()=>{let w=m.flatMap(A=>A.calls.map((k,T)=>({target:k.target,callData:k.callData,index:A.indexes[T]}))),v=await jc(e,w,{account:o,blockNumber:s,blockTag:i,stateOverride:l,concurrency:c});return m.length=0,v.map((A,k)=>(m.push({calls:[],indexes:[w[k].index],size:0}),A.success?{status:"fulfilled",value:[{success:!0,returnData:A.returnData}]}:{status:"rejected",reason:A.error}))})()).forEach((w,v)=>{let A=m[v];if(w.status==="rejected"){for(let k of A.indexes){let T=n[k],D=Vc(w.reason,{abi:T.abi,address:T.address,args:T.args,functionName:T.functionName,sender:o});if(!r)throw D;d[k]={status:"failure",error:D}}return}A.indexes.forEach((k,T)=>{let D=n[k],q=w.value[T];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=Uo({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 Qz=0,qa=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=Jz(t.chain),this.key=r,this.name=o,this.batch=n,this.uid=`${r}-${++Qz}-${Math.random().toString(36).slice(2,8)}`;let c=(t.transport??Xz(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 Fo(this,t)}readContract(t){return qo(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 $g(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 Xz(e,t){if(e)return so(e);let n=t?.rpcUrls.default.http??[];return n.length>1?bm(n):so(n[0])}function Jz(e){if(e===void 0)return;if(typeof e=="object")return e;let t=KS(e);if(!t)throw new Hc(e);return t}function Ii(e={}){return new qa(e)}var XS=new Map;function Zz(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:xt}}}}function Rt(e,t={}){let{batch:n=!0,pinRpcUrl:r=!1,fallbackConcurrency:o,assumeMulticall3:s}=t,i=Ho(e),a=t.rpcUrl?.trim(),l=i?Fa(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=XS.get(u);if(d)return d;let p=Ii({chain:i&&!xn(i)?Zz(i,c):i,transport:c.length===1?so(c[0]):bm(c),batch:n?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return XS.set(u,p),p}function Xg(){XS.clear()}function ZS(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?ZS(e,n):null;if(!o)return r;let s=[];if(t.forEach((i,a)=>{!ge(i.target)||!Ia(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 Jg(e){return e?.status==="success"?e.result:void 0}async function JS(e,t){try{return await e.multicall({contracts:t})}catch{return[]}}async function Vo(e,t,n){let r=t.map(()=>({symbol:null,decimals:null})),o=t.length>0?ZS(e,n):null;if(!o)return r;let s=[];if(t.forEach((l,c)=>{ge(l)&&s.push({index:c,address:l})}),s.length===0)return r;let i=await JS(o,s.flatMap(l=>[{address:l.address,abi:Ve,functionName:"symbol"},{address:l.address,abi:Ve,functionName:"decimals"}]));s.forEach((l,c)=>{let u=Jg(i[c*2]);typeof u=="string"&&u.trim()&&(r[l.index].symbol=u.trim()),r[l.index].decimals=Fg(Jg(i[c*2+1]))});let a=s.filter(l=>r[l.index].symbol===null);if(a.length>0){let l=await JS(o,a.map(c=>({address:c.address,abi:Fc,functionName:"symbol"})));a.forEach((c,u)=>{r[c.index].symbol=qg(Jg(l[u]))})}return r}async function B1(e,t,n){let r=new Array(t.length).fill(null),o=t.length>0?ZS(e,n):null;if(!o)return r;let s=[];return t.forEach((a,l)=>{if(ge(a.contract))try{s.push({index:l,address:a.contract,tokenId:BigInt(a.tokenId)})}catch{}}),s.length===0||(await JS(o,s.map(a=>({address:a.address,abi:qc,functionName:"tokenURI",args:[a.tokenId]})))).forEach((a,l)=>{let c=Jg(a);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(r[s[l].index]=u)}),r}function vm(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 eP(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 Ha(e){if(typeof e=="number")return Number.isFinite(e)&&e>0?vm(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 $a(e,t,n,r){let o=eP(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 Ci(e,t){let n=eP(e),r=eP(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 eG={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"}]},tG="payment-required",nG="PAYMENT-SIGNATURE",rG="X-PAYMENT",oG="payment-response",sG="x-payment-response",iG=600,aG=300,lG={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 M1(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 q1(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 cG(){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 H1(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=lG[t.toLowerCase()];if(n===void 0)throw new Error(`Unsupported x402 network: ${e}`);return n}function $1(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 Zg(e){let t=e.headers[tG];if(t){let o=F1(uG(t));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let n=e.data,r=n&&typeof n=="object"?n:F1(n);return r&&Array.isArray(r.accepts)?{version:1,payload:r}:null}function F1(e){if(typeof e!="string")return null;try{let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function uG(e){try{return q1(e)}catch{return null}}function dG(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 pG(e){let t=null;for(let n of e){let r=dG(n);if(r){if(r.scheme!=="exact"){t=`unsupported scheme "${r.scheme}"`;continue}try{return H1(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 tP(e,t,n,r){let o=Zg(e);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:i}=o,a=pG(i.accepts??[]);if(!n)throw new Error("No connected wallet address to build the payment from");let l=H1(a.network),c=Math.floor(Date.now()/1e3),u={from:n,to:a.payTo,value:String(a.amount),validAfter:String(Math.max(0,c-iG)),validBefore:String(c+(a.maxTimeoutSeconds??aG)),nonce:cG()},d={domain:{name:a.extra?.name,version:a.extra?.version,chainId:l,verifyingContract:a.asset},types:eG,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:$1(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 mG(e,t,n,r){let o=$1(t),s=await e.request(t.method??"GET",o,t.body,{headers:t.headers});if(s.status===402)return{status:"payment_required",challenge:tP(s,t,n,r)};if(!s.ok)throw new Error(he(s));return{status:"ok",data:s.data}}async function nP(e,t,n){let{url:r,method:o,body:s,headers:i}=t.request,a=await e.request(o,r,s,{headers:{...i??{},...rP(t,n)}});if(a.ok)return a.data;throw new Error(fG(a)??he(a))}function hG(e){return Zg(e)!==null}function V1(e){let t=j1(e);return t?.errorReason?t.errorReason:Zg(e)?.payload.error??null}function fG(e){let t=V1(e);return t?`x402 payment rejected: ${t}`:null}var gG={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 rP(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{[rG]:M1(JSON.stringify(i))}}let s={x402Version:2,...e.resource!=null?{resource:e.resource}:{},accepted:yG(n),payload:o,...e.extensions!=null?{extensions:e.extensions}:{}};return{[nG]:M1(JSON.stringify(s))}}function yG(e){let{resource:t,description:n,mimeType:r,outputSchema:o,...s}=e;return s}function j1(e){let t=e.headers[oG]??e.headers[sG];if(!t)return null;try{return JSON.parse(q1(t))}catch{return null}}function bG(e,t){return e==null?t:gG[e]??`Chain ${e}`}async function W1(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 Vo("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:bG(o,t.network),payTo:t.payTo,...r?{description:r}:{},resourceUrl:e.request.url}}function oP(e){return async(t,n)=>{let r=e.getPayer(),o=e.getSigner();if(!r||!o)return null;let s;try{s=tP(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 W1(s)})}catch{i=null}return i?rP(s,i):null}}var Ni=class extends Error{constructor(t="Aborted"){super(t),this.name="AbortError"}};function Va(e){if(!e||typeof e!="object")return!1;let t=e;return t.name==="AbortError"||t.name==="CanceledError"||t.code==="ERR_CANCELED"}function km(e){if(e?.aborted)throw new Ni}function sP(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 z1={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},wG="https://nft.keyring.app/api/gemini-stable",vG="https://generativelanguage.googleapis.com",kG=new Set([408,429,500,502,503,504]),G1=3e4,ey=e=>new Promise(t=>setTimeout(t,e));function ty(e,t,n){if(n!=null&&n>0)return Math.min(n,G1);let r=Math.min(t*2**(e-1),G1);return r/2+Math.random()*(r/2)}function xG(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?vG:wG)).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;km(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++){km(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(Va(q))throw q;if(g=q instanceof Error?q.message:String(q),f>=i)break;await ey(ty(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}`,!kG.has(y.status))throw new Error(g);if(f>=i)break;let V=xG(y.headers["retry-after"]??null);await ey(ty(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 ey(ty(f,a));continue}let w=y.data,v=w.candidates?.[0];if(!v)return{text:"",toolCalls:[]};let A="",k=[],T=v.content?.parts;if(!Array.isArray(T)||T.length===0){let q=v.finishReason;if(!(q==="SAFETY"||q==="RECITATION")&&f<i){g=`Gemini returned an empty turn (finishReason=${q??"none"})`,await ey(ty(f,a));continue}return{text:"",toolCalls:[]}}for(let q of T)q.text&&(A+=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:A,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:z1[s.type]??"STRING",description:s.description};s.type==="array"&&(i.items={type:z1[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"],AG=new Set(eu),Oi=[...eu],iP=new Set(Oi),er="0x1",nu="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function TG(e){return e.map(t=>tu[t]??t).join(", ")}function ny(e){let t=new Set;if(e)for(let r of e){let o=ry(r);o&&t.add(o)}let n=eu.filter(r=>!t.has(r));Oi=n.length>0?[...n]:[...eu],iP=new Set(Oi),er=Oi.includes("0x1")?"0x1":Oi[0],nu=TG(Oi)}var SG={"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=ry(e);return t&&iP.has(t)?t:null}function ry(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase().replace(/\s+/g," ");if(!t)return null;let n=SG[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&&AG.has(r)?r:null}function tr(e){return Ce(e)!==null}function nr(){return[...Oi]}var Li=class extends Error{constructor(n){super(`Chain "${n}" is not supported. Supported chains: ${nu}.`);this.requested=n;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Cs=e=>typeof e=="string"&&e.trim()!=="";function at(e,t){if(Cs(e)){let n=Ce(e);if(n)return n;throw new Li(e.trim())}if(Cs(t?.chain)){let n=Ce(t.chain);if(n)return n;throw new Li(t.chain.trim())}return null}function oy(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=ry(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 K1(e,t){let n=ry(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 EG={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Y1(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t?EG[t]??null:null}var RG={"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 sy(e){let t=Ce(e);return t?RG[t]??null:null}function iy(e,t){if(!Cs(e)||!Cs(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 ay(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 Hr=`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 Q1(e,t){let n=typeof e=="string"?e.trim():"",r=t&&t.length?t.filter(s=>iP.has(s)):[];return(r.length?r:Oi).map(s=>{let i=tu[s]??s;return{label:i,prompt:n?`${n} (${i})`:i}})}function ou(e,t){return{actionButtons:Q1(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=Q1(t,n)}},xm=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 gt(e,t){if(Cs(e))return e.trim();if(Cs(t?.walletAddress))return t.walletAddress.trim();throw new xm}function rn(e,t,n){if(Cs(e)){let r=Ce(e);if(r)return r;throw new Li(e.trim())}if(Cs(t?.chain)){let r=Ce(t.chain);if(r)return r;throw new Li(t.chain.trim())}if(Cs(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=_G(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 xm?{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 _G(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 X1(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 J1(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 ja(e){let t=X1(e),n=J1(e);return t===void 0&&n===void 0?null:{yieldProtocol:t,yieldAsset:n}}var IG="https://wallet-api.pantograph.app",CG="0x0000000000000000000000000000000000000000",nD={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},rD={"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 NG(e){return nD[e.toLowerCase()]||e}function Z1(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 aP(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 eD(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 ly=new WeakSet;function tD(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&&ly.add(i),i}var OG=100;function LG(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??IG).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=LG(n,OG);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?eD(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=ja(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=eD(o.data),i=t.toLowerCase()===CG,a=s.find(l=>l.address?.toLowerCase()===t.toLowerCase()||i&&l.address===""||l.token_address?.toLowerCase()===t.toLowerCase()||i&&l.token_address==="");return a?aP(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]=aP(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=Z1({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(aP)}}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=rD[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=>tD(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||!ly.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&&!ly.has(s)&&(s.symbol=a,ly.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=Z1({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=>tD(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 pt(e,t,n,r=[]){return{target:e,callData:Le({abi:t,functionName:n,args:r})}}var Wa=1e27,cy=10n**27n,Am=31536e3,DG=10;function $r(e){return Number.isFinite(e)&&e>=0&&e<=DG?e:null}function lP(e){return Math.expm1(e)}function Vr(e,t){return Number(e)/10**t}function Tm(e){return new Date(e).toISOString().slice(0,10)}async function Di(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 jo=class{underlyingCall(t){return pt(t.contract,Mo,"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=ft(t);return r===null?null:Vr(r,n.decimals)}decodeLiveRate(t){return null}convertToAssetsCall(t,n){return this.balanceIsUnderlying?null:pt(t.contract,Mo,"convertToAssets",[n])}},Wo=class extends jo{type="spark";balanceIsUnderlying=!1;sizeCall(t){return pt(t.contract,Mo,"totalAssets")}fetchApy(t,n,r,o){return Di(t,n,r)}};var cP=[{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 uP=[{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 dy=[{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"}]}],dP=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Ns=[{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"}],pP=[{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"}],Ui=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],mP=[{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 hP=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],fP=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var MG=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|
|
@@ -46,7 +46,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
|
|
|
46
46
|
- Market Cap: <marketCap>
|
|
47
47
|
- Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
|
|
48
48
|
- 24h Volume: <totalVolume.24h>
|
|
49
|
-
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:r?j(r):"all",timeFrame:s??null,count:c.length,tokens:c}}};function fu(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,r=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(r+"00").slice(0,2)}`}function gu(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<=0))return`($${fu(e)})`}var yu=class extends K{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n);if(o){let a=await this.service.getWalletTokenBalances({address:r,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return a.success?this.renderBalances(r,o,a.data?.result||[]):{error:a.error||"Failed to fetch token balances"}}let s=nr(),i=await Promise.all(s.map(async a=>{let l=await this.service.getWalletTokenBalances({address:r,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:a,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(r,i)}toTokenLine(t){let n=t.name||t.symbol||"Unknown",r=t.balance_formatted??"0",o=t.symbol||"",s=typeof t.usd_value=="number"?`$${fu(t.usd_value)}`:"$-";return`- ${n}: ${r} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(t,n,r){let o=r.reduce((s,i)=>s+(i.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:t,chain:n,totalUsdValue:`$${fu(o)}`,tokens:r.map(s=>this.toTokenLine(s))}}renderBalancesByChain(t,n){let r=n.map(s=>{let i=s.tokens.reduce((l,c)=>l+(c.usd_value||0),0),a=s.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:j(s.chain),total:i,tokens:a}}).filter(s=>s.tokens.length>0).sort((s,i)=>i.total-s.total),o=r.reduce((s,i)=>s+i.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:t,chain:"all",totalUsdValue:`$${fu(o)}`,chains:r.map(s=>({chain:s.chain,totalUsdValue:`$${fu(s.total)}`,tokens:s.tokens.map(i=>this.toTokenLine(i))}))}}};var bu=class extends K{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=rn(t.chain,n),s=typeof t.fromDate=="string"&&t.fromDate?t.fromDate:void 0,i=typeof t.toDate=="string"&&t.toDate?t.toDate:void 0,a=typeof t.fromBlock=="number"?t.fromBlock:typeof t.fromBlock=="string"&&t.fromBlock?Number(t.fromBlock):void 0,l=typeof t.toBlock=="number"?t.toBlock:typeof t.toBlock=="string"&&t.toBlock?Number(t.toBlock):void 0,c=Number.isFinite(a)?a:void 0,u=Number.isFinite(l)?l:void 0,d=typeof t.cursor=="string"&&t.cursor?t.cursor:void 0,m=(typeof t.order=="string"?t.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",g=typeof t.includeInternalTransactions=="boolean"?t.includeInternalTransactions:void 0,f=typeof t.nftMetadata=="boolean"?t.nftMetadata:void 0,y=typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,w=Number.isFinite(y)&&y>0?y:10,v=await this.service.getWalletHistory({address:r,chain:o,limit:w,fromDate:s,toDate:i,fromBlock:c,toBlock:u,cursor:d,order:m,includeInternalTransactions:g,nftMetadata:f});if(!v.success)return{error:v.error||"Failed to fetch wallet history"};let k=(v.data?.result||[]).map(T=>{let D=K1(o,T.hash);return D?{...T,explorerUrl:D}:T});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:r,chain:o||"default",pagination:{cursor:v.data?.cursor??null,hasMore:!!v.data?.cursor},transactionCount:k.length,transactions:k}}};function hK(e){if(e.value_decimal)return e.value_decimal;let t=parseInt(e.token_decimals??"18",10);if(isNaN(t)||t===0)return e.value;try{let n=BigInt(e.value),r=BigInt(10)**BigInt(t),o=n/r,i=(n%r).toString().padStart(t,"0").replace(/0+$/,"");return i?`${o}.${i}`:`${o}`}catch{return e.value}}var wu=class extends K{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=rn(t.chain,n),s=typeof t.limit=="number"?t.limit:Number(t.limit),i=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,a=typeof t.fromDate=="string"&&t.fromDate?t.fromDate:void 0,l=typeof t.toDate=="string"&&t.toDate?t.toDate:void 0,c=this.parseBlock(t.fromBlock),u=this.parseBlock(t.toBlock),d=typeof t.cursor=="string"&&t.cursor?t.cursor:void 0,m=(typeof t.order=="string"?t.order.toUpperCase():"")==="ASC"?"ASC":"DESC",g=typeof t.direction=="string"?t.direction.trim().toLowerCase():"all",f=g==="send"?"send":g==="receive"?"receive":"all",y=typeof t.tokenSymbol=="string"&&t.tokenSymbol?t.tokenSymbol.trim():void 0,w=Array.isArray(t.contractAddresses)?t.contractAddresses.filter(te=>typeof te=="string"&&!!te).map(te=>te.trim()):void 0,v,A;if(y){let te=await this.resolveContractAddressBySymbol(y,r,o);te&&(w=[te.address],v=te.symbol,A=te.name)}let k=await this.service.getWalletTokenTransfers({address:r,chain:o,contractAddresses:w,limit:i,fromDate:a,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let T=r.toLowerCase(),q=(k.data?.result||[]).map(te=>{let de=te.from_address.toLowerCase()===T,oe=de?"send":"receive",F=de?te.to_address:te.from_address,z=de?te.to_address_label??void 0:te.from_address_label??void 0,_=de?te.to_address_entity??void 0:te.from_address_entity??void 0;return{...te,direction:oe,amount_formatted:hK(te),counterparty:F,counterparty_label:z,counterparty_entity:_}}),V=f==="all"?q:q.filter(te=>te.direction===f);if(y&&!w){let te=y.toLowerCase();V=V.filter(de=>(de.token_symbol??"").toLowerCase()===te)}let Y=this.buildCounterparties(V);return{walletAddress:r,chain:o||"default",resolvedToken:v?{symbol:v,name:A,contractAddress:w?.[0]}:null,filters:{tokenSymbol:y||null,contractAddresses:w||null,direction:f,limit:i,order:m,fromDate:a||null,toDate:l||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??i,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:V.length,transfers:V,counterparties:Y}}async resolveContractAddressBySymbol(t,n,r){let o=t.toLowerCase(),s=await this.service.getWalletTokenBalances({address:n,chain:r});if(s.success&&s.data?.result?.length){let a=s.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}let i=await this.service.searchTokensByKey({key:t,chain:r});if(i.success&&i.data?.length){let l=i.data.find(c=>(c.symbol??"").toLowerCase()===o)??i.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(t){let n=new Map,r=new Map;for(let s of t){let i=s.direction==="send"?n:r,a=s.counterparty.toLowerCase(),l=parseFloat(s.amount_formatted)||0,c=i.get(a);c?(c.total+=l,c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):i.set(a,{label:s.counterparty_label,entity:s.counterparty_entity,total:l,count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((i,a)=>a[1].count-i[1].count).map(([i,a])=>({address:i,label:a.label,entity:a.entity,total_amount:a.total.toFixed(6).replace(/\.?0+$/,""),tx_count:a.count,first_seen:a.first,last_seen:a.last}));return{sent:o(n),received:o(r)}}parseBlock(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t=="string"&&t){let n=Number(t);return Number.isFinite(n)?n:void 0}}};var vu=class extends K{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=rn(t.chain,n),s=typeof t.limit=="number"?t.limit:Number(t.limit),i=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,a=typeof t.fromDate=="string"&&t.fromDate?t.fromDate:void 0,l=typeof t.toDate=="string"&&t.toDate?t.toDate:void 0,c=this.parseBlock(t.fromBlock),u=this.parseBlock(t.toBlock),d=typeof t.cursor=="string"&&t.cursor?t.cursor:void 0,m=(typeof t.order=="string"?t.order.toUpperCase():"")==="ASC"?"ASC":"DESC",g=typeof t.includePrices=="boolean"?t.includePrices:void 0,f=typeof t.direction=="string"?t.direction.trim().toLowerCase():"all",y=f==="send"?"send":f==="receive"?"receive":"all",w=Array.isArray(t.contractAddresses)?t.contractAddresses.filter(V=>typeof V=="string"&&!!V).map(V=>V.trim()):void 0,v=await this.service.getWalletNftTransfers({address:r,chain:o,contractAddresses:w,limit:i,fromDate:a,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m,includePrices:g});if(!v.success)return{error:v.error||"Failed to fetch NFT transfers"};let A=r.toLowerCase(),T=(v.data?.result||[]).map(V=>{let Y=V.from_address.toLowerCase()===A,te=Y?"send":"receive",de=Y?V.to_address:V.from_address,oe=Y?V.to_address_label??void 0:V.from_address_label??void 0,F=Y?V.to_address_entity??void 0:V.from_address_entity??void 0;return{...V,direction:te,counterparty:de,counterparty_label:oe,counterparty_entity:F}}),D=y==="all"?T:T.filter(V=>V.direction===y),q=this.buildCounterparties(D);return{walletAddress:r,chain:o||"default",filters:{contractAddresses:w||null,direction:y,limit:i,order:m,fromDate:a||null,toDate:l||null,fromBlock:c??null,toBlock:u??null,includePrices:g??null},pagination:{cursor:v.data?.cursor??null,pageSize:v.data?.page_size??i,page:v.data?.page??null,hasMore:!!v.data?.cursor},transferCount:D.length,transfers:D,counterparties:q}}buildCounterparties(t){let n=new Map,r=new Map;for(let s of t){let i=s.direction==="send"?n:r,a=s.counterparty.toLowerCase(),l=s.token_name??s.token_address,c=i.get(a);c?(c.tokenIds.add(s.token_id),c.collections.add(l),c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):i.set(a,{label:s.counterparty_label,entity:s.counterparty_entity,tokenIds:new Set([s.token_id]),collections:new Set([l]),count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((i,a)=>a[1].count-i[1].count).map(([i,a])=>({address:i,label:a.label,entity:a.entity,token_ids:Array.from(a.tokenIds),collections:Array.from(a.collections),tx_count:a.count,first_seen:a.first,last_seen:a.last}));return{sent:o(n),received:o(r)}}parseBlock(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t=="string"&&t){let n=Number(t);return Number.isFinite(n)?n:void 0}}};var fK=["all","7","30","60","90"],ku=class extends K{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n),s=typeof t.days=="string"?t.days.trim().toLowerCase():"",i=fK.includes(s)?s:void 0;if(o){let f=await this.service.getWalletPnlSummary({address:r,chain:o,days:i});return f.success?{walletAddress:r,chain:o,days:i??"all",summary:this.mapSummary(f.data)}:{error:f.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(nr().map(async f=>{let y=await this.service.getWalletPnlSummary({address:r,chain:f,days:i});return{chain:f,data:y.success?y.data:void 0}}))).flatMap(f=>f.data&&f.data.total_count_of_trades>0?[{chain:f.chain,data:f.data}]:[]),c=l.map(f=>({chain:j(f.chain),summary:this.mapSummary(f.data)})),u=l.reduce((f,y)=>f+Number(y.data.total_realized_profit_usd||0),0),d=l.reduce((f,y)=>f+Number(y.data.total_bought_volume_usd||0),0),p=l.reduce((f,y)=>f+Number(y.data.total_sold_volume_usd||0),0),m=l.reduce((f,y)=>f+Number(y.data.total_trade_volume||0),0),g={totalCountOfTrades:l.reduce((f,y)=>f+y.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:l.reduce((f,y)=>f+y.data.total_buys,0),totalSells:l.reduce((f,y)=>f+y.data.total_sells,0),totalBoughtVolumeUsd:d,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:r,chain:"all",days:i??"all",summary:g,chains:c}}mapSummary(t){return{totalCountOfTrades:t.total_count_of_trades,totalTradeVolume:t.total_trade_volume,totalRealizedProfitUsd:t.total_realized_profit_usd,totalRealizedProfitPercentage:t.total_realized_profit_percentage,totalBuys:t.total_buys,totalSells:t.total_sells,totalBoughtVolumeUsd:t.total_bought_volume_usd,totalSoldVolumeUsd:t.total_sold_volume_usd}}};var gK=["all","7","30","60","90"],yy=25,xu=class extends K{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${yy}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${yy}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${yy}.`,required:!1,items:{type:"string"}}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n),s=typeof t.days=="string"?t.days.trim().toLowerCase():"",i=gK.includes(s)?s:void 0,a=Array.isArray(t.tokenSymbols)?t.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],l=Array.isArray(t.tokenAddresses)?t.tokenAddresses.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[];if(o){let d=await this.fetchChainPnl(r,o,i,a,l);return d.ok?{walletAddress:r,chain:o,days:i??"all",filters:{tokenAddresses:d.tokenAddresses??null,resolvedSymbols:d.resolvedFromSymbols.length>0?d.resolvedFromSymbols:null,unresolvedSymbols:d.unresolvedSymbols.length>0?d.unresolvedSymbols:null},tokenCount:d.tokens.length,tokens:d.tokens}:{error:d.error||"Failed to fetch wallet PnL"}}let u=(await Promise.all(nr().map(async d=>({chain:d,res:await this.fetchChainPnl(r,d,i,a,l)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:j(d.chain),tokenCount:d.res.tokens.length,tokens:d.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:r,chain:"all",days:i??"all",filters:{requestedSymbols:a.length>0?a:null,requestedAddresses:l.length>0?l:null},tokenCount:u.reduce((d,p)=>d+p.tokenCount,0),chains:u}}async fetchChainPnl(t,n,r,o,s){let i=[],a=[];o.length>0&&(await Promise.all(o.map(p=>this.resolveContractAddress(p,n,t)))).forEach((p,m)=>{p?i.push({symbol:o[m],address:p.address}):a.push(o[m])});let l=yK([...i.map(d=>d.address),...s]).slice(0,yy),c=l.length>0?l:void 0,u=await this.service.getWalletPnl({address:t,chain:n,days:r,tokenAddresses:c});return{ok:u.success,error:u.error,tokens:u.data?.result??[],tokenAddresses:c,resolvedFromSymbols:i,unresolvedSymbols:a}}async resolveContractAddress(t,n,r){let o=t.toLowerCase();if(r){let i=await this.service.getWalletTokenBalances({address:r,chain:n});if(i.success&&i.data?.result?.length){let a=i.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let s=await this.service.searchTokensByKey({key:t,chain:n});if(s.success&&s.data?.length){let a=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};function yK(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}var bK=BigInt(2)**BigInt(255),Au=class extends K{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=rn(t.chain,n),s=typeof t.limit=="number"?t.limit:Number(t.limit),i=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):100,a=typeof t.cursor=="string"&&t.cursor?t.cursor:void 0,l=await this.service.getWalletApprovals({address:r,chain:o,limit:i,cursor:a});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,d=(c.result||[]).map(f=>wK(f)),p=0,m=0,g=[];for(let f of d){f.isUnlimited&&(m+=1);let y=parseFloat(f.token.usdAtRisk??"");Number.isFinite(y)&&(p+=y);let w=f.token.possibleSpam||f.token.verifiedContract===!1,v=!f.spender.label&&!f.spender.entity;(w||f.isUnlimited&&v)&&g.push(f)}return{walletAddress:r,chain:o||"default",filters:{limit:i,cursor:a??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??i,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:g.length},approvals:d,riskyApprovals:g}}};function wK(e){let t=vK(e.value);return{blockNumber:e.block_number,blockTimestamp:e.block_timestamp??null,transactionHash:e.transaction_hash??null,value:e.value,valueFormatted:e.value_formatted??null,isUnlimited:t,token:{address:e.token.address,addressLabel:e.token.address_label??null,name:e.token.name??null,symbol:e.token.symbol??null,logo:e.token.logo??null,possibleSpam:!!e.token.possible_spam,verifiedContract:e.token.verified_contract??null,currentBalance:e.token.current_balance??null,currentBalanceFormatted:e.token.current_balance_formatted??null,usdPrice:e.token.usd_price??null,usdAtRisk:e.token.usd_at_risk??null},spender:{address:e.spender.address,label:e.spender.address_label??null,entity:e.spender.entity??null,entityLogo:e.spender.entity_logo??null}}}function vK(e){if(!e)return!1;try{return BigInt(e)>=bK}catch{return!1}}var pD=.01,Tu=class extends K{name="get-wallet-defi-positions";description=`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n);if(o){let a=await this.service.getWalletDefiPositions({address:r,chain:o});if(!a.success)return{error:a.error||"Failed to fetch wallet DeFi positions"};let l=(a.data||[]).filter(mD);return{walletAddress:r,chain:o,positionCount:l.length,positions:l.map(hD)}}let i=(await Promise.all(nr().map(async a=>{let l=await this.service.getWalletDefiPositions({address:r,chain:a});return{chain:a,rows:l.success?(l.data||[]).filter(mD):[]}}))).filter(a=>a.rows.length>0).map(a=>({chain:j(a.chain),positionCount:a.rows.length,positions:a.rows.map(hD)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:r,chain:"all",positionCount:i.reduce((a,l)=>a+l.positionCount,0),chains:i}}};function mD(e){let t=e.position?.balance_usd,n=e.position?.total_unclaimed_usd_value;return typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=pD?!0:typeof n=="number"&&n>=pD}function hD(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,accountHealthFactor:e.account_data?.health_factor??null,position:kK(e.position)}}function kK(e){return{label:e.label,address:e.address,balanceUsd:e.balance_usd,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,tokens:(e.tokens||[]).map(t=>({tokenType:t.token_type,name:t.name,symbol:t.symbol,contractAddress:t.contract_address,decimals:t.decimals,logo:t.logo,thumbnail:t.thumbnail,balance:t.balance,balanceFormatted:t.balance_formatted,usdPrice:t.usd_price,usdValue:t.usd_value})),details:e.position_details??null}}var Su=class extends K{name="get-wallet-defi-protocol-positions";description=`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=t.protocol?.trim();if(!r)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=gt(t.address,n),s=at(t.chain,n);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,chain:s});return l.success?l.data?{walletAddress:o,chain:s,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let a=(await Promise.all(nr().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:j(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${r} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:r,totalUsdValue:a.reduce((l,c)=>l+c.totalUsdValue,0),chains:a}}protocolFields(t){return{protocolName:t.protocol_name,protocolId:t.protocol_id,protocolUrl:t.protocol_url,protocolLogo:t.protocol_logo,totalUsdValue:t.total_usd_value,totalUnclaimedUsdValue:t.total_unclaimed_usd_value,accountHealthFactor:t.account_data?.health_factor??null,positionCount:(t.positions||[]).length,positions:(t.positions||[]).map(xK)}}};function xK(e){return{label:e.label,address:e.address,balanceUsd:e.balance_usd,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,tokens:(e.tokens||[]).map(t=>({tokenType:t.token_type,name:t.name,symbol:t.symbol,contractAddress:t.contract_address,decimals:t.decimals,logo:t.logo,thumbnail:t.thumbnail,balance:t.balance,balanceFormatted:t.balance_formatted,usdPrice:t.usd_price,usdValue:t.usd_value})),details:e.position_details??null}}function AK(e){try{return(Number(BigInt(e))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return e}}var Pu=class extends K{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=t.transactionHash;if(!r)return{error:"Transaction hash is required."};let o=rn(t.chain,n),s=await this.service.getTransactionByHash({transactionHash:r,chain:o});if(!s.success||!s.data)return{error:s.error||"Failed to fetch transaction"};let i=s.data,a=(i.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=i.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:i.hash,status:i.receipt_status==="1"?"success":i.receipt_status==="0"?"failed":"unknown",timestamp:i.block_timestamp,blockNumber:i.block_number,from:{address:i.from_address,label:i.from_address_label||null,entity:i.from_address_entity||null},to:i.to_address?{address:i.to_address,label:i.to_address_label||null,entity:i.to_address_entity||null}:null,valueEth:AK(i.value||"0"),fee:i.transaction_fee,gasUsed:i.receipt_gas_used,gasPriceGwei:i.gas_price?(Number(i.gas_price)/1e9).toFixed(4):null,decodedCall:i.decoded_call?{signature:i.decoded_call.signature,label:i.decoded_call.label,params:i.decoded_call.params}:null,decodedEvents:a,contractCreated:i.receipt_contract_address||null,logs:l}}};var fD=new Map;function TK(e){let t=fD.get(e);if(t)return t;let n=Ii({rpcUrl:e});return fD.set(e,n),n}async function gD(e,t,n=[]){let r=await TK(e).rpc(t,n);if(r===void 0)throw new Error(`RPC ${t}: empty result`);return r}function yD(e,t,n){return gD(e,"eth_call",[{to:t,data:n},"latest"])}async function SK(e,t,n){let r=$o(e);if(!r)return null;try{return await yD(r,t,n)}catch{return null}}function Te(e,t){globalThis.__LENDING_DEBUG__!==!1&&(t===void 0?console.log(`[LEND] ${e}`):console.log(`[LEND] ${e}`,JSON.stringify(t,PK)))}function PK(e,t){return typeof t=="bigint"?`${t}n`:t}var EK=6e4,vP=new Map;async function Mm(e,t){let n=Os(t),r=n?parseInt(n,16):NaN;if(!n||!Number.isFinite(r))return[];let o=`${e}|${n}`,s=vP.get(o);if(s&&Date.now()-s.at<EK)return s.markets;let i=RK(e,n,r),a=i.then(l=>l.markets);return vP.set(o,{at:Date.now(),markets:a}),i.then(l=>{l.answered||vP.delete(o)}),a}async function by(e,t){return(await Mm(e,t)).length>0}async function RK(e,t,n){try{let r=`${e}/supply/v2?chainId=${n}&limit=100&page=1`;Te("catalog: GET",r);let o=await se.get(r);if(!o.ok){let i=o.status>=400&&o.status<500;return Te(i?"catalog: chain not served":"catalog: FAILED",{chain:t,status:o.status,message:he(o)}),{markets:[],answered:i}}let s=(o.data?.data?.items||[]).flatMap(i=>{let a=_K(i,t);return a?[a]:[]});return Te("catalog: got markets",{chain:t,rawItems:o.data?.data?.items?.length??0,usable:s.length,tokens:s.map(i=>i.token)}),{markets:s,answered:!0}}catch(r){return Te("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:t,message:r?.message}),{markets:[],answered:!1}}}function bD(e,t){let n=t.trim().toLowerCase();if(!n)return[];if(ge(n))return e.filter(o=>o.contract===n||o.token===n);let r=e.filter(o=>o.name.trim().toLowerCase()===n);return r.length>0?r:e.filter(o=>{let s=o.name.trim().toLowerCase(),i=o.protocol.trim().toLowerCase();return s.includes(n)||n.includes(s)||i.includes(n)||n.includes(i)})}function _K(e,t){if(e?.isDeleted===!0)return null;let n=typeof e?.contract=="string"?e.contract.toLowerCase():"";if(!ge(n))return null;let r=typeof e?.token=="string"&&ge(e.token)?e.token.toLowerCase():n,o=Number(e?.rating?.balanceScore),s=e?.type?.trim()||"unknown";return{chain:t,name:e?.name?.trim()||"USDC lending market",protocol:e?.protocolId?.name?.trim()||"Unknown",protocolLabel:yr(s),protocolUrl:e?.protocolId?.domain?.trim()||null,type:s,contract:n,token:r,platformScore:Number.isFinite(o)?o:null}}function kP(){return nr()}async function wy(e){let t=kP(),n=await Promise.all(t.map(r=>by(e,r)));return t.filter((r,o)=>n[o])}async function vy(e,t){let n=Ce(t);return n?by(e,n):!1}async function wD(e,t){let n=t.map(s=>Ce(s)).filter(s=>!!s),r=[...new Set(n)],o=await Promise.all(r.map(s=>by(e,s)));return r.filter((s,i)=>o[i])}function Ka(e){return Nm(e)}var vD=6;async function kD(e,t,n){let r=t.map(A=>ge(A)?A.toLowerCase():null);if(r.every(A=>A===null))return Te("discovery: ABORT \u2014 no valid token address",{tokens:t}),t.map(()=>null);let o=hy(e),s;try{Te("discovery: probing 5 accessors per token",{chain:e,tokens:r,psm:o}),s=await Qt(e,[...r.flatMap(A=>A?IK(A):[]),...o?oD(o):[]])}catch(A){return Te("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:e,message:A?.message}),t.map(()=>null)}let i=o?s.slice(s.length-sD):[],a=Ge(i[0])?.toLowerCase()??null,l=Ge(i[1]),c=Ge(i[2]),u=a&&l&&c?{susds:a,usds:l,oracle:c}:null;o&&Te("discovery: PSM3 lookup",{psm:o,susds:a,usds:l,oracle:c});let d=0,p=r.map(A=>{if(!A)return null;let k=s.slice(d,d+vD);return d+=vD,Te("discovery: probe answers",{token:A,"POOL()":Ge(k[0]),"UNDERLYING_ASSET_ADDRESS()":Ge(k[1]),"baseToken()":Ge(k[2]),"asset()":Ge(k[3]),"vsr()":ft(k[4])?.toString()??null,"manager()":Ge(k[5])}),{token:A,slice:k}}),m=new Set;for(let A of p){if(!A)continue;let k=Ge(A.slice[0]);k&&Ge(A.slice[1])&&m.add(k.toLowerCase())}let g=await CK(e,[...m]);m.size>0&&Te("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let f=new Map;for(let A of p){if(!A||Ge(A.slice[0])&&Ge(A.slice[1])||Ge(A.slice[2])||!Ge(A.slice[3]))continue;let T=Ge(A.slice[5]);T&&f.set(A.token,T.toLowerCase())}let y=await NK(e,f);f.size>0&&Te("discovery: Maple manager authentication",{claimed:[...f.keys()],genuine:[...y]});let w=p.flatMap(A=>A?Ge(A.slice[0])&&Ge(A.slice[1])||Ge(A.slice[2])?[]:y.has(A.token)?[]:Ge(A.slice[3])?[A.token]:[]:[]),v=await OK(e,[...new Set(w)],n);return w.length>0&&Te("discovery: Morpho vault lookup",{asked:[...new Set(w)],recognised:[...v.keys()]}),p.map(A=>{if(!A)return null;let{token:k,slice:T}=A,D={chain:e,protocolUrl:null,token:k,platformScore:null};if(u&&k===u.susds)return Te("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...D,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:yr("spark-l2-susds"),protocolUrl:Ka("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let q=Ge(T[0]);if(q&&Ge(T[1])){let V=g.has(q.toLowerCase());return Te("discovery: classified",{token:k,as:V?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:q}),V?{...D,name:"Aave v3",protocol:"AAVE",protocolLabel:yr("aave-v3"),protocolUrl:Ka("aave-v3"),type:"aave-v3",contract:q}:null}if(Ge(T[2]))return Te("discovery: classified",{token:k,as:"compound-v3"}),{...D,name:"Compound v3",protocol:"COMPOUND",protocolLabel:yr("compound-v3"),protocolUrl:Ka("compound-v3"),type:"compound-v3",contract:k};if(Ge(T[3])){if(y.has(k))return Te("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...D,name:"Maple",protocol:"MAPLE",protocolLabel:yr("maple"),protocolUrl:Ka("maple"),type:"maple",contract:k};if(v.has(k)){Te("discovery: classified",{token:k,as:"morpho-v2"});let te=v.get(k)||"Morpho V2";return{...D,name:te,protocol:"MORPHO",protocolLabel:yr("morpho-v2"),protocolUrl:Ka("morpho-v2"),type:"morpho-v2",contract:k}}let Y=ft(T[4])!==null;return Te("discovery: classified",{token:k,as:Y?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),Y?{...D,name:"Spark",protocol:"SPARK",protocolLabel:yr("spark-ethereum"),protocolUrl:Ka("spark-ethereum"),type:"spark-ethereum",contract:k}:{...D,name:"Spark",protocol:"SPARK",protocolLabel:yr("spark"),protocolUrl:Ka("spark"),type:"spark",contract:k}}return Te("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function IK(e){return[{target:e,callData:Le({abi:su,functionName:"POOL"})},{target:e,callData:Le({abi:su,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:e,callData:Le({abi:Ns,functionName:"baseToken"})},{target:e,callData:Le({abi:Mo,functionName:"asset"})},{target:e,callData:Le({abi:iu,functionName:"vsr"})},{target:e,callData:Le({abi:hP,functionName:"manager"})}]}async function CK(e,t){if(t.length===0)return new Set;try{let n=await Qt(e,t.map(r=>({target:r,callData:Le({abi:dP,functionName:"ADDRESSES_PROVIDER"})})));return new Set(t.filter((r,o)=>Ge(n[o])!==null))}catch{return new Set}}async function NK(e,t){if(t.size===0)return new Set;let n=[...t.entries()];try{let r=await Qt(e,n.map(([,o])=>({target:o,callData:Le({abi:fP,functionName:"pool"})})));return new Set(n.filter(([o],s)=>Ge(r[s])?.toLowerCase()===o.toLowerCase()).map(([o])=>o))}catch{return new Set}}async function OK(e,t,n){let r=parseInt(e,16);if(t.length===0||!Number.isFinite(r))return new Map;let o=await Promise.all(t.map(async s=>{try{let i=await se.post(n,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:r}}),a=i.ok?i.data?.data?.vaultV2ByAddress:null;return a?[s,a.name?.trim()||""]:null}catch{return null}}));return new Map(o.filter(s=>s!==null))}var LK=.01;function DK(e){return e.reduce((t,n)=>n.conditions===null?t+n.apyPercent:t,0)}function UK(e,t){if(typeof t!="string"||!t.trim())return;let n=t.trim(),r=gm();r[e]!==n&&Ma({...r,[e]:n})}var Eu=class{constructor(t,n,r){this.coinPoolBaseUrl=t;this.endpoints=n;this.describer=r}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(t,n,r){let o=Date.now();Te("describeReceiptTokens: START",{chain:t,tokens:n,hasRpcUrl:!!r});let s=Os(t);s&&UK(s,r);let i=s?Om(s):null,a=[...new Set(n.filter(ge).map(p=>p.toLowerCase()))];if(Te("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!i,wanted:a}),!s||!i||a.length===0)return Te("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!i,wantedCount:a.length}),new Map;Te("describeReceiptTokens: on-chain discovery for",a);let l=await kD(s,a,this.endpoints.morphoApiUrl),u=[...new Map(a.flatMap((p,m)=>{let g=l[m];return Te("describeReceiptTokens: discovery result",{token:p,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[p,g]]:[]})).entries()];if(u.length===0)return Te("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;Te("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([p,m])=>({token:p,type:m.type,contract:m.contract}))});let d=await this.describer.describe(s,i,u.map(([,p])=>p));return Te("describeReceiptTokens: DONE",{ms:Date.now()-o,overviews:d.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(d.map((p,m)=>[u[m][0],p]))}async findMarketByReceiptToken(t,n,r){if(Te("findMarketByReceiptToken: called",{chain:t,receiptToken:n,hasRpcUrl:!!r}),!ge(n))return Te("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:n}),null;let s=(await this.describeReceiptTokens(t,[n],r)).get(n.toLowerCase())??null;return Te("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(t){if(!ge(t.address))return[];let n=await wD(this.coinPoolBaseUrl,t.chains);return(await Promise.all(n.map(o=>this.positionsForChain(o,t.address)))).flat().sort((o,s)=>s.suppliedUsdc-o.suppliedUsdc||(s.avgApyPercent??0)-(o.avgApyPercent??0))}async describeResolvedMarkets(t,n){let r=Os(t),o=r?Om(r):null;return r&&o?this.describer.describe(r,o,n):[]}async positionsForChain(t,n){let r=Om(t),o=await Mm(this.coinPoolBaseUrl,t);if(!r||o.length===0)return[];let s=await this.describer.readBalances(t,n,o);if(s.length===0)return[];let i=await this.describer.describe(t,r,s.map(l=>l.market)),a=await this.describer.convertToUnderlying(t,s,i.map(l=>l.asset));return i.flatMap((l,c)=>{let u=a[c];return u<LK?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+DK(l.rewards))/100}]})}};var xP=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Ru=class{constructor(t){this.coinPoolBaseUrl=t}coinPoolBaseUrl;async listChains(){return wy(this.coinPoolBaseUrl)}async isSupported(t){return vy(this.coinPoolBaseUrl,t)}async getMarkets(t){let n=Ce(t);return n?Mm(this.coinPoolBaseUrl,n):[]}async findMarket(t,n){let r=await this.getMarkets(t);return bD(r,n)}canSupply(t){return xP.includes(t.type)}async readReceiptToken(t,n){let r=Bi(n).balanceIsUnderlying;try{let o=await Qt(t,[{target:n.token,callData:Le({abi:Ve,functionName:"symbol"})},{target:n.token,callData:Le({abi:Ve,functionName:"decimals"})}]);return{symbol:Rc(o[0]),decimals:_c(o[1]),isUnderlying:r}}catch{return{symbol:null,decimals:null,isUnderlying:r}}}};var AD=6e5,ky=new Map;async function xD(e){let t=ky.get(e);if(t&&Date.now()-t.at<AD)return t.chains;let n=HK(e);return ky.set(e,{at:Date.now(),chains:n}),n.then(r=>{r===null&&ky.delete(e)}),n}async function BK(e){try{let t=e==="morpho"?await MK():await FK();return!t||t.size===0?(Te(`protocolChains: ${e} returned no chains`),null):(Te(`protocolChains: ${e} live on`,[...t].sort((n,r)=>n-r)),t)}catch(t){return Te(`protocolChains: ${e} FAILED`,t instanceof Error?t.message:t),null}}async function MK(){let e=await se.post("https://api.morpho.org/graphql",{query:"{ chains { id network } }"});if(!e.ok)return null;let t=e.data?.data?.chains;if(!Array.isArray(t))return null;let n=new Set;for(let r of t)typeof r?.id=="number"&&Number.isInteger(r.id)&&r.id>0&&(n.add(r.id),typeof r.network=="string"&&r.network.trim()&&TD.set(r.id,r.network.trim()));return n}async function FK(){let e=await se.get("https://v3-api.compound.finance/market/all-networks/all-contracts/summary");if(!e.ok||!Array.isArray(e.data))return null;let t=new Set;for(let n of e.data)typeof n?.chain_id=="number"&&Number.isInteger(n.chain_id)&&n.chain_id>0&&t.add(n.chain_id);return t}var TD=new Map;function SD(e){return TD.get(e)??null}var qK=1500;async function PD(){let e=Promise.all([xD("morpho").catch(()=>null),xD("compound").catch(()=>null)]),t,n=new Promise(r=>{t=setTimeout(r,qK),t?.unref?.()});try{await Promise.race([e,n])}finally{t&&clearTimeout(t)}}function AP(e){let t=ky.get(e);return!t||Date.now()-t.at>=AD?null:ED.get(t.chains)??null}var ED=new WeakMap;function HK(e){let t=BK(e);return t.then(n=>{n&&ED.set(t,n)}),t}var $K={1:"ethereum",10:"opmainnet",130:"unichain",137:"polygon",143:"monad",480:"world-chain",988:"stable",999:"hyperevm",4217:"tempo",4663:"robinhood-chain",5042:"arc",8453:"base",42161:"arbitrum",747474:"katana"},VK={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},jK={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},WK={1:"mainnet",10:"op",130:"unichain",137:"polygon",2020:"ronin",5e3:"mantle",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function xy(e){let t=rY(e.chain);return(t===null?null:zK(e,t))??Nm(e.type)??nY(e,t)}function zK(e,t){switch(e.type){case"morpho-v2":{let n=$K[t]??YK(t);if(!n||!e.contract)return null;let r=`https://app.morpho.org/${n}/vault/${TP(e.contract)}`,o=QK(e.name);return o?`${r}/${o}`:r}case"aave-v3":{let n=VK[t],r=GK(e);return!n||!r?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${TP(r)}&marketName=${n}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let n=jK[t],r=eY(e);return!n||!r?null:`https://app.spark.finance/savings/${n}/${r}`}case"compound-v3":{if(XK(t))return null;let n=WK[t],r=JK(e);return!n||!r?null:`https://app.compound.finance/?market=${r}-${n}`}default:return null}}function GK(e){let t=e.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(t)?/^0x0+$/.test(t)?null:t:null}var KK=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function YK(e){if(!AP("morpho")?.has(e))return null;let n=SD(e);return n&&n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function QK(e){let t=e?.trim().toLowerCase()||"";return!t||KK.has(t)?null:t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function XK(e){let t=AP("compound");return t!==null&&!t.has(e)}function JK(e){let t=e.asset?.address?.trim().toLowerCase()||"",n=ZK[t];if(n)return n;let r=e.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(r)&&r.length<=12?r:null}var ZK={"0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"usdc.e","0xff970a61a04b1ca14834a43f5de4533ebddb5cc8":"usdc.e"};function eY(e){let t=e.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(t))return t;let n=`${e.name||""} ${e.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(n.includes(o))return o;if(e.type==="spark-ethereum")return tY[e.contract?.trim().toLowerCase()||""]??null;let r=e.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(r)||r.startsWith("s")?null:`s${r}`}var tY={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function nY(e,t){let n=e.protocolUrl?.trim();if(!n)return null;let r=/^https?:\/\//i.test(n)?n:`https://${n.replace(/^\/+/,"")}`;try{let o=new URL(r);return t!==null&&o.searchParams.set("chainId",String(t)),e.contract&&o.searchParams.set("contract",TP(e.contract)),o.toString()}catch{return r}}function TP(e){let t=e.trim().toLowerCase();return t.startsWith("0x")?t:`0x${t}`}function rY(e){let t=e?.trim();if(!t)return null;let n=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(n)&&n>0?n:null}var oY=new Set(["spark","spark-ethereum"]),sY=8;function iY(e,t,n){if(e.market.type!=="spark-l2-susds")return ft(t);let r=ft(t);return r===null||e.tokenDecimals===null?null:za(e.rawBalance,r,e.tokenDecimals,n)}var Ay=class{constructor(t){this.endpoints=t}endpoints;apyLimiter=new SP(sY);pantograph=new Ft;async describe(t,n,r){if(r.length===0)return[];Te("describe: START",{chain:t,count:r.length,types:r.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(t,r);Te("describe: assets resolved",o);let[i,a]=await Promise.all([this.readMarketState(t,r,o),Promise.all(r.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,n,o[c])))),PD()]);return Te("describe: on-chain state",i),Te("describe: APY fetched",a.map((l,c)=>({type:r[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),r.map((l,c)=>{let{totalSuppliedUsdc:u,liveApyFraction:d}=i[c],p=a[c].sizeOverride??u,m=lY(a[c].samples,d??a[c].current,a[c].rewards,a[c].avgOverride??null);return Te("describe: summarised",{market:l.name,type:l.type,liveFrom:d!==null?"on-chain":a[c].current!==null?"api":"none",rawSamples:a[c].samples.length,historyPoints:m.history.length,currentApyPercent:m.currentApyPercent,avgApyPercent:m.avgApyPercent,apyChangePercent:m.apyChangePercent,totalSuppliedUsdc:p,asset:o[c]?.symbol}),{...l,protocolUrl:xy({...l,asset:o[c],shareSymbol:s[c]}),asset:o[c],totalSuppliedUsdc:p,avgApyPercent:m.avgApyPercent,currentApyPercent:m.currentApyPercent,baseApyPercent:m.baseApyPercent,rewardApyPercent:m.rewardApyPercent,rewards:m.rewards,apyChangePercent:m.apyChangePercent,apyHistory:m.history}})}async readBalances(t,n,r){let o=Le({abi:Ve,functionName:"balanceOf",args:[n]}),s=Le({abi:Ve,functionName:"decimals"}),i=r.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),a=await Qt(t,i);return r.flatMap((l,c)=>{let u=ft(a[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:_c(a[c*2+1])}]})}async convertToUnderlying(t,n,r){let o=[],s=n.map(a=>{let l=Bi(a.market).convertToAssetsCall(a.market,a.rawBalance);return l?(o.push(l),o.length-1):-1}),i=await Qt(t,o);return n.map((a,l)=>{let c=r[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return Vr(a.rawBalance,c);let u=iY(a,i[s[l]],c);return u===null?Vr(a.rawBalance,a.tokenDecimals??c):Vr(u,c)})}async resolveAssets(t,n){let r={address:Ga,decimals:NaN,symbol:null,logo:null},o=[],s=n.map(p=>{let m=Bi(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),i;try{let p=o.length>0?await Qt(t,o):[];i=s.map(m=>m<0?null:Ge(p[m]))}catch{i=n.map(()=>null)}i=i.map((p,m)=>p??n[m]?.assetAddress??null);let a=[...new Set(i.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,u]=await Promise.all([this.readAssetMetadata(t,a),this.fetchAssetLogos(t,a),this.readShareSymbols(t,n)]);return{assets:i.map(p=>{if(!p)return r;let m=p.toLowerCase(),g=l.get(m),f=c.get(m)??null;return g?.decimals!==null&&g?.decimals!==void 0?{address:p,decimals:g.decimals,symbol:g.symbol??null,logo:f}:{address:p,decimals:NaN,symbol:null,logo:f}}),shareSymbols:u}}async readShareSymbols(t,n){let r=Le({abi:Ve,functionName:"symbol"}),o=[],s=n.map(i=>!oY.has(i.type)||!i.contract?-1:(o.push({target:i.contract,callData:r}),o.length-1));if(o.length===0)return n.map(()=>null);try{let i=await Qt(t,o);return s.map(a=>a<0?null:Rc(i[a]))}catch{return n.map(()=>null)}}async readAssetMetadata(t,n){let r=new Map;if(n.length===0)return r;let o=Le({abi:Ve,functionName:"decimals"}),s=Le({abi:Ve,functionName:"symbol"});try{let i=await Qt(t,n.flatMap(a=>[{target:a,callData:o},{target:a,callData:s}]));n.forEach((a,l)=>{r.set(a,{decimals:_c(i[l*2]),symbol:Rc(i[l*2+1])})})}catch{}return r}async fetchAssetLogos(t,n){let r=new Map;if(n.length===0)return r;try{let o=await this.pantograph.getTokensMetadata(n,t);for(let[s,i]of Object.entries(o)){let a=i.icon_image||i.logo||i.logoURI;a&&r.set(s.toLowerCase(),a)}}catch{}return Te("resolveAssets: logos",{chain:t,requested:n.length,found:r.size}),r}async readMarketState(t,n,r){let o=[],s=n.map((u,d)=>{let p=Bi(u),m=r[d],g={market:u,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(u,m));let f=p.liveRateCall(u,m);return f&&(g.rate=o.length,o.push(f)),g}),i=await Qt(t,o),a=[],l=s.map(u=>{if(u.rate<0)return-1;let d=u.protocol.followUpRateCall(u.market,i[u.rate]);return d?(a.push(d),a.length-1):-1}),c=a.length>0?await Qt(t,a):[];return s.map((u,d)=>{let p=u.rate<0?null:i[u.rate],m=l[d]>=0?c[l[d]]:p;return{totalSuppliedUsdc:u.protocol.decodeSize(i[u.size],u.asset),liveApyFraction:m===null?null:u.protocol.decodeLiveRate(m)}})}async fetchApy(t,n,r){try{Te("fetchApy: requesting",{market:t.name,type:t.type,asset:r?.symbol});let o=await Bi(t).fetchApy(t,n,this.endpoints,r);return Te("fetchApy: got",{market:t.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return Te("fetchApy: FAILED \u2014 market listed without APY",{market:t.name,type:t.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},SP=class{constructor(t){this.limit=t}limit;active=0;waiting=[];async run(t){this.active>=this.limit?await new Promise(n=>this.waiting.push(n)):this.active++;try{return await t()}finally{let n=this.waiting.shift();n?n():this.active--}}};function aY(e,t){let n=Tm(Date.now()),r=new Map,o=null;for(let a of e)!Number.isFinite(a.timeMs)||!Number.isFinite(a.fraction)||a.fraction<0||Tm(a.timeMs)>n||((!o||a.timeMs>o.timeMs)&&(o=a),r.set(a.timeMs,a.fraction));let s=[...r.entries()].sort((a,l)=>a[0]-l[0]).map(([a,l])=>({date:new Date(a).toISOString(),apyPercent:l*100})),i=t??(o&&Tm(o.timeMs)===n?o.fraction:null);return{history:s,live:i}}function lY(e,t,n=[],r=null){let{history:o,live:s}=aY(e,t),i=s===null?null:s*100,a=n.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=a.length===0?null:a.reduce((m,g)=>m+g.apyPercent,0),c=i===null?null:i+(l??0),u={baseApyPercent:i,rewardApyPercent:l,rewards:a},d=r!==null&&Number.isFinite(r)?r*100:null;if(o.length===0)return{history:o,avgApyPercent:d,currentApyPercent:c,apyChangePercent:null,...u};let p=o.reduce((m,g)=>m+g.apyPercent,0);return{history:o,avgApyPercent:d??p/o.length,currentApyPercent:c,apyChangePercent:uY(o,i),...u}}var RD=3600*1e3,cY=RD/2;function uY(e,t){if(t===null)return null;let n=Date.now()-RD,r=null,o=Number.POSITIVE_INFINITY;for(let s=e.length-1;s>=0;s--){let i=Math.abs(Date.parse(e[s].date)-n);if(i>o)break;o=i,r=e[s]}return!r||o>cY?null:t-r.apyPercent}function _D(e,t){if(!Number.isFinite(e))return e;let n=10**t,r=Number((e*n).toPrecision(15));return(e<0?-Math.floor(-r):Math.floor(r))/n+0}var io=class{read;supply;constructor(t={}){let n=t.coinPoolBaseUrl||"https://api.coinpool.app",r={lendingRatesBaseUrl:t.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:t.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:t.morphoApiUrl||"https://api.morpho.org/graphql"},o=new Ay(r);this.read=new Eu(n,r,o),this.supply=new Ru(n)}async listSupportedChains(){return this.supply.listChains()}async isSupported(t){return this.supply.isSupported(t)}async getMarkets(t){return this.supply.getMarkets(t)}async findMarket(t,n){return this.supply.findMarket(t,n)}canSupply(t){return this.supply.canSupply(t)}async readReceiptToken(t,n){return this.supply.readReceiptToken(t,n)}async describeReceiptTokens(t,n,r){return this.read.describeReceiptTokens(t,n,r)}async findMarketByReceiptToken(t,n,r){return this.read.findMarketByReceiptToken(t,n,r)}async describeResolvedMarkets(t,n){return this.read.describeResolvedMarkets(t,n)}async getMarketOverviews(t){return(await Promise.all(t.chains.map(async r=>this.read.describeResolvedMarkets(r,await this.getMarkets(r))))).flat().sort((r,o)=>(o.avgApyPercent??-1)-(r.avgApyPercent??-1))}async getSupplyPositions(t){return this.read.getSupplyPositions(t)}};var Fm="{market}",ND=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],Sy=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],jr="[[LIST]]",OD=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',LD=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function DD(e,t,n){let[r]=dY([e],t,n),[o]=e.canSupply?PP(e,t,n):[];return{name:e.name?.trim()||e.protocol,protocol:e.protocol,protocolUrl:e.protocolUrl,chain:n,apyPercent:e.apyPercent,detailPrompt:r?.prompt??"",detailLabel:r?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function dY(e,t,n){return UD(e,{labelTemplate:Ty(t.detail_button_label),promptTemplate:Ty(t.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Fm}`,...n===void 0?{}:{chainName:n}})}function PP(e,t,n){return UD([e],{labelTemplate:Ty(t.supply_button_label),promptTemplate:Ty(t.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Fm}`,promptFallback:`supply to ${Fm}`,...n===void 0?{}:{chainName:n},max:1})}function UD(e,t){let n=typeof t.chainName=="string"?t.chainName.trim():"",r=[],o=new Set;for(let s of e){if(t.max!==void 0&&r.length>=t.max)break;let i=s.name?.trim();!i||o.has(i.toLowerCase())||(o.add(i.toLowerCase()),r.push({label:ID(t.labelTemplate,i,t.labelFallback,t.labelNamesMarket===!0),prompt:ID(pY(t.promptTemplate),i,t.promptFallback)+mY(s.contract,n)}))}return r}function pY(e){let[t,n]=[e[0],e[1]];return t===void 0||t===t.toLowerCase()||n!==void 0&&n!==n.toLowerCase()?e:t.toLowerCase()+e.slice(1)}function Ty(e){return typeof e=="string"?e:""}function mY(e,t){let n=e?.trim();if(!n||!/^0x[a-fA-F0-9]{40}$/.test(n))return"";let r=t?.trim();return r?` (market: ${n} - ${r})`:` (market: ${n})`}function ID(e,t,n,r=!0){let s=e&&(!r||e.includes(Fm))?e:n;return hY(s).split(Fm).join(t).replace(/\s+/g," ").trim()}var CD="{chain}";function hY(e){if(!e.includes(CD))return e;let t=CD.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${t}`,"g"),"").replace(new RegExp(`${t}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(t,"g"),"")}var Py=[{id:"aave-v3",label:"Aave v3",types:["aave-v3"],aliases:["aave","aavev3","aave3","ave"]},{id:"compound-v3",label:"Compound v3",types:["compound-v3"],aliases:["compound","compoundv3","compound3","comet","comp"]},{id:"spark-any",label:"Spark",types:["spark","spark-ethereum"],aliases:["spark","sparkfi","sparklend","sparkprotocol"]},{id:"morpho-v2",label:"Morpho",types:["morpho-v2"],aliases:["morpho","morphov2","morpho2","morphoblue","metamorpho"]}],RP=Py.map(e=>e.label),EP={euler:"Euler",venus:"Venus",radiant:"Radiant",benqi:"Benqi",qi:"Benqi",fluid:"Fluid",instadapp:"Fluid",silo:"Silo",moonwell:"Moonwell",sonne:"Sonne",granary:"Granary",ironbank:"Iron Bank",cream:"Cream",maker:"Maker",makerdao:"Maker",sky:"Sky",justlend:"JustLend",kamino:"Kamino",solend:"Solend",marginfi:"marginfi",save:"Save",curve:"Curve",yearn:"Yearn",convex:"Convex",pendle:"Pendle",ethena:"Ethena",gearbox:"Gearbox",notional:"Notional",exactly:"Exactly",seamless:"Seamless",zerolend:"ZeroLend",dforce:"dForce",tectonic:"Tectonic",liqee:"Liqee"};function BD(e){let t=typeof e=="string"?e.trim():"";if(!t)return{kind:"none"};let n=bY(t);if(!n)return{kind:"none"};let r=fY(n);if(r){let s=new Set(r.types);return{kind:"supported",label:r.label,matches:i=>s.has(i.type)}}let o=yY(n);return o?{kind:"unsupported",label:o,requested:t}:{kind:"unknown",requested:t}}function fY(e){let t=Py.filter(n=>n.aliases.includes(e));if(t.length===1)return t[0];if(t.length>1)return null;if(e.length>=3){let n=Py.filter(r=>r.aliases.some(o=>o.includes(e)||e.includes(o)));if(n.length===1)return n[0];if(n.length>1)return null}return gY(e)}function gY(e){let t=null,n=!1;for(let r of Py)for(let o of r.aliases){let s=MD(o);if(s===0||Math.abs(o.length-e.length)>s)continue;let i=FD(e,o,s);i>s||(!t||i<t.distance?(t={spec:r,distance:i},n=!1):i===t.distance&&r!==t.spec&&(n=!0))}return t&&!n?t.spec:null}function MD(e){return e.length<=4?0:e.length<=9?2:3}function yY(e){let t=EP[e];if(t)return t;if(e.length>=4){let o=new Set(Object.entries(EP).filter(([s])=>s.length>=4&&(s.includes(e)||e.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let n=null,r=!1;for(let[o,s]of Object.entries(EP)){let i=MD(o);if(i===0||Math.abs(o.length-e.length)>i)continue;let a=FD(e,o,i);a>i||(!n||a<n.distance?(n={label:s,distance:a},r=!1):a===n.distance&&s!==n.label&&(r=!0))}return n&&!r?n.label:null}function bY(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function FD(e,t,n){if(e===t)return 0;if(!e.length)return t.length;if(!t.length)return e.length;let r=new Array(t.length+1),o=Array.from({length:t.length+1},(i,a)=>a),s=new Array(t.length+1);for(let i=1;i<=e.length;i++){s[0]=i;let a=s[0];for(let c=1;c<=t.length;c++){let u=o[c-1]+(e[i-1]===t[c-1]?0:1),d=Math.min(s[c-1]+1,o[c]+1,u);i>1&&c>1&&e[i-1]===t[c-2]&&e[i-2]===t[c-1]&&(d=Math.min(d,r[c-2]+1)),s[c]=d,d<a&&(a=d)}if(a>n)return n+1;let l=r;r=o,o=s,s=l}return o[t.length]}function qt(e,t){return e==null?null:_D(e,t)}var Bn=2,Mi=2;function Ey(e){let t=qt(e.currentApyPercent,Bn),n=e.rewards.map(s=>({apyPercent:qt(s.apyPercent,Bn)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),r=e.rewardApyPercent===null?null:n.reduce((s,i)=>s+Math.round(i.apyPercent*100),0)/100;if(r===null||t===null)return{currentApyPercent:t,rewardApyPercent:r,rewards:n,baseApyPercent:qt(e.baseApyPercent,Bn)};let o=Math.round(t*100)-Math.round(r*100);return{currentApyPercent:t,rewardApyPercent:r,rewards:n,baseApyPercent:o/100}}var wY=["apy","score","size"],qD=3,HD=40,_u=class extends K{name="get-lending-markets";kind="ui";description='BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${RP.join(", ")}. Set it whenever the user names a protocol \u2014 "supply aave", "morpho vaults", "l\xE3i su\u1EA5t b\xEAn Compound" \u2014 and pass what they wrote, VERBATIM. Do NOT correct their spelling, do NOT translate it, and do NOT map it to a name from the supported list yourself: misspellings are resolved for you, and a protocol that is NOT supported is reported back so you can tell the user. Pass it even when you believe the protocol is unsupported \u2014 that is how the user gets told. OMIT it when the user named no protocol; never guess one to narrow a list they asked for in full.`,required:!1},{name:"limit",type:"number",description:`How many markets to return, 1-${HD}. Default ${qD} \u2014 the top markets by the chosen ranking, which answers "where can I earn on my USDC" on its own. Raise it ONLY when the user asks for more than that, for the full list, or to compare broadly; lower it when they want a shorter shortlist.`,required:!1},{name:"sort",type:"string",description:'Ranking: "apy" (default, highest live protocol APY first), "score" (safest / best-rated first \u2014 use when the user asks for safe, reliable or trusted markets), or "size" (largest market first \u2014 use when the user asks for the biggest or most liquid markets).',required:!1},...ND,...Sy];service;constructor(t){super(),this.service=new io(t)}async run(t,n){let r=at(t.chain,void 0),o=r?null:Ce(n?.chain),s=r??o,i=s?await this.service.isSupported(s):!1,a=i?[]:await this.service.listSupportedChains();if(s&&!i)return{_instructions:`There are no lending markets on ${j(s)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:j(s),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:a.map(v=>j(v))};let l=BD(t.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:a,u=kY(t.sort),d=xY(t.limit),p=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?p.filter(v=>l.matches(v)):p;if(l.kind==="supported"&&m.length===0&&p.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?j(s):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?j(s):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(p.map(v=>v.protocol))]};let g=[...m].sort(vY[u]).slice(0,d),f=g.map(v=>DD({name:v.name,contract:v.contract,protocol:v.protocol,protocolUrl:v.protocolUrl,apyPercent:qt(v.currentApyPercent,Bn),canSupply:this.service.supply.canSupply(v)},t,j(v.chain))),w={component:"LendingMarketList",props:{chain:s?j(s):"all",multiChain:new Set(f.map(v=>v.chain)).size>1,markets:f}};return{...f.length>0?{ui:w}:{},_instructions:this.instructions(g,u,f.length>0,l.kind==="supported"?l.label:null),chain:s?j(s):"all",chainsQueried:c.map(v=>j(v)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:u,marketCount:f.length,totalMarketsAvailable:m.length,marketNames:f.map(v=>v.name)}}unsupportedProtocol(t){let n=t.kind==="unsupported",r=n?t.label:`"${t.requested}"`;return{_instructions:`The user asked about ${r}, which has no lending markets here. In their language: tell them plainly that ${r} is ${n?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${r} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:n?t.label:t.requested,protocolSupported:!1,supportedProtocols:[...RP],marketCount:0,marketNames:[]}}instructions(t,n,r=!1,o=null){if(t.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let s={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[n];return[o?`These are the ${o} lending markets the user can supply to, ${s}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,`Write your reply in TWO parts separated by a line containing exactly ${jr} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",n==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(t.map(i=>i.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${j(t[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${s} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",r?OD:""].filter(Boolean).join(" ")}},vY={apy:(e,t)=>(t.currentApyPercent??-1)-(e.currentApyPercent??-1),score:(e,t)=>(t.platformScore??-1)-(e.platformScore??-1),size:(e,t)=>(t.totalSuppliedUsdc??-1)-(e.totalSuppliedUsdc??-1)};function kY(e){let t=typeof e=="string"?e.trim().toLowerCase():"";return wY.includes(t)?t:"apy"}function xY(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?qD:Math.min(Math.floor(t),HD)}function $D(e){let{currentApyPercent:t,avgApyPercent:n,totalSuppliedUsdc:r,rewardApyPercent:o,baseApyPercent:s,platformScore:i}=e;return e.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:o!==null&&s!==null&&o>s*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:t!==null&&n!==null&&n>0&&t>n*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:r!==null&&r<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:i!==null&&i<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:i!==null&&i>=8.5&&r!==null&&r>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:r!==null&&r>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}function Ry(e){let t=typeof e=="string"?e.trim():"",n=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(t);if(n)return n[1];let r=/0x[a-fA-F0-9]{40}/.exec(t);return r&&r[0]!==t?r[0]:t}var Iu=class extends K{name="get-lending-market-detail";category="blockchain-data";description='Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...Sy];service;constructor(t){super(),this.service=new io(t)}async run(t,n){let o=at(t.chain,void 0)??Ce(n?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let d=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:j(o),chainsWithLendingMarkets:d.map(p=>j(p)),_instructions:`There are no lending markets on ${j(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=Ry(t.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let i=await this.service.findMarket(o,s);if(i.length===0)return{error:"market_not_found",market:s,chain:j(o),_instructions:`No lending market matching "${s}" exists on ${j(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(i.length>1)return{error:"ambiguous_market",market:s,chain:j(o),candidates:i.map(d=>({marketName:d.name,protocol:d.protocol})),_instructions:`"${s}" matches ${i.length} different markets on ${j(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${j(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let a=i[0],l=await this.describeOne(o,a);if(!l)return{error:"market_unavailable",marketName:a.name,chain:j(o),_instructions:`${a.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let c=this.service.supply.canSupply(a),u=c?PP({name:a.name,contract:a.contract},t,j(o)):[];return{_instructions:this.instructions(l,u.length>0,c),...u.length>0?{actionButtons:u}:{},marketName:l.name,protocol:l.protocolLabel??l.protocol,protocolUrl:l.protocolUrl,chain:j(l.chain),suppliedAssetSymbol:l.asset.symbol,totalSuppliedUsdc:qt(l.totalSuppliedUsdc,Mi),...Ey(l),avgApyPercent:qt(l.avgApyPercent,Bn),apyChangePercent:qt(l.apyChangePercent,Bn),platformScore:l.platformScore,supplySupported:c}}async describeOne(t,n){try{let[r]=await this.service.describeResolvedMarkets(t,[n]);return r??null}catch{return null}}instructions(t,n,r){let o=$D(t);return[`This is the full picture of ONE lending market, ${t.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',r?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",n?LD:""].filter(Boolean).join(" ")}};var Cu=class extends K{name="get-wallet-lending-positions";description='Get a wallet\'s own LENDING / SUPPLY (earn, deposit, savings) positions in the curated lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much it has supplied there, the AVERAGE supply APY over the last week (plus the live rate and the day-over-day change), the estimated yearly yield on that balance, and the market total supplied. Balances are read on-chain, so they match the app. Use for questions like: "Which protocols am I supplying on?", "Show my lending positions", "How much am I earning on my USDC?", "What APY am I getting?", "Where is my USDC deposited?", "My Aave / Compound / Spark / Morpho supply", "what am I earning on Aave", "my savings positions". This is the PREFERRED tool for any "what am I earning / supplying / depositing" question, even when the user names a protocol ("my Aave v3 supply", "my Spark deposit") \u2014 it is the only source of the 7-day average APY, the estimated yearly yield and the platform safety score. Each position reports its OWN asset, which is usually USDC but need not be \u2014 never assume the amounts are dollars without checking `suppliedAssetSymbol`. Chains and markets come from the live catalogue, so do not rule a chain out from memory: call the tool and let it answer. For protocols outside Aave v3 / Compound v3 / Spark / Morpho (Aave v2, MakerDAO\u2026), or when this tool reports nothing but the user insists they have a deposit, fall back to get-wallet-defi-positions. Do NOT use for: markets the wallet has NOT supplied to yet \u2014 where to deposit, best available APY, "promising lending" \u2192 get-lending-markets; the BORROW side of these same protocols, plus LP / staking \u2192 get-wallet-defi-positions (or get-wallet-defi-protocol-positions for one named protocol); plain token balances \u2192 get-wallet-token-balances.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:`Hex chain ID to scope to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry lending markets is resolved at call time, so do NOT filter the request against a list you remember. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 positions are then read on the connected wallet's own chain.`,required:!1}];service;constructor(t){super(),this.service=new io(t)}async run(t,n){let r=gt(t.address,n);if(!ge(r))return{error:`"${r}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=at(t.chain,n),s=o?await this.service.isSupported(o):!1,i=s?[]:await this.service.listSupportedChains();if(o&&!s)return{_instructions:`There are no lending markets on ${j(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:r,chain:j(o),positionCount:0,positions:[],chainsWithLendingMarkets:i.map(c=>j(c))};let a=o?[o]:i,l=await this.service.getSupplyPositions({address:r,chains:a});return{_instructions:this.instructions(l),walletAddress:r,chain:o?j(o):"all",chainsQueried:a.map(c=>j(c)),positionCount:l.length,totals:AY(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:j(c.chain),suppliedUsdc:qt(c.suppliedUsdc,Mi),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:qt(c.avgApyPercent,Bn),...Ey(c),apyChangePercent:qt(c.apyChangePercent,Bn),estimatedAnnualYieldUsdc:qt(c.estimatedAnnualYieldUsdc,Mi),marketTotalSuppliedUsdc:qt(c.totalSuppliedUsdc,Mi),apyHistory:c.apyHistory.map(u=>({...u,apyPercent:qt(u.apyPercent,Bn)})),platformScore:c.platformScore}))}}instructions(t){return t.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(t.map(r=>r.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function AY(e){if(new Set(e.map(i=>i.asset.symbol??i.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let r=e.reduce((i,a)=>i+a.suppliedUsdc,0),o=e.filter(i=>i.avgApyPercent!==null),s=o.reduce((i,a)=>i+a.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:e[0]?.asset.symbol??null,suppliedUsdc:qt(r,Mi),estimatedAnnualYieldUsdc:qt(e.reduce((i,a)=>i+(a.estimatedAnnualYieldUsdc??0),0),Mi),weightedAvgApyPercent:qt(s>0?o.reduce((i,a)=>i+a.suppliedUsdc*a.avgApyPercent,0)/s:null,Bn)}}var Nu=class extends K{name="open-supply-usdc-form";kind="ui";category="lending-action";description='Open the SUPPLY form so the user can DEPOSIT into a specific lending market and start earning yield. This is the tool for a supply COMMAND: the user names a market and tells you to act on it, in any wording and any language \u2014 "supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare "Supply Aave", or a tapped "Supply \u2026" button. A supply verb plus a market name is already a complete command; terseness is not ambiguity, and the words the user left out are supplied by context rather than looked up. Each market deposits its OWN asset (usually USDC), resolved from the market itself \u2014 so a message that names no asset is still this tool: resolve the market from whatever the user did name. An amount is optional. Pass `market` \u2014 the market name or protocol exactly as it was shown to them (e.g. "Aave v3 USDC", "Spark"), and `amount` ONLY when they named one. Supports Aave v3, Compound v3, Spark and Morpho vaults, on whichever chains currently carry them \u2014 that set is resolved at call time, so never refuse a chain from memory. PRECONDITION: a connected wallet. The boundary is command vs question: use this to ACT on one market; to LIST or compare markets \u2192 get-lending-markets; for what the wallet already supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}];service;moralis;constructor(t){super(),this.service=new io(t),this.moralis=new De(t?.moralis)}async run(t,n){let r=n?.walletAddress;if(!r)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let s=at(t.chain,void 0)??Ce(n?.chain);if(!s)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};if(!await this.service.isSupported(s)){let w=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:j(s),chainsWithLendingMarkets:w.map(v=>j(v)),_instructions:`There are no lending markets on ${j(s)}, so nothing can be supplied there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let i=Ry(t.market);if(!i)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let a=await this.service.findMarket(s,i);if(a.length===0)return{error:"market_not_found",market:i,chain:j(s),_instructions:`No lending market matching "${i}" exists on ${j(s)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(a.length>1)return{error:"ambiguous_market",market:i,chain:j(s),candidates:a.map(w=>({marketName:w.name,protocol:w.protocol})),_instructions:`"${i}" matches ${a.length} different markets on ${j(s)}, so the supply cannot target one yet. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+i+`" and chain for ${j(s)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let l=a[0];if(!this.service.supply.canSupply(l))return{error:"unsupported_protocol",marketName:l.name,protocol:l.protocol,_instructions:`Supplying to ${l.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let c=await this.describeOne(s,l),u=TY(c);if(!u)return{error:"asset_unresolved",marketName:l.name,chain:j(s),_instructions:`The asset ${l.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[d,p]=await Promise.all([this.assetBalance(r,s,u.address),this.service.readReceiptToken(s,l)]);if(d&&Ci(d.amount,"0")<=0)return{error:"no_asset_balance",marketName:l.name,chain:j(s),assetSymbol:u.symbol,assetBalance:"0",_instructions:`The user has no ${u.symbol} available to supply to ${l.name} on ${j(s)}. In the user's language, tell them plainly that they have no ${u.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let m=SY(t.amount),g=m?gr(m,u.decimals):null;if(g&&d&&Ci(g,d.amount)>0)return{error:"insufficient_asset_balance",marketName:l.name,chain:j(s),assetSymbol:u.symbol,requestedAmount:m,assetBalance:d.amount,_instructions:`The user wants to supply ${m} ${u.symbol} to ${l.name}, but they only hold ${d.amount} ${u.symbol} on ${j(s)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${m} ${u.symbol} exceeds their balance of ${d.amount} ${u.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let f={action:"supply_usdc",chainId:s,chainName:j(s),walletAddress:r,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??xy(l),contract:l.contract,token:l.token,apyPercent:c?.currentApyPercent??c?.avgApyPercent??null,receiptToken:p},asset:u,...g?{prefillAmount:g}:{},...d?{spendable:d.amount}:{},...d?.usd?{spendableUsd:d.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:f},marketName:l.name,protocol:l.protocol,chain:j(s),apyPercent:qt(f.market.apyPercent,Bn),assetSymbol:u.symbol,assetBalance:d?.amount??null,_instructions:this.instructions(l,u.symbol)}}async describeOne(t,n){try{let[r]=await this.service.describeResolvedMarkets(t,[n]);return r??null}catch{return null}}async assetBalance(t,n,r){try{let o=await this.moralis.getWalletTokenBalances({address:t,chain:n,tokenAddresses:[r]});if(!o.success)return null;let s=(o.data?.result??[]).find(a=>(a.token_address||"").toLowerCase()===r.toLowerCase());if(!s?.balance_formatted)return{amount:"0",usd:null};let i=typeof s.usd_value=="number"?String(s.usd_value):null;return{amount:String(s.balance_formatted),usd:i}}catch{return null}}instructions(t,n){return[`The supply action for ${t.name} is ready.`,`In the user's language, invite them to enter the amount of ${n} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${n}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function TY(e){let t=e?.asset;return!t?.address||t.address===Ga||!Number.isFinite(t.decimals)?null:{address:t.address,symbol:t.symbol||"the market asset",decimals:t.decimals}}function SY(e){let t=typeof e=="string"?e.trim():typeof e=="number"?String(e):"";return/^\d*\.?\d+$/.test(t)&&Number(t)>0?t:null}var Fi={GAMMA:"https://gamma-api.polymarket.com",DATA:"https://data-api.polymarket.com",BRIDGE:"https://bridge.polymarket.com",CLOB:"https://clob.polymarket.com",RELAYER:"https://relayer-v2.polymarket.com"},_y="/submit",Iy={INTERVAL_MS:3e3,TIMEOUT_MS:9e4},IP="0xebd1cc31700311ef8259fc9337f7a04317bfee851a71bf628420669d75124374",PY=/^0x[0-9a-fA-F]{64}$/,_P=IP;function CP(e){let t=e?.trim();if(!t){_P=IP;return}if(!PY.test(t))throw new Error(`Invalid Polymarket builder code: ${t}`);_P=t.toLowerCase()}function Ou(){return _P}var EY=1e4,RY="https://intercom.help/funxyz/en/articles/10732578-contact-us",NP="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",qi="https://polymarket.com",OP="wss://ws-live-data.polymarket.com",Hi="0x89",qm="137",LP="0xDCa4af75705dbB50f62437045afF9921947917d2",DP="Trading setup approvals",on={DEPLOY:"deploy",ENABLE_TRADING:"enable_trading",APPROVE:"approve",DONE:"done"},Cy={INTERVAL_MS:2e3,MAX_ATTEMPTS:30},Hm=["USDC","USDC.E","USDT","USD\u20AE0","USDT0","DAI","USDE","AUSD","USDG"],Ya={"1151111081099710":"svm",8253038:"btc",728126428:"tron",29780:null},Ls="0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB",zo=6,Wr={depositWalletFactory:"0x00000000000Fb5C9ADea0298D729A0CB3823Cc07",depositWalletImplementation:"0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB",safeFactory:"0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b",safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf",factoryBeaconSelector:"0x49493a4d"},Ds={PREFIX:BigInt("0x61003d3d8160233d3973"),CONST1:"0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",CONST2:"0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",BEACON_PREFIX:BigInt("0x6100523d8160233d3973"),BEACON_CONST1:"0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",BEACON_CONST2:"0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",BEACON_CONST3:"0x60195155f3363d3d373d3d363d602036600436635c60da"},$i=[{key:"politics",tagId:"2",label:"Politics",aliases:["politic","chinh tri","ch\xEDnh tr\u1ECB","\u653F\u6CBB","\uC815\uCE58"]},{key:"sports",tagId:"1",label:"Sports",aliases:["sport","the thao","th\u1EC3 thao","\u30B9\u30DD\u30FC\u30C4","\u4F53\u80B2","\uC2A4\uD3EC\uCE20"]},{key:"crypto",tagId:"21",label:"Crypto",aliases:["cryptocurrency","tien dien tu","ti\u1EC1n \u0111i\u1EC7n t\u1EED","tien ma hoa","ti\u1EC1n m\xE3 h\xF3a","\u6697\u53F7\u8CC7\u7523","\u52A0\u5BC6\u8D27\u5E01","\uC554\uD638\uD654\uD3D0"]},{key:"esports",tagId:"64",label:"Esports",aliases:["e-sports","the thao dien tu","th\u1EC3 thao \u0111i\u1EC7n t\u1EED","e\u30B9\u30DD\u30FC\u30C4","\u7535\u7ADE"]},{key:"iran",tagId:"78",label:"Iran",aliases:["\u30A4\u30E9\u30F3","\u4F0A\u6717","\uC774\uB780"]},{key:"finance",tagId:"120",label:"Finance",aliases:["tai chinh","t\xE0i ch\xEDnh","\u91D1\u878D","\uAE08\uC735"]},{key:"geopolitics",tagId:"100265",label:"Geopolitics",aliases:["dia chinh tri","\u0111\u1ECBa ch\xEDnh tr\u1ECB","\u5730\u653F\u5B66","\u5730\u7F18\u653F\u6CBB"]},{key:"tech",tagId:"1401",label:"Tech",aliases:["technology","cong nghe","c\xF4ng ngh\u1EC7","\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC","\u79D1\u6280","\uAE30\uC220"]},{key:"elections",tagId:"144",label:"Elections",aliases:["election","bau cu","b\u1EA7u c\u1EED","\u9078\u6319","\u9009\u4E3E","\uC120\uAC70"]},{key:"culture",tagId:"596",label:"Culture",aliases:["pop culture","pop-culture","entertainment","van hoa","v\u0103n h\xF3a","giai tri","gi\u1EA3i tr\xED","\u30A8\u30F3\u30BF\u30E1","\u5A31\u4E50"]},{key:"economy",tagId:"100328",label:"Economy",aliases:["economics","kinh te","kinh t\u1EBF","\u7D4C\u6E08","\u7ECF\u6D4E","\uACBD\uC81C"]},{key:"weather",tagId:"84",label:"Weather",aliases:["climate","thoi tiet","th\u1EDDi ti\u1EBFt","\u5929\u6C17","\u5929\u6C14"]},{key:"science",tagId:"74",label:"Science",aliases:["khoa hoc","khoa h\u1ECDc","\u79D1\u5B66","\uACFC\uD559"]},{key:"awards",tagId:"18",label:"Awards",aliases:["giai thuong","gi\u1EA3i th\u01B0\u1EDFng","\u8CDE","\u5956\u9879"]}],$m={trending:{order:"volume24hr",ascending:!1},new:{order:"startDate",ascending:!1},volume:{order:"volume",ascending:!1},liquidity:{order:"liquidity",ascending:!1},competitive:{order:"competitive",ascending:!1},ending_soon:{order:"endDate",ascending:!0}},UP="102127",BP="100639",MP="102169",FP=["TRADE","REDEEM","SPLIT","MERGE","CONVERSION","REWARD"],qP=.01,Vm={MIN_BUY_USD:1,DEFAULT_SLIPPAGE:.05,SLIPPAGE_OPTIONS:[.02,.05,.1]},Ny={POLL_MS:1e3,TIMEOUT_MS:2e4},gn={STABLE_SYMBOLS:["USDC","USDT","USDT0","USD\u20AE0"],CHAIN_ORDER:["137","8453","42161","1","10","56"],LARGE_USD:5e4,ERROR:{INVALID_AMOUNT:"invalid_amount",BELOW_MINIMUM:"below_minimum",INSUFFICIENT_BALANCE:"insufficient_balance",CANCELLED:"cancelled",FAILED:"failed"}},Qa={POSITIONS_READ_LIMIT:500,ERROR:{NOTHING_TO_CLAIM:"nothing_to_claim",CANCELLED:"cancelled",FAILED:"failed"}},Us={ENTER_AMOUNT:"enter_amount",NO_LIQUIDITY:"no_liquidity",NOT_ENOUGH_LIQUIDITY:"not_enough_liquidity",BELOW_MINIMUM:"below_minimum",EXCEEDS_HOLDING:"exceeds_holding",TOO_SMALL:"too_small"},bt={REGION_RESTRICTED:"region_restricted",MARKET_CLOSED:"market_closed",NOT_FILLED:"not_filled",INSUFFICIENT_BALANCE:"insufficient_balance",NOT_ENOUGH_LIQUIDITY:"not_enough_liquidity",TRADING_PAUSED:"trading_paused",BELOW_MIN_SIZE:"below_min_size",CLOSE_ONLY:"close_only",ACCOUNT_BANNED:"account_banned",CANCELLED:"cancelled",FAILED:"failed"},jm={THROTTLE_MS:1e3,STALE_MS:3e4,FALLBACK_POLL_MS:5e3};function WD(e){return`btc-updown-5m-${Math.floor(e/1e3/300)*300}`}var _Y=e=>/^btc-updown-(5m|15m)-/.test((e.slug??"").toLowerCase()),ao={MAX:8,INDEX:2,PREGAME_MINUTES:720,VOLUME_FLOOR:15e4,MAX_PER_SERIES:2,GAME_MINUTES:180,PAIR_VOLUME:3e5,PROXIMITY_WEIGHT:10},zD={nfl:2160,cbb:1440,cwbb:1440},IY={cwbb:1e5,"world-cup":25e3,wimbledon:25e3},CY={cwbb:3,"world-cup":6,wimbledon:4},NY={nba:150,wnba:120,ufc:60,f1:120,cs2:90,"dota-2":90,"league-of-legends":60,valorant:60},OY="world-cup";function HP(e){if(!e)return null;let t=e.trim().replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),n=Date.parse(t);return Number.isFinite(n)?n:null}function LY(e){return(e.seriesSlug||e.series?.[0]?.slug||(e.slug??"").split("-")[0]||"").toLowerCase().replace(/-\d{4}(-\d{2,4})?$/,"")}var DY=e=>(e.tags??[]).some(t=>["1","64"].includes(String(t?.id))||t?.slug==="sports"||t?.slug==="esports");function UY(e){let t=(e.markets??[]).find(n=>n.gameStartTime)?.gameStartTime;return HP(e.startTime)??HP(t)??HP(e.startDate)}var BY=e=>{let t=Number(e.volume);return Number.isFinite(t)?t:0},VD=e=>e.closed!==!0;function MY(e,t){if(e.parentEventId!=null||e.closed===!0||e.ended===!0||!DY(e))return null;let n=LY(e);if(!n)return null;let r=UY(e);if(r===null)return null;let o=BY(e);if(o<(IY[n]??ao.VOLUME_FLOOR))return null;let s=(r-t)/6e4,i=NY[n]??ao.GAME_MINUTES,a=e.live===!0&&-s<=i+15+180+10;if(!a&&s<-30)return null;let l=zD[n]??ao.PREGAME_MINUTES;return!a&&!(s>=-5&&s<=l)?null:{row:e,league:n,volume:o,minutes:s,live:a}}function FY(e){let t=new Map;for(let r of e)t.set(r.league,[...t.get(r.league)??[],r]);let n=[];for(let[r,o]of t){let s=[...o].sort((u,d)=>d.volume-u.volume),i=CY[r]??ao.MAX_PER_SERIES,a=r===OY,l=a?Math.min(s.length,i):1;if(!a&&s.length>=2){let[u,d]=s,p=u.volume>=ao.PAIR_VOLUME&&d.volume>=ao.PAIR_VOLUME,m=[u,d].filter(g=>g.live||g.minutes<=60).length>=2;(p||m)&&(l=Math.min(s.length,i))}let c=zD[r]??ao.PREGAME_MINUTES;for(let u of s.slice(0,l)){let d=Math.log1p(u.volume),p=Math.max(0,Math.min(1,(c-Math.max(0,u.minutes))/c));n.push({...u,worldCup:a,score:u.live?d:d+ao.PROXIMITY_WEIGHT*p})}}return n.sort((r,o)=>{if(r.worldCup!==o.worldCup)return r.worldCup?-1:1;let s=r.minutes<0,i=o.minutes<0;return s!==i?s?-1:1:o.score-r.score}).slice(0,ao.MAX).map(r=>r.row)}function jD(e){let t=new Set;return e.filter(n=>{let r=String(n.id??"");return!r||t.has(r)?!1:(t.add(r),!0)})}function GD(e,t){let n=e.btc5m&&VD(e.btc5m)?e.btc5m:null,r=d=>jD(d.filter(p=>VD(p)&&!_Y(p))),o=r(e.feed),s=r(e.featured);if(s.length>0){let d=new Set(s.map(m=>String(m.id))),p=new Set(s.map(m=>(m.series?.[0]?.slug??"").toLowerCase()).filter(Boolean));o=[...s,...o.filter(m=>!d.has(String(m.id))&&!p.has((m.series?.[0]?.slug??"").toLowerCase()))]}let i=o.slice(0,ao.INDEX),a=o.slice(ao.INDEX),l=new Set(i.map(d=>String(d.id))),c=jD([...a,...r(e.sports)]).filter(d=>!l.has(String(d.id))).map(d=>MY(d,t)).filter(d=>d!==null),u=FY(c);if(u.length>0){let d=new Set(u.map(p=>String(p.id)));o=[...i,...u,...a.filter(p=>!d.has(String(p.id)))]}return n&&(o=[...o.slice(0,1),n,...o.slice(1)]),o}var qY=/^([a-z0-9]+)-updown-(5m|15m|4h)-(\d+)$/,HY={"5m":300,"15m":900,"4h":14400},$Y={"5m":"fiveminute","15m":"fifteen","4h":"fourhour"},KD=e=>new Date(e*1e3).toISOString().replace(".000Z","Z");function Dy(e,t){let n=qY.exec((e??"").toLowerCase());if(!n)return null;let[,r,o,s]=n,i=Number(s),a=t?.cryptoMarketConfig;return{symbol:r.toUpperCase(),priceFeed:`${r}/usd`,duration:o,startTime:t?.eventStartTime||KD(i),endTime:t?.endDate||KD(i+HY[o]),twapSeconds:a?.twapEnabled===!0?Math.max(0,Number(a.twapLookbackSeconds)||0):0}}function XD(e){return{symbol:e.symbol,eventStartTime:e.startTime,variant:$Y[e.duration]??"hourly",endDate:e.endTime,...e.twapSeconds>0?{twapEnabled:"true",twapLookbackSeconds:String(e.twapSeconds)}:{}}}var VY="crypto_prices_chainlink",jY=15e3,WY=1e4,YD=[1e3,2e3,5e3,1e4],Bs=new Map,$P=new Map,Ms=null,Oy=null,Lu=null,Ly=null,VP=0,jP=(e,t)=>JSON.stringify({action:e,subscriptions:t.map(n=>({topic:VY,type:"*",filters:JSON.stringify({symbol:n})}))});function zY(e,t){let n=$P.get(e);n&&n.timestamp>t.timestamp||($P.set(e,t),Bs.get(e)?.forEach(r=>r(t)))}function GY(e){if(typeof e!="string"||!e.startsWith("{"))return;let t;try{t=JSON.parse(e)}catch{return}let n=t.payload??{},r=typeof n.symbol=="string"?n.symbol.toLowerCase():"";if(!r)return;let o=Array.isArray(n.data)?n.data:[n],s=o[o.length-1],i=Number(s?.value),a=Number(s?.timestamp);Number.isFinite(i)&&i>0&&zY(r,{value:i,timestamp:Number.isFinite(a)?a:Date.now()})}function KY(){Oy&&clearInterval(Oy),Lu&&clearTimeout(Lu),Ly&&clearTimeout(Ly),Oy=Lu=Ly=null}function JD(){KY();let e=Ms;if(Ms=null,e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.close()}catch{}}}function QD(){Lu&&clearTimeout(Lu),Lu=setTimeout(WP,jY)}function WP(){if(JD(),Bs.size===0)return;let e=YD[Math.min(VP,YD.length-1)];VP+=1,Ly=setTimeout(ZD,e)}function ZD(){if(Ms||Bs.size===0)return;let e=globalThis.WebSocket;if(!e)return;let t=new e(OP);Ms=t,t.onopen=()=>{t.send(jP("subscribe",[...Bs.keys()])),Oy=setInterval(()=>t.readyState===1&&t.send("ping"),WY),QD()},t.onmessage=n=>{VP=0,QD(),GY(n.data)},t.onclose=WP,t.onerror=WP}function eU(e,t){let n=e.toLowerCase(),r=Bs.get(n)??new Set,o=r.size===0;r.add(t),Bs.set(n,r);let s=$P.get(n);return s&&t(s),Ms?o&&Ms.readyState===1&&Ms.send(jP("subscribe",[n])):ZD(),()=>{let i=Bs.get(n);!i?.delete(t)||i.size>0||(Bs.delete(n),Bs.size===0?JD():Ms?.readyState===1&&Ms.send(jP("unsubscribe",[n])))}}var YY=.1;function Oe(e,t){if(e==null||e==="")return t;let n=typeof e=="number"?e:Number.parseFloat(String(e));return Number.isFinite(n)?n:t}function Uy(e){if(Array.isArray(e))return e;if(typeof e!="string"||e==="")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Wm(e){let t=String(e.version??"").trim().toLowerCase();return t===""||t==="v1"?"v1":t==="v2"?"v2":null}function zm(e){let t=e.feeSchedule??null,n=e.feesEnabled===!0?Oe(t?.rate,0):0,r=Oe(t?.exponent,1);return{rate:n>0&&n<1?n:0,exponent:r>0?r:1}}function Gm(e){return e.active!==!1&&e.archived!==!0&&e.closed!==!0&&e.acceptingOrders===!0&&e.enableOrderBook!==!1}function tU(e,t){return Uy(t==="v2"?e.positionIds:e.clobTokenIds).map(n=>String(n??"")).filter(Boolean)}function nU(e,t){let n=Uy(e.outcomes).map(o=>String(o)),r=tU(e,t);return n.length>=2&&r.length===n.length?n.map((o,s)=>({label:o,tokenId:r[s]})):[]}function zP(e){let t=Uy(e.outcomes).map(c=>String(c)),n=Uy(e.outcomePrices).map(c=>Oe(c,null)),r=Wm(e);if(r===null)return null;let o=tU(e,r);if(t.length<2||n.length!==t.length||o.length!==t.length||n.some(c=>c===null||c<0||c>1)||!e.id||!e.conditionId)return null;let s=(e.question??"").trim(),i=Oe(e.bestBid,null),a=Oe(e.bestAsk,null),l=Oe(e.lastTradePrice,null);return{id:String(e.id),slug:e.slug??"",conditionId:e.conditionId,question:s,label:(e.groupItemTitle??"").trim()||s,outcomes:t.map((c,u)=>({label:c,chance:n[u]})),clobTokenIds:o,protocol:r,volume:Oe(e.volumeNum??e.volume,0),volume24h:Oe(e.volume24hr,0),liquidity:Oe(e.liquidityNum??e.liquidity,0),endDate:e.endDate??null,open:Gm(e),fee:zm(e),priced:i!==null&&a!==null&&a-i<=YY+1e-9||l!==null&&l>0,negRisk:e.negRisk===!0,sportsMarketType:e.sportsMarketType??null,bestBid:i,bestAsk:a,oneDayPriceChange:Oe(e.oneDayPriceChange,null),groupItemThreshold:Oe(e.groupItemThreshold,null)}}function QY(e){let t=String(e.abbreviation??"").trim(),n=/^[a-z]{2,}\d+$/i.test(t)?t.replace(/\d+$/,""):t;return n?n.toUpperCase():null}function XY(e,t){if(e.sportsMarketType!=="moneyline"||t.length===0)return e;let n=new Map(t.map(r=>[lt(String(r.name??"")),QY(r)]));return{...e,outcomes:e.outcomes.map(r=>{let o=n.get(lt(r.label));return o?{...r,shortLabel:o}:r})}}function GP(e){return`${qi}/event/${e}`}function By(e){if(!e.id||!e.slug)return null;let t=e.negRisk===!0,n=Array.isArray(e.teams)?e.teams:[],r=(e.markets??[]).map(zP).filter(o=>o!==null).map(o=>XY({...o,negRisk:o.negRisk||t},n));return t?r.sort((o,s)=>s.outcomes[0].chance-o.outcomes[0].chance):r.every(o=>o.groupItemThreshold!==null)&&r.sort((o,s)=>(o.groupItemThreshold??0)-(s.groupItemThreshold??0)),{id:String(e.id),slug:e.slug,title:(e.title??"").trim(),description:(e.description??"").trim(),resolutionSource:(e.resolutionSource??"").trim(),image:e.image||e.icon||null,url:GP(e.slug),startDate:e.startDate??null,endDate:e.endDate??null,volume:Oe(e.volume,0),volume24h:Oe(e.volume24hr,0),liquidity:Oe(e.liquidity,0),negRisk:t,ended:e.ended===!0,markets:r,upDown:Dy(e.slug,e.markets?.[0])}}function Xa(e){return e.markets.find(t=>t.sportsMarketType==="moneyline")}function My(e,t=2){let n=e.markets.filter(l=>l.open);if(n.length===0)return null;let r=l=>l.priced?l.outcomes.slice(0,t):[],o=Xa(e);return o?o.open?{kind:"binary",outcomes:r(o),openMarketCount:n.length}:null:e.markets.length===1?{kind:"binary",outcomes:r(n[0]),openMarketCount:1}:{kind:"multi",outcomes:[...n.filter(l=>l.priced)].sort((l,c)=>c.outcomes[0].chance-l.outcomes[0].chance).slice(0,t).map(l=>({label:l.label,chance:l.outcomes[0].chance})),openMarketCount:n.length}}function Km(e){let t=/polymarket\.com\/(?:[a-z]{2}(?:-[a-z]{2})?\/)?event\/([a-z0-9-]+)(?:\/([a-z0-9-]+))?/i.exec(e);return t?{eventSlug:t[1].toLowerCase(),...t[2]?{marketSlug:t[2].toLowerCase()}:{}}:null}function rU(e){return`(prediction: ${e})`}function Ym(e){let t=/\(prediction:\s*([a-z0-9-]+)\s*\)/i.exec(e);return t?t[1].toLowerCase():null}function lt(e){let t=e.toLowerCase().replace(/đ/g,"d");try{t=t.normalize("NFD").replace(/[̀-ͯ]/g,"")}catch{}return t.replace(/[\s!-/:-@[-`{-~]+/g," ").trim()}function Fy(e){if(typeof e!="string"||!e.trim())return null;let t=lt(e);for(let n of $i)if([n.key,n.label,...n.aliases].map(lt).includes(t))return n;for(let n of $i)if([n.key,n.label,...n.aliases].map(lt).some(o=>o.length>=4&&(t.startsWith(o)||o.startsWith(t))))return n;return null}var gPe=$i.map(e=>e.key);var Go=1e-9,Ja=e=>Math.floor(e*100+Go)/100,oU=e=>Math.ceil(e*100-Go)/100;function Vi(e,t){return!t||!(t.rate>0)||!(e>0)||!(e<1)?0:t.rate*(e*(1-e))**t.exponent}function sU(e,t,n){return t>0?e/(1+Vi(t,n)/t):e}function iU(e,t,n){let r=[...e].sort((i,a)=>i.price-a.price),o=t,s=0;for(let i of r){if(o<=Go)break;if(!(i.price>0))continue;let a=1+Vi(i.price,n)/i.price,l=i.price*i.size,c=l*a;c>=o?(s+=o/a,o=0):(s+=l,o-=c)}return{notional:s,filled:o<=Go}}function aU(e,t,n){return Math.max(0,t-Du(e,t,n).feeUsd)}function KP(e,t,n){if(!(e>0)||e>1||!(t>0))return{usd:0,shares:0};let r=t*Vi(e,n),o=Number.isFinite(r)?Math.round(r*1e4)/1e4:0;return{usd:o,shares:o/e}}function YP(e,t,n){let r=Du(e,t,n),o=r.shares>0?t/r.shares:0,s=r.filled?KP(o,r.shares,n):{usd:0,shares:0},i=Math.max(0,r.shares-s.shares);return{shares:i,usd:t,feeUsd:s.usd,avgPrice:i>0?t/i:0,worstPrice:r.worstPrice,filled:r.filled}}function QP(e,t,n,r,o=0){if(!(t>0))return e;let s=Vi(t,r)*(1+o/100),a=Math.min(e,n)/t*s;return n<=e+a?Math.max(n-a,0):e}function Du(e,t,n){let r=[...e].sort((c,u)=>c.price-u.price),o=t,s=0,i=0,a=r[0]?.price??0;for(let c of r){if(o<=Go)break;let u=c.price*c.size;a=c.price;let d=u>=o?o/c.price:c.size;s+=d,i+=d*Vi(c.price,n),o=u>=o?0:o-u}let l=t-o;return{shares:s,usd:l,feeUsd:i,avgPrice:s>0?l/s:0,worstPrice:a,filled:o<=Go}}function XP(e,t,n){let r=[...e].sort((c,u)=>u.price-c.price),o=t,s=0,i=0,a=r[0]?.price??0;for(let c of r){if(o<=Go)break;let u=Math.min(o,c.size);a=c.price,s+=u*c.price,i+=u*Vi(c.price,n),o-=u}let l=t-o;return{shares:l,usd:s-i,feeUsd:i,avgPrice:l>0?s/l:0,worstPrice:a,filled:o<=Go}}function JP(e,t,n){return e?t.side==="BUY"?t.usd>0?Du(e.asks,t.usd,n):null:t.shares>0?XP(e.bids,t.shares,n):null:null}function qy(e,t,n,r=Vm.DEFAULT_SLIPPAGE){if(!(t>0))return e;let o=Math.max(0,Math.round(-Math.log10(t))),s=Math.round(e/t),i=n==="BUY"?Math.min(Math.ceil(s*(1+r)-Go),Math.round(1/t)-1):Math.max(Math.floor(s*(1-r)+Go),1);return Number((i*t).toFixed(o))}function lU(e,t,n,r=Vm.DEFAULT_SLIPPAGE,o="v1",s){let i=JP(t,n,s);if(!i||!t)return{error:Us.ENTER_AMOUNT,quote:null};if(i.shares<=0)return{error:Us.NO_LIQUIDITY,quote:i};if(n.side==="BUY"){let u=Ja(n.usd),d=qy(i.worstPrice,t.tickSize,"BUY",r),p=typeof n.cash=="number"&&n.cash>=0?n.cash:null,m=p===null?u:Ja(QP(u,d,p,s)),g=YP(t.asks,u,s);return u<Vm.MIN_BUY_USD?{error:Us.BELOW_MINIMUM,quote:g}:!g.filled||!Du(t.asks,m,s).filled?{error:Us.NOT_ENOUGH_LIQUIDITY,quote:g}:{quote:g,order:{tokenId:e,protocol:o,side:"BUY",amount:u,notional:m,maxPrice:d,...p===null?{}:{maxSpend:p}}}}let a=i,l=n.heldShares;if(l!==void 0&&n.shares>l+1e-6)return{error:Us.EXCEEDS_HOLDING,quote:a,maxShares:Ja(l)};if(!a.filled)return{error:Us.NOT_ENOUGH_LIQUIDITY,quote:a,maxShares:Ja(a.shares)};let c=Ja(l!==void 0?Math.min(n.shares,l):n.shares);return c<=0?{error:Us.TOO_SMALL,quote:a}:{quote:a,order:{tokenId:e,protocol:o,side:"SELL",shares:c,minPrice:qy(a.worstPrice,t.tickSize,"SELL",r)}}}function cU(e,t){let n=t==="BUY"?e?.asks[0]:e?.bids[0];return n?n.price:null}function Za(e,t){return e.filter(n=>Number.isFinite(n.price)&&Number.isFinite(n.size)&&n.size>0).sort((n,r)=>t==="bids"?r.price-n.price:n.price-r.price)}fw();var O_="0x0000000000000000000000000000000000000000",gw=(e,t)=>!!e&&!!t&&e.toLowerCase()===t.toLowerCase();function zr(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)}function yw(){return Rt(Hi)}var Eh=e=>e.toLowerCase();function UF(e){return Wt.encode([{type:"address"},{type:"bytes32"}],[Eh(Wr.depositWalletFactory),_t.padLeft(Eh(e),32)])}function KX(e,t){let n=BigInt((t.length-2)/2),r=Ds.PREFIX+(n<<BigInt(56));return Je.keccak256(_t.concat(_t.fromNumber(r,{size:10}),Eh(e),"0x6009",Ds.CONST2,Ds.CONST1,t))}function YX(e,t){let n=BigInt((t.length-2)/2),r=Ds.BEACON_PREFIX+(n<<BigInt(56));return Je.keccak256(_t.concat(_t.fromNumber(r,{size:10}),Eh(e),Ds.BEACON_CONST3,Ds.BEACON_CONST2,Ds.BEACON_CONST1,t))}function L_(e){let t=UF(e);return ho.fromCreate2({from:Wr.depositWalletFactory,salt:Je.keccak256(t),bytecodeHash:KX(Wr.depositWalletImplementation,t)})}function D_(e,t){let n=UF(e);return ho.fromCreate2({from:Wr.depositWalletFactory,salt:Je.keccak256(n),bytecodeHash:YX(t,n)})}function U_(e){return ho.fromCreate2({from:Wr.safeFactory,salt:Je.keccak256(Wt.encode([{type:"address"}],[Eh(e)])),bytecodeHash:Wr.safeInitCodeHash})}var Sh=null;function QX(e){return Sh||(Sh=XX(e),Sh.catch(()=>{Sh=null})),Sh}async function XX(e){try{let{data:t}=await e.call({to:Wr.depositWalletFactory,data:Wr.factoryBeaconSelector});return t&&t.length>=66?`0x${t.slice(-40)}`:O_}catch(t){if(jg(t)!==void 0)return O_;throw t}}async function Ph(e,t){return await e.getCode({address:t})!==void 0}async function B_(e,t=yw()){let n=L_(e),r=await QX(t);return gw(r,O_)||await Ph(t,n)?n:D_(e,r)}async function bw(e,t,n=yw()){if(t&&gw(t,e))return{address:e,owner:e,kind:"profile",deployed:await Ph(n,e)};let r=await B_(e,n),o=U_(e),[s,i]=await Promise.all([Ph(n,r),Ph(n,o)]);if(t){if(gw(t,o))return{address:o,owner:e,kind:"safe",deployed:i};if(gw(t,r))return{address:r,owner:e,kind:"deposit-wallet",deployed:s};if(await Ph(n,t))return{address:t,owner:e,kind:"profile",deployed:!0}}return s?{address:r,owner:e,kind:"deposit-wallet",deployed:!0}:i?{address:o,owner:e,kind:"safe",deployed:!0}:{address:r,owner:e,kind:"deposit-wallet",deployed:!1}}async function Rh(e,t=yw()){return t.readContract({address:Ls,abi:Ve,functionName:"balanceOf",args:[e]})}async function cd(e,t=yw()){return Number(await Rh(e,t))/10**zo}var Ys=class extends Error{status;constructor(t,n){super(n),this.name="PolymarketApiError",this.status=t}},_h=3e4,Ih=1e4,JX=60*6e4,ZX=64,BF=100,MF=1e3,eJ=new Set([429,500,502,503,504]),FF=2,tJ=3e3,nJ={active:"true",archived:"false",closed:"false",featured_order:"true",order:"featuredOrder",ascending:"true"},qF={closed:"false",order:"volume",ascending:"false",limit:"50"},rJ=50,oJ=5e3,sJ="1",iJ="64",HF=e=>new Promise(t=>setTimeout(t,e));function $F(e,t){let n=t?Number(t)*1e3:NaN;return Number.isFinite(n)&&n>=0?Math.min(n,tJ):400*2**e}async function ww(e,t){try{return await e}catch(n){if(WF(n))throw n;return t}}function WF(e){let t=e?.name,n=e?.code;return t==="AbortError"||t==="CanceledError"||n==="ERR_CANCELED"}var Ye=class{gamma;data;bridge;builderCode;clob;web;cache=new Map;accounts=new Map;constructor(t={}){this.gamma=(t.gammaBaseUrl??Fi.GAMMA).replace(/\/+$/,""),this.data=(t.dataBaseUrl??Fi.DATA).replace(/\/+$/,""),this.bridge=(t.bridgeBaseUrl??Fi.BRIDGE).replace(/\/+$/,""),this.builderCode=t.builderCode,this.clob=(t.clobBaseUrl??Fi.CLOB).replace(/\/+$/,""),this.web=(t.webBaseUrl??qi).replace(/\/+$/,"")}async listEvents({sort:t,tagId:n,limit:r}){let{order:o,ascending:s}=$m[t],i={closed:"false",order:o,ascending:String(s),limit:String(Math.min(Math.max(1,r),BF))};n&&(i.tag_id=n),t==="ending_soon"&&(i.end_date_min=new Date(Math.floor(Date.now()/6e4)*6e4).toISOString()),(t==="ending_soon"||t==="competitive")&&(i.exclude_tag_id=[UP]),t==="new"&&!n&&(i.exclude_tag_id=[BP,MP]);let a=this.eventRows(i);if(t!=="trending"||n)return vw(await a);let l=Date.now(),[c,u,d,p,m]=await Promise.all([a,ww(this.eventRows({...nJ,limit:String(rJ)}),[]),ww(this.eventRows({...qF,tag_id:sJ}),[]),ww(this.eventRows({...qF,tag_id:iJ}),[]),ww(this.eventRows({slug:WD(l),limit:"1"}).then(g=>g[0]??null),null)]);return vw(GD({feed:c,featured:u,sports:[...d,...p],btc5m:m},l))}async eventRows(t){let n=await this.getJson(`${this.gamma}/events/keyset`,t,_h);return Array.isArray(n.events)?n.events:[]}async getUpDownPrices(t){let n=await this.getJson(`${this.web}/api/crypto/crypto-price`,XD(t),oJ),r=o=>{let s=Oe(o,null);return s!==null&&s>0?s:null};return{openPrice:r(n?.openPrice),closePrice:r(n?.closePrice),completed:n?.completed===!0}}async searchEvents(t,n){let r=t.trim();if(!r)return[];let s=((await this.getJson(`${this.gamma}/public-search`,{q:r,events_status:"active",limit_per_type:String(Math.min(Math.max(1,n),50)),keep_closed_markets:"0"},_h)).events??[]).map(l=>l.id).filter(l=>typeof l=="string"&&!!l);if(s.length===0)return[];let i=await this.getJson(`${this.gamma}/events/keyset`,{id:s,limit:String(Math.min(s.length,BF))},_h),a=new Map(vw(i.events).map(l=>[l.id,l]));return s.map(l=>a.get(l)).filter(l=>l!==void 0)}async getEventBySlug(t){let n=await this.getJson(`${this.gamma}/events/keyset`,{slug:t,limit:"1"},_h);return vw(n.events)[0]??null}async getMarketTradeInfo(t){if(!/^0x[0-9a-fA-F]{64}$/.test(t))return null;let r=(await this.getJson(`${this.gamma}/markets/keyset`,{condition_ids:t,limit:"1"},_h)).markets?.[0];if(!r)return null;let o=Wm(r);return o===null?null:{conditionId:t,protocol:o,fee:zm(r),negRisk:r.negRisk===!0,open:Gm(r),outcomes:nU(r,o),question:(r.question??"").trim(),label:(r.groupItemTitle??"").trim(),eventTitle:(r.events?.[0]?.title??"").trim()}}async getProfileWallet(t){try{let n=await this.getJson(`${this.gamma}/public-profile`,{address:t},Ih);return typeof n.proxyWallet=="string"&&n.proxyWallet?n.proxyWallet:null}catch(n){if(n instanceof Ys&&n.status===404)return null;throw n}}async resolveAccount(t){let n=t.toLowerCase(),r=this.accounts.get(n);if(r&&(r.account.deployed||Date.now()-r.at<Ih))return r.account;let o=await bw(t,await this.getProfileWallet(t));return this.accounts.set(n,{account:o,at:Date.now()}),o}async getCash(t){return cd(t)}async getPositionsValue(t){let n=await this.getJson(`${this.data}/v2/value`,{user:t},Ih);return Oe(n?.data?.value,0)}async getPositions(t,n,r={}){let o=await this.getJson(`${this.data}/v2/positions`,{user:t,status:"OPEN",filter_type:"TOKENS",filter_amount:String(qP),sort_by:"CURRENT_VALUE",sort_direction:"DESC",limit:String(Math.min(Math.max(1,n),MF))},r.fresh?0:Ih);return jF(o).map(uJ)}async getActivity(t,n){let r=await this.getJson(`${this.data}/v2/activity`,{user:t,type:FP.join(","),sort_direction:"DESC",limit:String(Math.min(Math.max(1,n),MF))},Ih);return jF(r).map(dJ)}async getBridgeAssets(){return((await this.getJson(`${this.bridge}/supported-assets`,{},JX)).supportedAssets??[]).map(mJ).filter(n=>n!==null)}async getDepositAddresses(t){let r=(await this.requestJson("POST",`${this.bridge}/deposit`,{body:{address:t},headers:{"X-Builder-Code":this.builderCode??Ou()}})).address??{},o=typeof r.evm=="string"&&/^0x[0-9a-fA-F]{40}$/.test(r.evm)?r.evm:"";if(!o)throw new Ys(502,"Bridge returned no EVM deposit address");return{evm:o,svm:Ze(r.svm),btc:Ze(r.btc),tron:Ze(r.tron)}}async createWithdrawalAddresses(t){let r=(await this.requestJson("POST",`${this.bridge}/withdraw`,{body:{address:t.wallet,toChainId:t.toChainId,toTokenAddress:t.toTokenAddress,recipientAddr:t.recipient},headers:{"X-Builder-Code":this.builderCode??Ou()}})).address??{},o=typeof r.evm=="string"&&/^0x[0-9a-fA-F]{40}$/.test(r.evm)?r.evm:"";if(!o)throw new Ys(502,"Bridge returned no EVM withdrawal address");return{evm:o,svm:Ze(r.svm),btc:Ze(r.btc),tron:Ze(r.tron)}}async getBridgeQuote(t){let n=await this.requestJson("POST",`${this.bridge}/quote`,{body:t}),r=n.estFeeBreakdown??{},o=Ze(n.estToTokenBaseUnit);if(!/^\d+$/.test(o))throw new Ys(502,"Bridge returned no quote");return{estToTokenBaseUnit:o,estOutputUsd:Oe(n.estOutputUsd,0),estInputUsd:Oe(n.estInputUsd,0),estCheckoutTimeMs:Oe(n.estCheckoutTimeMs,null),minReceived:Oe(r.minReceived,null),totalImpactUsd:Oe(r.totalImpactUsd,0),totalImpactPercent:Oe(r.totalImpact,0),quoteId:Ze(n.quoteId)}}async getBridgeTransfers(t){return/^0x[0-9a-fA-F]{40}$/.test(t)?((await this.requestJson("GET",`${this.bridge}/status/${t}`)).transactions??[]).map(hJ).sort((r,o)=>(o.createdTimeMs??0)-(r.createdTimeMs??0)):[]}async getOrderBook(t,n){let r=await this.requestJson("GET",`${this.clob}/book?${VF({token_id:t})}`,{signal:n});return aJ(t,r)}getJson(t,n,r){let o=VF(n),s=o?`${t}?${o}`:t,i=this.cache.get(s);if(i&&Date.now()-i.at<i.ttl)return i.value;let a=this.requestJson("GET",s);if(a.catch(()=>{this.cache.get(s)?.value===a&&this.cache.delete(s)}),this.cache.size>=ZX){let l=this.cache.keys().next().value;l!==void 0&&this.cache.delete(l)}return this.cache.set(s,{at:Date.now(),ttl:r,value:a}),a}async requestJson(t,n,r={}){for(let o=0;;o++){let s;try{s=await se.request(t,n,r.body,{...r.signal?{signal:r.signal}:{},headers:{...r.body!==void 0?{"Content-Type":"application/json"}:{},...r.headers}})}catch(i){if(WF(i)||o>=FF)throw i;await HF($F(o));continue}if(s.ok)return s.data;if(!eJ.has(s.status)||o>=FF)throw new Ys(s.status,he(s));await HF($F(o,s.headers["retry-after"]))}}};function VF(e){let t=[];for(let[n,r]of Object.entries(e))for(let o of Array.isArray(r)?r:[r])t.push(`${encodeURIComponent(n)}=${encodeURIComponent(o)}`);return t.join("&")}function vw(e){return(Array.isArray(e)?e:[]).map(By).filter(t=>t!==null)}var Ze=e=>typeof e=="string"?e:"";function aJ(e,t){let n=r=>(r??[]).map(o=>({price:Oe(o.price,NaN),size:Oe(o.size,NaN)}));return{tokenId:e,bids:Za(n(t.bids),"bids"),asks:Za(n(t.asks),"asks"),tickSize:Oe(t.tick_size,.01),minOrderSize:Oe(t.min_order_size,0),negRisk:t.neg_risk===!0,lastTradePrice:Oe(t.last_trade_price,null),updatedAt:Date.now()}}var jF=e=>Array.isArray(e?.data)?e.data:[],lJ="1970-01-01",cJ=999;function uJ(e){let t=Ze(e.end_date),n=Oe(e.outcome_index,0);return{title:Ze(e.title),outcome:Ze(e.outcome),eventSlug:Ze(e.event_slug),conditionId:Ze(e.condition_id),asset:Ze(e.token_id),outcomeIndex:n===cJ?0:n,oppositeOutcome:Ze(e.opposite_outcome),oppositeAsset:Ze(e.opposite_token_id),icon:Ze(e.icon)||null,shares:Oe(e.current_size,0),avgPrice:Oe(e.avg_price,0),curPrice:Oe(e.current_price,0),initialValue:Oe(e.entry_cost_usdc,0),currentValue:Oe(e.current_value,0),cashPnl:Oe(e.unrealized_pnl,0),percentPnl:Oe(e.percent_pnl,0),redeemable:e.redeemable===!0,endDate:t&&t!==lJ?t:null}}function dJ(e){let t=Ze(e.side).toUpperCase();return{type:Ze(e.type).toUpperCase(),side:t==="BUY"||t==="SELL"?t:null,title:Ze(e.title),outcome:Ze(e.outcome),eventSlug:Ze(e.event_slug),shares:Oe(e.size,0),usd:Oe(e.usdc_size,0),price:Oe(e.price,0),timestamp:Oe(e.timestamp,0),transactionHash:Ze(e.transaction_hash)}}var pJ="0x0000000000000000000000000000000000000000";function mJ(e){let t=e.token??{},n=Ze(t.address).toLowerCase(),r=Oe(t.decimals,NaN);return!e.chainId||!n||!Number.isInteger(r)?null:{chainId:String(e.chainId),chainName:Ze(e.chainName),symbol:Ze(t.symbol),name:Ze(t.name),address:n===NP?pJ:n,decimals:r,minUsd:Oe(e.minCheckoutUsd,0)}}function hJ(e){return{fromChainId:String(e.fromChainId??""),fromTokenAddress:Ze(e.fromTokenAddress).toLowerCase(),fromAmountBaseUnit:String(e.fromAmountBaseUnit??"0"),toChainId:String(e.toChainId??""),status:Ze(e.status).toUpperCase(),txHash:Ze(e.txHash)||null,createdTimeMs:Oe(e.createdTimeMs,null)}}var zF=require("@noble/hashes/hmac"),GF=require("@noble/hashes/sha2");function M_(e,t,n,r,o){let s=`${t}${n}${r}${o??""}`,i=(0,zF.hmac)(GF.sha256,gJ(e),new TextEncoder().encode(s));return yJ(i).replace(/\+/g,"-").replace(/\//g,"_")}function ts(e){return typeof e?.authorize=="function"?e:F_(e)}var fJ=["POLY_BUILDER_API_KEY","POLY_BUILDER_PASSPHRASE","POLY_BUILDER_SIGNATURE","POLY_BUILDER_TIMESTAMP"];function KF(e){return{isBuilderKey:!0,supportGasless:!0,async authorize({method:t,path:n,body:r}){let o=typeof e.headers=="function"?await e.headers():e.headers,s=await fetch(e.url,{method:"POST",headers:{...o??{},"Content-Type":"application/json"},body:JSON.stringify({method:t,path:n,body:r}),credentials:e.credentials});if(!s.ok)throw new Error(`Remote builder signer rejected the request (${s.status})`);let i=await s.json(),a={};for(let l of fJ){let c=i?.[l];if(typeof c!="string"||!c)throw new Error(`Remote builder signer answered without ${l}`);a[l]=c}return a}}}function F_(e){return{isBuilderKey:!0,supportGasless:!0,async authorize({method:t,path:n,body:r}){let o=Math.floor(Date.now()/1e3);return{POLY_BUILDER_API_KEY:e.key,POLY_BUILDER_PASSPHRASE:e.passphrase,POLY_BUILDER_SIGNATURE:M_(e.secret,o,t,n,r),POLY_BUILDER_TIMESTAMP:String(o)}}}}function gJ(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}function yJ(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}var bJ=new Set(["STATE_CONFIRMED","STATE_FAILED","STATE_INVALID"]),wJ=e=>new Promise(t=>setTimeout(t,e));async function YF(e,t={}){let n=await fetch(`${Fi.RELAYER}${e}`,t),r=await n.text(),o;try{o=r?JSON.parse(r):null}catch{o=null}if(!n.ok){let s=o?.error||r||`HTTP ${n.status}`;throw new Error(`Relayer ${t.method??"GET"} ${e} failed (${n.status}): ${s}`)}return o}async function vJ(e,t,n){let r=JSON.stringify({type:"WALLET-CREATE",from:e,to:Wr.depositWalletFactory,metadata:"Deploy Deposit Wallet"}),o=await ts(t).authorize({method:"POST",path:_y,body:r});return YF(_y,{method:"POST",headers:{"Content-Type":"application/json",...o},body:r,signal:n})}async function kJ(e,t){let n=Date.now();for(;Date.now()-n<Iy.TIMEOUT_MS;){let r=await YF(`/transaction?id=${encodeURIComponent(e)}`,{signal:t}),o=Array.isArray(r)?r[0]:null;if(!o)throw new Error("Relayer transaction not found");if(bJ.has(o.state))return o;if(t?.aborted)throw new Error("Cancelled");await wJ(Iy.INTERVAL_MS)}throw new Error("Deploy timed out")}async function kw(e,t,n){let r=await vJ(e,t,n),o=await kJ(r.transactionID,n);if(o.state!=="STATE_CONFIRMED")throw new Error(`Deposit wallet deployment failed: ${o.error_msg||o.state}`);return{transactionHash:o.transactionHash,proxyAddress:o.proxyAddress,state:o.state}}var mT=null;function Vme(){let e=globalThis.URLSearchParams;typeof e!="function"||"size"in e.prototype||Object.defineProperty(e.prototype,"size",{configurable:!0,get(){let t=0;return this.forEach(()=>{t+=1}),t}})}function ca(){return Vme(),mT??=Promise.all([Promise.resolve().then(()=>(oj(),rj)),Promise.resolve().then(()=>(ij(),sj))]).then(([e,t])=>({sdk:e,actions:t})),mT.catch(()=>{mT=null}),mT}async function ua(){let{sdk:e}=await ca(),t=$o(Hi);return t?e.forkEnvironmentConfig({name:"production",rpc:t},e.production):e.production}var tL=new Map,hT=()=>{let e=$o(Hi)??"",t=tL.get(e);return t||(t=ua().then(async n=>(await ca()).sdk.createPublicClient({environment:n})),t.catch(()=>tL.delete(e)),tL.set(e,t)),t};function da(e){return{async getAddress(){return e.address},async signTypedData(t){let{EIP712Domain:n,...r}=t.types;return await e.signTypedData({...t,types:r})},async signMessage(t){if(!e.signMessage)throw new Error("Polymarket signer: signMessage is not supported by this wallet");return await e.signMessage(t)},async sendTransaction(){throw new Error("Polymarket signer: direct transactions are not supported \u2014 use the gasless relayer")}}}var jme=(BigInt(1)<<BigInt(256))-BigInt(1),Wme=[{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]}];async function fT(e){let[t,n]=await Promise.all([hT().then(i=>i.fetchTradingApprovalsState({user:e})),ua()]),r=new Set(zme(n).map(i=>i.toLowerCase())),o=(t.missing?.erc20??[]).map(i=>({tokenAddress:i.tokenAddress,spenderAddress:i.spenderAddress})).filter(i=>!r.has(String(i.spenderAddress).toLowerCase())),s=(t.missing?.erc1155??[]).map(i=>({tokenAddress:i.tokenAddress,operatorAddress:i.operatorAddress})).filter(i=>!r.has(String(i.operatorAddress).toLowerCase()));return{isFullyApproved:o.length===0&&s.length===0,missing:{erc20:o,erc1155:s}}}function zme(e){let t=e?.contracts?.perpsDepositContract;return[typeof t=="string"&&t?t:LP]}async function ys(e,t=new Ye){let n=await t.resolveAccount(e),r=n.deployed?await fT(n.address):null;return{account:n,approvals:r}}function lj(e){return e.isDeployed?e.isTradingEnabled?e.isApproved?on.DONE:on.APPROVE:on.ENABLE_TRADING:on.DEPLOY}function nL(e){return[...e.erc20.map(t=>({to:t.tokenAddress,data:Le({abi:Ve,functionName:"approve",args:[t.spenderAddress,jme]})})),...e.erc1155.map(t=>({to:t.tokenAddress,data:Le({abi:Wme,functionName:"setApprovalForAll",args:[t.operatorAddress,!0]})}))]}var hi=class extends Error{step;constructor(t,n,r){super(n),this.name="PolymarketOnboardingError",this.step=t,r!==void 0&&(this.cause=r)}};async function cj(e){let t=e.service??new Ye,n=e.tracking??{intervalMs:Cy.INTERVAL_MS,maxAttempts:Cy.MAX_ATTEMPTS},r=da(e.signer),o=e.chain?.approvals??fT,s=f=>{Gme(e.signal,f),e.onStep?.(f)},i=await t.resolveAccount(e.signer.address);if(i.kind==="profile")throw new hi(on.ENABLE_TRADING,"This address is a Polymarket account wallet, not a wallet that can sign for one.");let a=e.chain?.isDeployed??(async f=>await Rt(Hi).getCode({address:f})!==void 0);i.deployed||(s(on.DEPLOY),await Kd(on.DEPLOY,async()=>{await kw(e.signer.address,e.builder,e.signal),await aj(()=>a(i.address),f=>f,n,e.signal)}),i={...i,deployed:!0});let{sdk:l,actions:c}=await ca(),u=ts(e.builder),d=await ua();s(on.ENABLE_TRADING);let p=await Kd(on.ENABLE_TRADING,()=>l.createSecureClient({environment:d,signer:r,apiKey:u,wallet:i.address,...e.credentials?{credentials:{...e.credentials}}:{}})),m=og(p);if(!m)throw new hi(on.ENABLE_TRADING,"No CLOB credentials were issued.");await Kd(on.ENABLE_TRADING,async()=>e.onCredentials?.(m));let g=await Kd(on.APPROVE,()=>o(i.address));return g.isFullyApproved||(s(on.APPROVE),g=await Kd(on.APPROVE,async()=>{let f=nL(g.missing),y=await c.prepareGaslessTransaction(p,{calls:f,metadata:DP});return await(await Kme(y,r)).wait(),aj(()=>o(i.address),v=>v.isFullyApproved,n,e.signal)})),await Kd(on.APPROVE,()=>c.updateBalanceAllowance(p,{assetType:"COLLATERAL"})),s(on.DONE),{account:i,credentials:m,approvals:g}}function og(e){let{key:t,secret:n,passphrase:r}=e?.credentials??{};return typeof t=="string"&&t&&typeof n=="string"&&n&&typeof r=="string"&&r?{key:t,secret:n,passphrase:r}:null}async function Kd(e,t){try{return await t()}catch(n){if(n instanceof hi)throw n;let r=n instanceof Error&&n.message?n.message:String(n);throw new hi(e,r,n)}}function Gme(e,t){if(e?.aborted)throw new hi(t,"Cancelled")}async function aj(e,t,n,r){for(let o=1;;o++){let s=await e();if(t(s))return s;if(o>=n.maxAttempts)throw new Error("Not confirmed on-chain yet \u2014 please try again in a moment.");if(r?.aborted)throw new Error("Cancelled");await new Promise(i=>setTimeout(i,n.intervalMs))}}async function Kme(e,t){let n=await e.next();for(;!n.done;){let r=n.value;try{switch(r.kind){case"requestAddress":n=await e.next(await t.getAddress());break;case"signGaslessTypedData":n=await e.next(await t.signTypedData(r.payload));break;case"signGaslessMessage":n=await e.next(await t.signMessage(r.payload));break;default:throw new Error(`Unsupported gasless workflow request: ${String(r.kind)}`)}}catch(o){n=await e.throw(o)}}return n.value}var uj=new Set(Hm),Yme="0x0000000000000000000000000000000000000000";function rL(e){return e.filter(t=>/^\d+$/.test(t.chainId)&&Number(t.chainId)>0&&Number(t.chainId)<2**32&&t.address!==Yme&&/^0x[0-9a-f]{40}$/.test(t.address)&&uj.has(t.symbol.toUpperCase()))}async function gT(e,t){let n=new Map;for(let o of rL(t)){let s=Number(o.chainId),i=n.get(s)??[];i.some(a=>a.address===o.address)||i.push(o),n.set(s,i)}return(await Promise.allSettled([...n.entries()].map(async([o,s])=>{let i=`0x${o.toString(16)}`,l=await Rt(i).multicall({contracts:s.flatMap(c=>[{address:c.address,abi:Ve,functionName:"balanceOf",args:[e]},{address:c.address,abi:Ve,functionName:"decimals"}]),allowFailure:!0});return s.flatMap((c,u)=>{let d=l[2*u],p=l[2*u+1],m=d?.status==="success"&&typeof d.result=="bigint"?d.result:BigInt(0),g=p?.status==="success"&&(typeof p.result=="number"||typeof p.result=="bigint")?Number(p.result):NaN;return m<=BigInt(0)||!Number.isInteger(g)?[]:[{chainId:o,chainHex:i,chainName:j(i)||c.symbol,tokenAddress:c.address,symbol:c.symbol,decimals:g,balance:Jc(m,g),minUsd:c.minUsd}]})}))).flatMap(o=>o.status==="fulfilled"?o.value:[]).sort((o,s)=>Number(s.balance)-Number(o.balance))}var Qme=e=>/^\d+$/.test(e)&&Number(e)>0&&Number(e)<2**32&&!(e in Ya);function yT(e){let t=o=>{let s=gn.CHAIN_ORDER.indexOf(o);return s===-1?gn.CHAIN_ORDER.length:s},n=o=>{let s=Hm.indexOf(o.toUpperCase());return s===-1?Hm.length:s},r=new Set;return e.filter(o=>Qme(o.chainId)&&/^0x[0-9a-f]{40}$/.test(o.address)&&o.symbol).filter(o=>{let s=`${o.chainId}:${o.address}`;return r.has(s)?!1:(r.add(s),!0)}).map(o=>({chainId:o.chainId,chainName:o.chainName,symbol:o.symbol,tokenAddress:o.address,decimals:o.decimals,minUsd:o.minUsd,stable:uj.has(o.symbol.toUpperCase())})).sort((o,s)=>t(o.chainId)-t(s.chainId)||o.chainName.localeCompare(s.chainName)||n(o.symbol)-n(s.symbol)||o.symbol.localeCompare(s.symbol))}async function sg(e,t=new Ye){let n=Is(String(e.amount??"").trim(),e.asset.decimals);if(n===null||n<=BigInt(0))throw new Error("Enter an amount");let r=await t.getBridgeQuote({fromAmountBaseUnit:n.toString(),fromChainId:e.asset.chainId,fromTokenAddress:e.asset.tokenAddress,recipientAddress:e.wallet,toChainId:qm,toTokenAddress:Ls});return{estInputUsd:r.estInputUsd,estOutputUsd:r.estOutputUsd,priceImpactPercent:r.totalImpactPercent,totalFeeUsd:r.totalImpactUsd,minReceivedUsd:r.minReceived,estTimeMs:r.estCheckoutTimeMs}}var oL=100;async function dj(e,t,n=new Ye){let r=Math.max(oL,e.minUsd||0);if(e.stable)return sg({asset:e,amount:String(r),wallet:t},n);let o=await sg({asset:e,amount:"1",wallet:t},n);if(!(o.estInputUsd>0))return o;let s=(r/o.estInputUsd).toFixed(Math.min(e.decimals,8));return sg({asset:e,amount:s,wallet:t},n)}var Dr=e=>{let t=typeof e=="number"?e:Number.parseFloat(String(e??""));return Number.isFinite(t)?t:NaN},bT=e=>{let t=Dr(e);return Number.isFinite(t)?String(t):""};function pj(e,t){return Za([...e.entries()].map(([n,r])=>({price:Number(n),size:r})),t)}function Xme(e){return{bids:new Map(e.bids.map(t=>[bT(t.price),t.size])),asks:new Map(e.asks.map(t=>[bT(t.price),t.size])),tickSize:e.tickSize,minOrderSize:e.minOrderSize,negRisk:e.negRisk,lastTradePrice:e.lastTradePrice,updatedAt:e.updatedAt}}function Jme(e,t){return{tokenId:e,bids:pj(t.bids,"bids"),asks:pj(t.asks,"asks"),tickSize:t.tickSize,minOrderSize:t.minOrderSize,negRisk:t.negRisk,lastTradePrice:t.lastTradePrice,updatedAt:t.updatedAt}}function sL(e,t,n=Date.now()){let r=t?.payload??{};switch(t?.type){case"book":{let o=e.get(String(r.assetId));if(!o)return!1;let s=i=>[bT(i.price),Dr(i.size)];return o.bids=new Map((r.bids??[]).map(s).filter(([i,a])=>i&&a>0)),o.asks=new Map((r.asks??[]).map(s).filter(([i,a])=>i&&a>0)),Number.isFinite(Dr(r.tickSize))&&(o.tickSize=Dr(r.tickSize)),Number.isFinite(Dr(r.minOrderSize))&&(o.minOrderSize=Dr(r.minOrderSize)),typeof r.negRisk=="boolean"&&(o.negRisk=r.negRisk),Number.isFinite(Dr(r.lastTradePrice))&&(o.lastTradePrice=Dr(r.lastTradePrice)),o.updatedAt=n,!0}case"price_change":{let o=!1;for(let s of r.priceChanges??[]){let i=e.get(String(s.assetId)),a=bT(s.price);if(!i||!a)continue;let l=String(s.side).toUpperCase()==="BUY"?i.bids:i.asks,c=Dr(s.size);c>0?l.set(a,c):l.delete(a),i.updatedAt=n,o=!0}return o}case"last_trade_price":{let o=e.get(String(r.assetId));return!o||!Number.isFinite(Dr(r.price))?!1:(o.lastTradePrice=Dr(r.price),o.updatedAt=n,!0)}case"tick_size_change":{let o=e.get(String(r.assetId));return!o||!Number.isFinite(Dr(r.newTickSize))?!1:(o.tickSize=Dr(r.newTickSize),o.updatedAt=n,!0)}default:return!1}}function mj(e,t){let n=[...new Set(e.filter(Boolean))],r=t.service??new Ye,o=t.throttleMs??jm.THROTTLE_MS,s=t.staleMs??jm.STALE_MS,i=t.fallbackPollMs??jm.FALLBACK_POLL_MS,a=new Map,l=new AbortController,c=!1,u=null,d=null,p=Date.now(),m=0,g=null,f=null,y=null,w=V=>{u!==V&&(u=V,t.onStatus?.(V))},v=()=>{let V={};for(let[Y,te]of a)V[Y]=Jme(Y,te);return V},A=()=>{c||(g&&clearTimeout(g),g=null,m=Date.now(),t.onUpdate(v()))},k=()=>{if(c||g)return;let V=o-(Date.now()-m);V<=0?A():g=setTimeout(A,V)},T=()=>(y??=Promise.all(n.map(async V=>{try{let Y=await r.getOrderBook(V,l.signal);a.set(V,Xme(Y))}catch(Y){c||t.onError?.(Y)}})).then(()=>(p=Date.now(),A(),v())).finally(()=>{y=null}),y),D=V=>new Promise(Y=>{let te=setTimeout(Y,V);l.signal.addEventListener("abort",()=>{clearTimeout(te),Y()})}),q=async()=>{for(w("connecting"),await T();!c;){try{let V=await hT();if(c)break;if(d=await V.subscribe([{topic:"market",assetIds:n,customFeatureEnabled:!1}]),c){d.close();break}w("live");for await(let Y of d){if(c)break;p=Date.now(),sL(a,Y,p)&&k()}}catch(V){c||t.onError?.(V)}if(d=null,c)break;w("polling"),await T(),await D(i)}};return f=setInterval(()=>{!c&&Date.now()-p>s&&T()},Math.max(1e3,Math.floor(s/2))),q(),{refresh:T,stop(){c||(c=!0,l.abort(),g&&clearTimeout(g),f&&clearInterval(f),d?.close(),w("stopped"))}}}var Zme=(e,t)=>!!e&&!!t&&e.key===t.key&&e.secret===t.secret&&e.passphrase===t.passphrase;async function Yd(e){let{sdk:t}=await ca(),n=await t.createSecureClient({environment:await ua(),signer:da(e.signer),apiKey:ts(e.builder),wallet:e.wallet,...e.credentials?{credentials:{...e.credentials}}:{}}),r=og(n);return r&&!Zme(r,e.credentials)&&await e.onCredentials?.(r),n}function Qd(e){let t=e??{},n=String(t.message??"");return t.name==="CancelledSigningError"||/user (rejected|denied)|cancel(l)?ed/i.test(n)&&!/order (was )?cancel/i.test(n)}var pa=class extends Error{code;constructor(t,n,r){super(n),this.name="PolymarketTradeError",this.code=t,r!==void 0&&(this.cause=r)}},ehe=15e3,hj={unmatched:bt.NOT_FILLED,fak_not_filled:bt.NOT_FILLED,fok_not_filled:bt.NOT_FILLED,insufficient_balance_or_allowance:bt.INSUFFICIENT_BALANCE,market_not_ready:bt.MARKET_CLOSED,post_only_mode:bt.TRADING_PAUSED},the=[[/not enough balance \/ allowance/i,bt.INSUFFICIENT_BALANCE],[/lower than the minimum/i,bt.BELOW_MIN_SIZE],[/closed only mode/i,bt.CLOSE_ONLY],[/address banned/i,bt.ACCOUNT_BANNED],[/no orders found to match|couldn't be fully filled|not filled/i,bt.NOT_FILLED],[/not yet ready to process|market (is )?(closed|not active|resolved)|orderbook .* does not exist/i,bt.MARKET_CLOSED],[/post-only mode|trading is (currently )?(paused|disabled)|cancel-only/i,bt.TRADING_PAUSED]],nhe=e=>/not enough balance \/ allowance/i.test(String(e?.message??""));function aL(e){if(e instanceof pa)return e;let t=e??{},n=t.message||String(e),r=the.find(([s])=>s.test(n))?.[1],o=r===bt.CLOSE_ONLY||r===bt.ACCOUNT_BANNED?r:/restrict|region|geoblock|jurisdiction|not available in your/i.test(n)||t.status===403&&!t.restriction?bt.REGION_RESTRICTED:t.restriction?bt.TRADING_PAUSED:t.name==="InsufficientLiquidityError"?bt.NOT_ENOUGH_LIQUIDITY:Qd(e)?bt.CANCELLED:(r??(t.code&&hj[t.code]))||bt.FAILED;return new pa(o,n,e)}var rhe=(e,t)=>!!e&&!!t&&e.key===t.key&&e.secret===t.secret&&e.passphrase===t.passphrase,iL=e=>{let t=Number.parseFloat(String(e??""));return Number.isFinite(t)?t:0};async function fj(e){let{order:t}=e;try{let{sdk:n,actions:r}=await ca(),o=await n.createSecureClient({environment:await ua(),signer:da(e.signer),apiKey:ts(e.builder),wallet:e.wallet,...e.credentials?{credentials:{...e.credentials}}:{}}),s=og(o);s&&!rhe(s,e.credentials)&&await e.onCredentials?.(s);let i=e.builderCode??Ou(),a=t.side==="BUY"?{assetId:t.tokenId,side:n.OrderSide.BUY,amount:t.notional&&t.notional>0?t.notional:t.amount,...t.maxSpend!==void 0&&t.maxSpend>0?{maxSpend:t.maxSpend}:{},maxPrice:t.maxPrice,builderCode:i,orderType:n.OrderType.FAK}:{assetId:t.tokenId,side:n.OrderSide.SELL,shares:t.shares,minPrice:t.minPrice,builderCode:i,orderType:n.OrderType.FAK},c=await(async()=>{try{return await o.placeMarketOrder(a)}catch(g){if(nhe(g))return{ok:!1,code:"insufficient_balance_or_allowance",error:g};throw g}})();if(!c.ok&&c.code==="insufficient_balance_or_allowance"&&(await r.updateBalanceAllowance(o,ohe(t)),c=await o.placeMarketOrder(a)),!c.ok)throw new pa(hj[c.code]??bt.FAILED,c.message||c.code||"Order rejected");if(String(c.status).toLowerCase()===wT.DELAYED)return await she(o,String(c.orderId),t,e.delayedTimeoutMs);let u=iL(c.makingAmount),d=iL(c.takingAmount),p=Array.isArray(c.transactionsHashes)?c.transactionsHashes:[],m=e.settlementTimeoutMs??ehe;if(p.length===0&&m>0&&(c.tradeIds?.length??0)>0){let g;p=await Promise.race([r.waitForOrderFillSettlement(o,c).catch(()=>[]),new Promise(f=>{g=setTimeout(()=>f([]),m)})]).finally(()=>clearTimeout(g))}return{orderId:String(c.orderId),status:String(c.status),pending:!1,side:t.side,shares:t.side==="BUY"?d:u,usd:t.side==="BUY"?u:d,transactionHashes:p}}catch(n){throw aL(n)}}var wT={DELAYED:"delayed",LIVE:"live",MATCHED:"matched",UNMATCHED:"unmatched"};function ohe(e){return e.side==="BUY"?{assetType:"COLLATERAL"}:{assetType:e.protocol==="v2"?"CONDITIONAL-V2":"CONDITIONAL",assetId:e.tokenId}}async function she(e,t,n,r){let o=Date.now()+(r??Ny.TIMEOUT_MS);for(;;){await new Promise(c=>setTimeout(c,Ny.POLL_MS));let s=null;try{s=await e.fetchOrder({orderId:t})}catch{}let i=String(s?.status??"").toLowerCase(),a=iL(s?.sizeMatched),l=!!s&&!i.includes(wT.DELAYED);if(l&&a>0)return{orderId:t,status:wT.MATCHED,pending:!1,side:n.side,shares:a,usd:null,transactionHashes:[]};if(l)throw new pa(bt.NOT_FILLED,`Delayed order ${t} ended unmatched (${i})`);if(Date.now()>=o)return{orderId:t,status:wT.DELAYED,pending:!0,side:n.side,shares:0,usd:null,transactionHashes:[]}}}var Io=class extends Error{code;constructor(t,n,r){super(n),this.name="PolymarketWithdrawError",this.code=t,r!==void 0&&(this.cause=r)}},gj=/^0x[0-9a-fA-F]{40}$/,ihe=new Set(gn.STABLE_SYMBOLS);function vT(e){let t=o=>{let s=gn.CHAIN_ORDER.indexOf(o);return s===-1?gn.CHAIN_ORDER.length:s},n=o=>gn.STABLE_SYMBOLS.indexOf(o),r=new Set;return e.filter(o=>!(o.chainId in Ya)).filter(o=>gj.test(o.address)&&o.address.toLowerCase()!==Ls.toLowerCase()).filter(o=>ihe.has(o.symbol.toUpperCase())).filter(o=>{let s=`${o.chainId}:${o.address.toLowerCase()}`;return r.has(s)?!1:(r.add(s),!0)}).sort((o,s)=>t(o.chainId)-t(s.chainId)||o.chainName.localeCompare(s.chainName)||n(o.symbol.toUpperCase())-n(s.symbol.toUpperCase())).map(o=>({chainId:o.chainId,chainName:o.chainName,tokenAddress:o.address,symbol:o.symbol,decimals:o.decimals,minUsd:o.minUsd}))}function kT(e,t){return typeof t=="number"&&t>0?e<BigInt(Math.round(t*10**zo)):!1}async function ahe(e,t){if(typeof e.minUsd=="number")return e.minUsd;let n=e.tokenAddress.toLowerCase();return(await t.getBridgeAssets()).find(o=>o.chainId===e.chainId&&o.address.toLowerCase()===n)?.minUsd??0}function yj(e){return new Io(gn.ERROR.BELOW_MINIMUM,`Below the bridge minimum of $${e} for this destination`)}function xT(e){let t=String(e??"").trim(),n=/^(\d+)(?:\.(\d+))?$/.exec(t);if(!n)return null;let[,r,o=""]=n;if(o.length>zo)return null;let s=BigInt(r)*BigInt(10)**BigInt(zo)+BigInt(o.padEnd(zo,"0")||"0");return s>BigInt(0)?s:null}function lL(e){let t=BigInt(10)**BigInt(zo),n=e/t,r=(e%t).toString().padStart(zo,"0").replace(/0+$/,"");return r?`${n}.${r}`:n.toString()}async function bj(e,t=new Ye){let n=xT(e.amount);if(n===null)throw new Io(gn.ERROR.INVALID_AMOUNT,"Enter an amount");let r=e.destination.minUsd;if(kT(n,r))throw yj(r);let o=await t.getBridgeQuote({fromAmountBaseUnit:n.toString(),fromChainId:qm,fromTokenAddress:Ls,recipientAddress:e.recipient,toChainId:e.destination.chainId,toTokenAddress:e.destination.tokenAddress});return{estOutputBaseUnit:o.estToTokenBaseUnit,estOutputUsd:o.estOutputUsd,minReceivedUsd:o.minReceived,totalFeeUsd:o.totalImpactUsd,estTimeMs:o.estCheckoutTimeMs}}async function wj(e){let t=e.service??new Ye,n=xT(e.amount);if(n===null)throw new Io(gn.ERROR.INVALID_AMOUNT,"Enter an amount");if(!gj.test(e.recipient))throw new Io(gn.ERROR.FAILED,`Invalid recipient ${e.recipient}`);try{let r=await ahe(e.destination,t);if(kT(n,r))throw yj(r);let o=await Rh(e.wallet);if(o<n)throw new Io(gn.ERROR.INSUFFICIENT_BALANCE,`Cash ${lL(o)} is below ${e.amount}`);let s=await Yd(e),i=await t.createWithdrawalAddresses({wallet:e.wallet,toChainId:e.destination.chainId,toTokenAddress:e.destination.tokenAddress,recipient:e.recipient}),l=await(await s.transferErc20({tokenAddress:Ls,recipientAddress:i.evm,amount:n})).wait();return{bridgeAddress:i.evm,transactionHash:typeof l?.transactionHash=="string"?l.transactionHash:null,amountBaseUnit:n.toString()}}catch(r){throw cL(r)}}function cL(e){if(e instanceof Io)return e;let t=e?.message||String(e),n=Qd(e)?gn.ERROR.CANCELLED:/insufficient|exceeds balance|not enough balance/i.test(t)?gn.ERROR.INSUFFICIENT_BALANCE:gn.ERROR.FAILED;return new Io(n,t,e)}var ma=class extends Error{code;constructor(t,n,r){super(n),this.name="PolymarketRedeemError",this.code=t,r!==void 0&&(this.cause=r)}};async function vj(e){let t=e.service??new Ye;if(!/^0x[0-9a-fA-F]{64}$/.test(e.conditionId))throw new ma(Qa.ERROR.FAILED,`Invalid condition id ${e.conditionId}`);try{if((await t.getPositions(e.wallet,Qa.POSITIONS_READ_LIMIT,{fresh:!0})).filter(a=>a.conditionId.toLowerCase()===e.conditionId.toLowerCase()&&a.redeemable&&a.shares>0).length===0)throw new ma(Qa.ERROR.NOTHING_TO_CLAIM,"Nothing left to redeem in this market");let i=await(await(await Yd(e)).redeemPositions({conditionId:e.conditionId})).wait();return{transactionHash:typeof i?.transactionHash=="string"?i.transactionHash:null}}catch(n){if(n instanceof ma)throw n;let r=n?.message||String(n);throw new ma(Qd(n)?Qa.ERROR.CANCELLED:Qa.ERROR.FAILED,r,n)}}var lhe=6,che=.6,uhe=.1,dhe=200,phe=8,cc=new Map;function kj(e,t){let n=lt(e);if(n.length<phe||!t)return;let r=cc.get(n)??new Set;r.add(t),cc.delete(n),cc.set(n,r),cc.size>dhe&&cc.delete(cc.keys().next().value)}function mhe(e,t){let n=lt(e),r=lt(t),o=null;for(let[s,i]of cc)(n===s||r!==""&&` ${r} `.includes(` ${s} `))&&(!o||s.length>o.title.length)&&(o={title:s,slugs:i});return o&&o.slugs.size===1?[...o.slugs][0]:null}async function AT(e,t,n){let r=Ym(t)??Km(t)?.eventSlug??Ym(n)??Km(n)?.eventSlug??mhe(t,n)??null;if(r){let c=await e.getEventBySlug(r);return c?{kind:"event",event:c}:{kind:"not_found",query:t||r}}if(!t)return{kind:"unnamed"};let o=(await e.searchEvents(t,lhe)).filter(c=>c.markets.some(u=>u.open));if(o.length===0)return{kind:"not_found",query:t};let s=o.map(c=>({event:c,match:uL(t,c.title)})).sort((c,u)=>u.match.score-c.match.score),[i,a]=s;return o.length===1||i.match.exact||i.match.recall>=che&&(!a||i.match.score-a.match.score>=uhe)?{kind:"event",event:i.event}:{kind:"ambiguous",query:t,candidates:o}}function uL(e,t){let n=c=>lt(c).split(" ").filter(u=>u.length>1),r=n(e),o=n(t);if(r.length===0||o.length===0)return{recall:0,precision:0,score:0,exact:!1};let s=new Set(o),i=new Set(r),a=r.filter(c=>s.has(c)).length/r.length,l=o.filter(c=>i.has(c)).length/o.length;return{recall:a,precision:l,score:a*.7+l*.3,exact:r.join(" ")===o.join(" ")}}var TT="{market}",hhe=`Show me details of the prediction market ${TT}`,ha=[{name:"detail_button_label",type:"string",description:`Label for the "Details" button rendered on EVERY event card, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it. Just the word "Details" translated: English "Details", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the event \u2014 the button sits on that event's own card. One or two words.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this prediction market in detail" request IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a card's button is tapped. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the event title. English: "Show me details of the prediction market {market}". Vietnamese: "Xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng d\u1EF1 \u0111o\xE1n {market}". Always include {market}.`,required:!1}],xj=e=>typeof e=="string"?e.trim():"";function dL(e){return xj(e.detail_button_label).replace(TT,"").replace(/\s+/g," ").trim()}function pL(e,t,n){kj(e,t);let r=xj(n.detail_prompt_template);return(r.includes(TT)?r:hhe).split(TT).join(e).replace(/\s+/g," ").trim()}function fhe(e){return Math.round(e*1e3)/10}function fi(e,t){let n=10**t;return Math.trunc(Number((e*n).toFixed(6)))/n}function fa(e){return fi(e,2)}function ST(e){return fi(e,6)}function uc(e){return Math.round(e)}function mL(e){return e.map(t=>({label:t.label,chancePercent:fhe(t.chance),...t.shortLabel?{shortLabel:t.shortLabel}:{}}))}function Xd(e,t){let n=My(e);return n?{title:e.title,slug:e.slug,url:e.url,image:e.image,endDate:e.endDate,volumeUsd:uc(e.volume),volume24hUsd:uc(e.volume24h),kind:n.kind,outcomes:mL(n.outcomes),openMarketCount:n.openMarketCount,detailPrompt:pL(e.title,e.slug,t),detailLabel:dL(t),upDown:e.upDown}:null}var ga='A chance shown here is the PRICE traders currently pay for that outcome \u2014 the market-implied probability \u2014 never a forecast of yours: phrase it as "the market prices X at N%", never "X will win" or "X is likely". Do NOT give your own opinion or analysis of the underlying event (an election, a game, a policy decision), do NOT tell the user which side to buy or how much to stake, and never state a chance, price or volume the tool did not return. Prediction markets can lose the whole stake; this is information, not advice. Do NOT mention tool names.';var Tj=5,hL=20,ghe=3,Sj=Object.keys($m),Aj={trending:"ordered as polymarket.com's homepage Trending view: its featured events, live or upcoming games and the live 5-minute Bitcoin market first, then by 24-hour trading volume",new:"ordered by creation date, newest first",volume:"ordered by all-time trading volume, largest first",liquidity:"ordered by liquidity, deepest first",competitive:"ordered by how close the odds are (the most contested first)",ending_soon:"ordered by end date, the soonest-ending first"},Jd=class extends K{name="get-prediction-markets";kind="ui";category="prediction";description='BROWSE or SEARCH Polymarket prediction markets \u2014 real-world questions people trade on (elections, sports games, crypto prices, economics, geopolitics, tech, weather\u2026). Returns event cards with the current market-implied odds of each, volume and end date, plus a "Details" button per event. Use for: "trending predictions", "hot Polymarket markets", "sports prediction markets", "d\u1EF1 \u0111o\xE1n v\u1EC1 crypto", "new markets", "markets ending soon", "most contested markets", "is there a market on <topic>?", "odds on the next Fed decision", "Polymarket odds for the election". Pass `query` when the user names a TOPIC or event (a person, team, coin, event); pass `category` when they name a broad section; pass neither for the general feed. Do NOT use for: ONE event in full (all its options, rules, deadline) \u2192 get-prediction-market-detail; the user\'s own positions \u2192 get-prediction-portfolio; their trade history \u2192 get-prediction-activity.';parameters=[{name:"query",type:"string",description:`Search text when the user names a topic, event, person, team or coin ("bitcoin", "world cup", "Fed rates", "Lakers"). Write it in ENGLISH keywords \u2014 market titles are English \u2014 translating the user's words ("b\u1EA7u c\u1EED M\u1EF9" \u2192 "US election"). OMIT for a general or category feed.`,required:!1},{name:"category",type:"string",description:`Category to scope a feed to. One of: ${$i.map(t=>t.key).join(", ")}. Pass the user's word as-is if unsure \u2014 it is matched for you, and an unknown one is reported back. OMIT when the user named none, and when \`query\` is set.`,required:!1},{name:"sort",type:"string",description:`Feed order: ${Sj.map(t=>`"${t}" (${Aj[t]})`).join(", ")}. Default "trending". Ignored when \`query\` is set (search results are ordered by relevance).`,required:!1},{name:"limit",type:"number",description:`How many events, 1-${hL}. Default ${Tj}. Raise only when the user asks for more.`,required:!1},...ha];service;constructor(t){super(),this.service=new Ye(t)}async run(t){let n=typeof t.query=="string"?t.query.trim():"",r=bhe(t.limit),o=typeof t.category=="string"?t.category.trim():"",s=n?null:Fy(o);if(!n&&o&&!s)return{requestedCategory:o,categoriesAvailable:$i.map(p=>p.label),_instructions:`"${o}" is not a prediction-market category here. In the user's language, say so in one short sentence and name the categories in \`categoriesAvailable\`, offering to show one of them or to search a specific topic. Do NOT invent markets. Do NOT mention tool names.`};let i=yhe(t.sort),l=(n?await this.service.searchEvents(n,Math.min(hL*2,r*2+5)):await this.service.listEvents({sort:i,tagId:s?.tagId,limit:r*ghe})).map(p=>Xd(p,t)).filter(p=>p!==null).slice(0,r);if(l.length===0)return{query:n||null,category:s?.label??null,eventCount:0,_instructions:(n?`No open prediction market matches "${n}" right now. `:"No open prediction markets could be loaded for this view right now. ")+"Say so briefly in the user's language and offer to show the trending markets or another topic. Do NOT invent markets or odds. Do NOT mention tool names."};let c={sort:n?"relevance":i,category:s?.label??null,query:n||null,events:l},u={component:"PredictionMarketList",props:c},d=n?`prediction markets matching "${n}", most relevant first`:`${s?`${s.label} `:""}prediction markets ${Aj[i]}`;return{ui:u,query:n||null,category:s?.label??null,sortedBy:c.sort,eventCount:l.length,eventTitles:l.map(p=>p.title),_instructions:[`These are ${d}. They are ALREADY RENDERED as cards below your reply, each with its title, the`,'current odds, volume, end date and a "Details" button. Do NOT write the list out: no numbered or',"bullet list, no per-event lines, no odds, no links, no mention of the buttons.",`Write your reply in TWO parts separated by a line containing exactly ${jr} and nothing`,"else \u2014 include that marker EXACTLY ONCE, on its own line; do not translate, style or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: ONE short sentence noting that the odds are live market prices that move","constantly and that this is information, not betting advice \u2014 in the user's language.",ga].join(" ")}}};function yhe(e){let t=typeof e=="string"?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):"";return Sj.includes(t)?t:"trending"}function bhe(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?Tj:Math.min(Math.floor(t),hL)}function Zd(e){return!e.open||e.clobTokenIds.length!==e.outcomes.length||e.clobTokenIds.length<2?null:{question:e.question,conditionId:e.conditionId,negRisk:e.negRisk,protocol:e.protocol,fee:e.fee,outcomes:e.outcomes.map((t,n)=>({label:t.label,tokenId:e.clobTokenIds[n],...t.shortLabel?{shortLabel:t.shortLabel}:{}}))}}function Pj(e,t,n){let r=e.markets.filter(c=>c.open&&Zd(c));if(r.length===0)return null;if(n?.open&&Zd(n)&&!t)return n;if(r.length===1)return r[0];if(!t)return null;let o=lt(t),s=r.find(c=>lt(c.label)===o||lt(c.question)===o);if(s)return s;let i=r.map(c=>({m:c,match:uL(t,c.label||c.question)})).sort((c,u)=>u.match.score-c.match.score),[a,l]=i;return a.match.recall>=.6&&(!l||a.match.score>l.match.score)?a.m:null}function Ej(e,t){if(!t)return-1;let n=lt(t),o={co:"yes",khong:"no"}[n]??n,s=e.outcomes.map(a=>lt(a.label)),i=s.indexOf(o);return i>=0?i:s.findIndex(a=>a.includes(o)||o.includes(a))}function PT(e){let t=typeof e=="string"?e.trim().replace(",","."):typeof e=="number"?String(e):"";return/^\d+(\.\d+)?$/.test(t)&&Number(t)>0?t:null}function ET(e){return typeof e=="string"&&/^(all|max|everything|het|tat ca|toan bo)$/.test(lt(e))}var whe=15,Rj=600,vhe=5,ep=class extends K{name="get-prediction-market-detail";kind="ui";category="prediction";description='Show ONE prediction market (Polymarket event) in full: every open option with its current market-implied odds and 24 h change, volume, liquidity, end date and how it resolves. Use when the user singles out one event \u2014 "tell me more about the Fed October decision market", "odds of each candidate in the Brazil election", "how does this market resolve", a pasted polymarket.com link, or a tapped "Details" button (its message names the title of an event card already shown). Do NOT use for browsing many events or a topic in general \u2192 get-prediction-markets. Do NOT use when the user wants to buy, sell or bet (mua / b\xE1n / \u0111\u1EB7t c\u01B0\u1EE3c) \u2014 even with a hint \u2192 open-prediction-trade.';parameters=[{name:"market",type:"string",description:'Which event. When the message names the title of an event card already shown (a "Details" tap), pass that title VERBATIM, untranslated. When it carries a "(prediction: <slug>)" hint, pass that hint VERBATIM (with the parentheses). When it carries a polymarket.com link, pass the link. Otherwise pass the event as the user named it, in ENGLISH keywords ("Fed decision October", "Brazil presidential election").',required:!0},...ha];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=typeof t.market=="string"?t.market.trim():"",o=await AT(this.service,r,n?.query??"");switch(o.kind){case"event":return this.detail(o.event);case"ambiguous":return this.ambiguous(o.query,o.candidates,t);case"not_found":return this.notFound(o.query);default:return{_instructions:"No event was named. Ask the user, in their language, which prediction market they want to see. Do NOT mention tool names."}}}detail(t){let n=t.markets.filter(i=>i.open),r=fL(t),o=r.markets,s={component:"PredictionMarketDetail",props:r};return n.length===0?{ui:s,title:t.title,open:!1,resolvedOutcomes:xhe(t),_instructions:"This prediction market is CLOSED \u2014 no longer open for trading. In the user's language, say so in one or two sentences; if `resolvedOutcomes` lists winners, state them as how the market resolved. "+ga}:{ui:s,title:t.title,open:!0,endDate:t.endDate,volumeUsd:r.volumeUsd,mutuallyExclusive:t.negRisk,leadingOptions:o.filter(i=>i.outcomes.length>0).slice(0,vhe).map(i=>({option:i.label,outcomes:i.outcomes.map(a=>`${a.label} ${a.chancePercent}%`).join(" / ")})),openMarketCount:n.length,rules:_j(t.description,Rj),_instructions:["The event is ALREADY RENDERED as a card below your reply, listing every open option with its odds,","volume, end date and rules. Write at most THREE short sentences: what the question is, the leading","option(s) from `leadingOptions` as market prices, and when it ends. Do NOT list every option and do NOT","repeat the rules unless the user asked how it resolves (then summarize `rules` in one sentence).",ga].join(" ")}}ambiguous(t,n,r){let o=n.map(i=>Xd(i,r)).filter(i=>i!==null);return o.length===0?this.notFound(t):{ui:{component:"PredictionMarketList",props:{sort:"relevance",category:null,query:t,events:o}},query:t,candidateCount:o.length,candidateTitles:o.map(i=>i.title),_instructions:[`"${t}" matches several prediction markets, so none was opened. They are ALREADY RENDERED as cards`,'below your reply, each with a "Details" button. Write your reply in TWO parts separated by a line',`containing exactly ${jr} (exactly once, on its own line): PART ONE \u2014 one short sentence`,"saying several markets match and asking which one they mean; PART TWO \u2014 leave it empty or one short","sentence. Do NOT list the markets in text.",ga].join(" ")}}notFound(t){return{query:t,found:!1,_instructions:`No open prediction market matching "${t}" was found. Say so briefly in the user's language and offer to search a related topic or show the trending markets. Do NOT invent a market or odds. Do NOT mention tool names.`}}};function fL(e){let t=e.markets.filter(s=>s.open),n=Xa(e),o=(n?n.open?[n]:[]:t.slice(0,whe)).map(khe(e));return{title:e.title,slug:e.slug,url:e.url,image:e.image,description:_j(e.description,Rj),resolutionSource:e.resolutionSource,endDate:e.endDate,volumeUsd:uc(e.volume),volume24hUsd:uc(e.volume24h),liquidityUsd:uc(e.liquidity),negRisk:e.negRisk,markets:o,hiddenMarketCount:Math.max(0,t.length-o.length)}}function khe(e){let t=e.markets.length===1;return n=>({label:t?e.title:n.label,outcomes:n.priced?mL(n.outcomes):[],volumeUsd:uc(n.volume),oneDayChangePoints:n.priced&&n.oneDayPriceChange!==null?Math.round(n.oneDayPriceChange*1e3)/10:null,trade:Zd(n)})}function xhe(e){return e.markets.filter(t=>!t.open).map(t=>({market:t.label,winner:t.outcomes.find(n=>n.chance>=.999)?.label??""})).filter(t=>t.winner).slice(0,5)}function _j(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=n.lastIndexOf(" ");return`${(r>t*.6?n.slice(0,r):n).trimEnd()}\u2026`}function bs(e,t){return{component:"PredictionSetupCard",props:{signer:e.owner,wallet:e.address,walletKind:e.kind==="safe"?"safe":"deposit-wallet",deployed:e.deployed,approved:e.deployed?t?.isFullyApproved??!1:null}}}var ya="This wallet has no Polymarket account yet, so there is nothing to show. A card to set one up is ALREADY RENDERED below your reply. In ONE short sentence in the user's language, say there is no Polymarket account yet and that they can create it with the card below. Do NOT invent positions, balances or steps, and do NOT mention tool names.";var RT={name:"address",type:"string",description:"EVM address (0x\u2026) to look up \u2014 the user's wallet or a Polymarket account wallet. Set it ONLY when the user wrote an address; otherwise OMIT it and the connected wallet is used.",required:!1};function Ij(e){return`${qi}/profile/${e}`}function _T(e){return e?`${qi}/event/${e}`:null}async function IT(e,t,n){let r=gt(t.address,n);if(!zr(r))return{ok:!1,result:{address:r,_instructions:`"${r}" is not a valid EVM address. Ask the user, in their language, for a valid 0x address. Do NOT mention tool names.`}};let o=await e.resolveAccount(r),s=!!n?.walletAddress&&n.walletAddress.toLowerCase()===r.toLowerCase();return!o.deployed&&s&&o.kind!=="profile"?{ok:!1,result:{ui:bs(o,null),hasPolymarketAccount:!1,_instructions:ya}}:o.deployed?{ok:!0,account:o}:{ok:!1,result:{address:r,hasPolymarketAccount:!1,_instructions:"This wallet has no Polymarket account yet \u2014 nothing has been deposited or traded on Polymarket from it. Tell the user so in one short sentence, in their language, and offer to show the trending prediction markets instead. Do NOT invent positions or balances. Do NOT mention tool names."}}}var Cj=10,Nj=30,Ahe=200,tp=class extends K{name="get-prediction-portfolio";kind="ui";category="prediction";description=`The user's Polymarket holdings: cash available to trade, the value and profit/loss of every open position, and winnings ready to claim. Use for "my Polymarket positions", "my bets", "how much have I won/lost on Polymarket", "v\u1ECB th\u1EBF d\u1EF1 \u0111o\xE1n c\u1EE7a t\xF4i", "Polymarket balance". Works for the connected wallet or an address the user gives. Do NOT use for past trades \u2192 get-prediction-activity; for markets to browse \u2192 get-prediction-markets.`;parameters=[RT,{name:"limit",type:"number",description:`How many positions to list, 1-${Nj}. Default ${Cj}.`,required:!1},...ha];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=await IT(this.service,t,n);if(!r.ok)return r.result;let o=r.account.address,s=Phe(t.limit),[i,a,l]=await Promise.all([this.service.getPositions(o,Ahe),this.service.getPositionsValue(o),this.service.getCash(o).catch(()=>null)]),c=i.filter(The),u=c.filter(y=>y.redeemable),d=fa(u.reduce((y,w)=>y+w.currentValue,0)),p=c.slice(0,s).map(y=>She(y,t)),m={wallet:o,profileUrl:Ij(o),cashUsd:l===null?null:ST(l),positionsValueUsd:fa(a),claimableUsd:d,positions:p,totalPositions:c.length},g={component:"PredictionPortfolio",props:m},f=fa(c.reduce((y,w)=>y+w.cashPnl,0));return{ui:g,wallet:o,cashUsd:m.cashUsd,positionsValueUsd:m.positionsValueUsd,claimableUsd:d,openPositionCount:c.length-u.length,claimablePositionCount:u.length,unrealizedPnlUsd:f,positionsShown:p.length,positions:p.map(y=>({market:y.title,outcome:y.outcome,valueUsd:y.valueUsd,pnlUsd:y.pnlUsd})),_instructions:["The portfolio is ALREADY RENDERED as a card below your reply: cash, positions value, claimable winnings","and each position with its value and profit/loss. Write at most TWO short sentences in the user's","language: the headline numbers (cash, positions value, and claimable winnings if above 0) in USD exactly","as given, and \u2014 only if there are no positions \u2014 that the account currently holds none. End with a period,","never a colon. Do NOT list the positions in text (`positions` is there only so you never state anything","that is not in it). Never state a figure that is not in this result.",c.length===0?"":"Do NOT judge the positions or suggest selling, holding or buying anything.","Do NOT mention tool names."].filter(Boolean).join(" ")}}};function The(e){return e.shares<=0?!1:!e.redeemable||e.currentValue>0}function She(e,t){return{title:e.title,outcome:e.outcome,url:_T(e.eventSlug),icon:e.icon,shares:fi(e.shares,2),avgPrice:fi(e.avgPrice,4),curPrice:fi(e.curPrice,4),valueUsd:fa(e.currentValue),pnlUsd:fa(e.cashPnl),pnlPercent:Math.round(e.percentPnl*10)/10,claimable:e.redeemable&&e.currentValue>0,endDate:e.endDate,detailPrompt:e.eventSlug?pL(e.title,e.eventSlug,t):"",detailLabel:dL(t),tokenId:e.asset,conditionId:e.conditionId,outcomeIndex:e.outcomeIndex,oppositeOutcome:e.oppositeOutcome,oppositeTokenId:e.oppositeAsset}}function Phe(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?Cj:Math.min(Math.floor(t),Nj)}var Oj=10,Lj=30,Ehe="https://polygonscan.com/tx/",np=class extends K{name="get-prediction-activity";kind="ui";category="prediction";description=`The user's recent Polymarket history: each buy and sell (outcome, shares, price, amount), claimed winnings and rewards, newest first. Use for "my Polymarket trades", "what did I bet on", "l\u1ECBch s\u1EED giao d\u1ECBch Polymarket", "my last prediction trades". Works for the connected wallet or an address the user gives. Do NOT use for current holdings \u2192 get-prediction-portfolio.`;parameters=[RT,{name:"limit",type:"number",description:`How many entries, 1-${Lj}. Default ${Oj}.`,required:!1}];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=await IT(this.service,t,n);if(!r.ok)return r.result;let o=r.account.address,s=Rhe(t.limit),i=(await this.service.getActivity(o,s)).map(c=>({type:c.type,side:c.side,title:c.title,outcome:c.outcome,url:_T(c.eventSlug),shares:fi(c.shares,2),usd:fa(c.usd),price:fi(c.price,4),timestamp:c.timestamp,txUrl:/^0x[0-9a-fA-F]{64}$/.test(c.transactionHash)?`${Ehe}${c.transactionHash}`:null}));return i.length===0?{wallet:o,entryCount:0,_instructions:"This Polymarket account has no trading history yet. Say so in one short sentence in the user's language. Do NOT invent trades. Do NOT mention tool names."}:{ui:{component:"PredictionActivity",props:{wallet:o,items:i},completeList:!0},wallet:o,entryCount:i.length,entries:i.map(c=>({type:c.type,side:c.side,market:c.title,outcome:c.outcome,usd:c.usd,date:c.timestamp>0?new Date(c.timestamp*1e3).toISOString().slice(0,10):null})),_instructions:["The history is ALREADY RENDERED as a list below your reply \u2014 every entry with its type, outcome, shares,",'price, amount and time \u2014 so a request to "show" or "list" the trades is ALREADY fully answered by it;',"writing the entries out again would show each one twice.",`Write your reply in TWO parts separated by a line containing exactly ${jr} (exactly once, on`,"its own line). PART ONE: ONE short sentence ending with a period (never a colon) saying this is their","recent Polymarket activity and how many entries are shown. PART TWO: EMPTY \u2014 write nothing at all after the","marker. No bullet or numbered list anywhere, no per-entry lines: `entries` is given ONLY so you never","state anything that is not in it. Do NOT judge the trades. Do NOT mention tool names."].join(" ")}}};function Rhe(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?Oj:Math.min(Math.floor(t),Lj)}var rp=class extends K{name="open-prediction-setup";kind="ui";category="prediction";description=`Open the card that SETS UP the user's Polymarket account so they can trade prediction markets: one button that enables trading, creates their Polymarket wallet and grants the trading approvals \u2014 gasless, signed once from their own wallet. Use for "create a Polymarket account", "set up Polymarket", "enable trading on Polymarket", "t\u1EA1o t\xE0i kho\u1EA3n Polymarket", "k\xEDch ho\u1EA1t giao d\u1ECBch d\u1EF1 \u0111o\xE1n", or when the user wants to start betting / trading and has no account. Needs the connected wallet. Do NOT use to deposit funds \u2192 open-prediction-deposit.`;parameters=[];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=n?.walletAddress?.trim();if(!r||!zr(r))return{error:"wallet_not_connected",_instructions:"Setting up a Polymarket account needs the user's own connected wallet, which signs for it. Ask them, in their language, to connect a wallet first. Do NOT mention tool names."};let{account:o,approvals:s}=await ys(r,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, not a wallet that can sign for one, so it cannot be set up here. Say so briefly in the user's language. Do NOT mention tool names."};let i=bs(o,s),a=o.deployed&&s?.isFullyApproved===!0;return{ui:i,walletDeployed:o.deployed,approvalsComplete:s?.isFullyApproved??!1,_instructions:["The Polymarket account-setup card is ALREADY RENDERED below your reply; it runs the setup itself when the","user taps its button. Write ONE or TWO short sentences in the user's language:",a?"the wallet is already created and approved on-chain, so the card only needs to confirm trading access \u2014":"what the button does \u2014 enables trading, creates their Polymarket wallet and grants the approvals in one go,","with no gas fees, signed from their own wallet (an NFC card is tapped once).","Do NOT claim the account is set up, do NOT list technical steps or contract names, and do NOT mention tool","names."].join(" ")}}};var op=class extends K{name="open-prediction-deposit";kind="ui";category="prediction";description='Open the card that DEPOSITS funds into the user\'s Polymarket account (to trade prediction markets): send a stablecoin they hold (USDC, USDT, DAI\u2026 on Ethereum, Base, Polygon, Arbitrum, BSC\u2026) straight from their wallet, or get the EVM deposit address + QR code for another EVM wallet or exchange (EVM chains only). Use for "deposit to Polymarket", "fund my Polymarket", "n\u1EA1p ti\u1EC1n v\xE0o Polymarket", "top up my prediction account", "n\u1EA1p 50 USDC v\xE0o Polymarket". Needs the connected wallet; if the account is not set up yet the setup card is shown instead. Pass `amount` ONLY when the user named one.';parameters=[{name:"amount",type:"string",description:`Amount to pre-fill, in the stablecoin's own units as a plain decimal ("50", "12.5"). ONLY when the user named an amount; never invent or convert one.`,required:!1}];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=n?.walletAddress?.trim();if(!r||!zr(r))return{error:"wallet_not_connected",_instructions:"Depositing into Polymarket needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let{account:o,approvals:s}=await ys(r,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, so deposits are made to it directly from another wallet. Say so briefly in the user's language. Do NOT mention tool names."};if(!o.deployed)return{ui:bs(o,s),hasPolymarketAccount:!1,_instructions:ya};let[i,a]=await Promise.all([this.service.getBridgeAssets(),this.service.getDepositAddresses(o.address)]),l=await gT(r,i),c=typeof t.amount=="string"&&/^\d+(\.\d+)?$/.test(t.amount.trim())?t.amount.trim():null,d={component:"PredictionDepositCard",props:{wallet:o.address,owner:r,depositAddress:a.evm,options:l,assets:yT(i),networks:_he(i,a),prefillAmount:c}},p=l.length>0?Math.min(...l.map(m=>m.minUsd)):null;return{ui:d,walletHasDepositableStablecoins:l.length>0,depositableFromWallet:l.slice(0,5).map(m=>`${m.symbol} on ${m.chainName}`),minimumDepositUsd:p,_instructions:["The deposit card is ALREADY RENDERED below your reply: it opens the deposit screen, which sends a stablecoin","from the user's wallet, or shows the EVM deposit address and QR code for another EVM wallet or exchange","(EVM chains only \u2014 Ethereum, Base, Polygon, Arbitrum, BNB Chain\u2026). Write ONE or TWO short sentences in the","user's language:",l.length>0?"they can deposit straight from their wallet with the card (pick a token and amount),":"their wallet holds no stablecoin the card can send, so they can deposit from another EVM wallet or exchange using the address and QR code,","funds arrive as cash in their Polymarket account after the bridge processes them (usually a few minutes),",p!==null?`and deposits below about $${p} may not be credited.`:"and very small deposits may not be credited.","Do NOT claim a deposit was made, do NOT repeat addresses, and do NOT mention tool names."].join(" ")}}};function _he(e,t){let n={evm:{chains:new Set,minUsd:1/0},svm:{chains:new Set,minUsd:1/0},btc:{chains:new Set,minUsd:1/0},tron:{chains:new Set,minUsd:1/0}};for(let r of e){let o=Ya[r.chainId];if(o===null)continue;let s=n[o??"evm"];s.chains.add(r.chainName),s.minUsd=Math.min(s.minUsd,r.minUsd)}return Object.keys(n).filter(r=>t[r]&&n[r].chains.size>0).map(r=>({family:r,address:t[r],chains:[...n[r].chains].sort(),minUsd:Number.isFinite(n[r].minUsd)?n[r].minUsd:0}))}var Ihe=100,sp=class extends K{name="open-prediction-trade";kind="ui";category="prediction";description='Prepare a BUY or SELL of shares in a prediction market (Polymarket) for the user to review and confirm in the order drawer, which shows the live price. Use for "bet $10 on Yes", "buy Yes on the Fed market", "mua 20$ c\u1EEDa Lula", "sell my Real Madrid shares", "b\xE1n h\u1EBFt c\u1ED5 ph\u1EA7n Trump". Market orders only. Needs the connected wallet with a Polymarket account (otherwise the setup card is shown). Do NOT use to browse or see odds \u2192 get-prediction-markets / get-prediction-market-detail.';parameters=[{name:"market",type:"string",description:'Which event. A "(prediction: <slug>)" hint, a polymarket.com link or the title of an event card already shown in the message \u2192 pass it VERBATIM. Otherwise the event as the user named it, in ENGLISH keywords ("Fed decision October").',required:!0},{name:"option",type:"string",description:'For an event with several options (candidates, price levels, dates): the one the user picked, as named ("Lula", "85,000", "No change"). Omit when the user did not name one.',required:!1},{name:"outcome",type:"string",description:'The side the user picked: "Yes", "No", or a team / name. Omit when not said.',required:!1},{name:"side",type:"string",description:'"buy" (bet on / mua) or "sell" (sell shares / b\xE1n).',required:!0},{name:"amount",type:"string",description:'ONLY when the user named it. BUY: USD to spend as a plain decimal ("10"). SELL: number of shares, or "all" to sell everything. Never invent or convert one.',required:!1},...ha];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=n?.walletAddress?.trim();if(!r||!zr(r))return{error:"wallet_not_connected",_instructions:"Trading prediction markets needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let o=["sell","ban"].includes(lt(String(t.side??"")))?"SELL":"BUY",{account:s,approvals:i}=await ys(r,this.service);if(s.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, which cannot sign orders here. Say so briefly in the user's language. Do NOT mention tool names."};if(!s.deployed||i?.isFullyApproved!==!0)return{ui:bs(s,i),hasPolymarketAccount:s.deployed,_instructions:s.deployed?"The Polymarket account is not fully set up for trading yet. A card that finishes the setup is ALREADY RENDERED below your reply. In ONE short sentence in the user's language, say the account needs to finish setup before trading. Do NOT mention tool names.":ya};let a=typeof t.market=="string"?t.market.trim():"",l=await AT(this.service,a,n?.query??"");if(l.kind==="unnamed"||l.kind==="not_found")return{found:!1,_instructions:l.kind==="unnamed"?"No market was named. Ask the user, in their language, which prediction market they want to trade.":`No open prediction market matching "${l.query}" was found. Say so briefly in the user's language and offer to search a related topic. Do NOT invent a market. Do NOT mention tool names.`};if(l.kind==="ambiguous"){let k=l.candidates.map(D=>Xd(D,t)).filter(D=>!!D);return{ui:{component:"PredictionMarketList",props:{sort:"relevance",category:null,query:l.query,events:k}},candidateCount:k.length,_instructions:[`"${l.query}" matches several prediction markets, so no order was prepared. They are ALREADY`,"RENDERED as cards below. Write your reply in TWO parts separated by a line containing exactly",`${jr} (once, on its own line): PART ONE \u2014 one short sentence asking which market they`,"mean; PART TWO \u2014 empty. Do NOT list the markets in text."].join(" ")}}let c=l.event,u=typeof t.option=="string"?t.option.trim():"",d=Pj(c,u,Xa(c)??null);if(!d){let k=fL(c),T=k.markets.some(D=>D.trade);return{ui:{component:"PredictionMarketDetail",props:k},title:c.title,open:T,_instructions:T?"This event has several options and the order needs ONE. The event is ALREADY RENDERED below with a buy button on every option. In ONE short sentence in the user's language, ask them to pick the option on the card. Do NOT claim an order was placed. Do NOT mention tool names.":"This prediction market is closed \u2014 it can no longer be traded. Say so in one sentence in the user's language. Do NOT mention tool names."}}let p=Zd(d),m=t.amount,g=o==="SELL"&&ET(m),f=Ej(d,typeof t.outcome=="string"?t.outcome:""),y=null;if(o==="SELL"){let k=(await this.service.getPositions(s.address,Ihe)).filter(D=>D.conditionId===d.conditionId&&D.shares>0&&!D.redeemable),T=(f>=0?k.find(D=>D.outcomeIndex===f):void 0)??(k.length===1?k[0]:void 0);if(!T)return{holdsShares:!1,market:d.question,_instructions:k.length>1?"The user holds several outcomes of this market. Ask, in their language, which one to sell. Do NOT mention tool names.":"The user holds no shares of this market's chosen outcome, so there is nothing to sell. Say so in one sentence in the user's language. Do NOT mention tool names."};f=T.outcomeIndex,y=Math.floor(T.shares*100)/100}let w={eventTitle:c.title,eventSlug:c.slug,url:c.url,image:c.image,marketLabel:c.markets.length===1?c.title:d.label,market:p,outcomeIndex:Math.max(0,f),side:o,amount:g?null:PT(m),sellAll:g,signer:r,wallet:s.address,endDate:d.endDate??c.endDate},v={component:"PredictionTradeCard",props:w},A=p.outcomes[w.outcomeIndex].label;return{ui:v,side:o,market:d.question,outcome:A,outcomeWasNamed:f>=0,amount:w.amount,sellAll:g,heldShares:y,_instructions:["The order is ALREADY RENDERED below your reply as a card; it opens the order screen with the LIVE price,","where the user reviews and confirms (one signature / NFC tap). In ONE or TWO short sentences in the",`user's language, say what is prepared (${o==="BUY"?"buying":"selling"} "${A}" in`,`"${d.question}"${w.amount?`, ${o==="BUY"?`$${w.amount}`:`${w.amount} shares`}`:""}),`,f>=0?"":"that they can switch the outcome on the card,","and that they confirm it there. Do NOT claim the order is placed or filled, do NOT state a price (it is","live on the card), do NOT give betting advice, and do NOT mention tool names.",ga].filter(Boolean).join(" ")}}};var ip=class extends K{name="open-prediction-withdraw";kind="ui";category="prediction";description='Open the card that WITHDRAWS cash from the user\'s Polymarket account back to their own wallet, as USDC or USDT on the chain they choose (Polygon, Base, Arbitrum, Ethereum, Optimism, BNB Chain\u2026). Use for "withdraw from Polymarket", "cash out my Polymarket", "r\xFAt ti\u1EC1n kh\u1ECFi Polymarket", "r\xFAt 20 USDC v\u1EC1 v\xED", "withdraw everything to Base". Needs the connected wallet; if the account is not set up yet the setup card is shown instead. Pass `amount` ONLY when the user named one ("all" for everything), and `chain` / `token` ONLY when named. Selling a position first is open-prediction-trade, not this.';parameters=[{name:"amount",type:"string",description:'USD amount to pre-fill as a plain decimal ("20", "12.5"), or "all" for the whole cash balance. ONLY when the user named one; never invent or convert one.',required:!1},{name:"chain",type:"string",description:'Destination chain the user named, in English ("Base", "Polygon", "Arbitrum", "Ethereum", "BNB Chain"). OMIT when not named \u2014 the card lets them pick.',required:!1},{name:"token",type:"string",description:'Destination stablecoin the user named ("USDC" or "USDT"). OMIT when not named.',required:!1}];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=n?.walletAddress?.trim();if(!r||!zr(r))return{error:"wallet_not_connected",_instructions:"Withdrawing from Polymarket needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let{account:o,approvals:s}=await ys(r,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, which cannot sign a withdrawal here; withdrawals are made from the wallet that owns it. Say so briefly in the user's language. Do NOT mention tool names."};if(!o.deployed)return{ui:bs(o,s),hasPolymarketAccount:!1,_instructions:ya};let[i,a]=await Promise.all([this.service.getBridgeAssets(),cd(o.address).catch(()=>null)]),l=vT(i);if(l.length===0)return{error:"withdraw_unavailable",_instructions:"Withdrawals are not available right now (the bridge lists no destination). Say so briefly in the user's language and suggest trying again later. Do NOT mention tool names."};let c=a===null?null:ST(a);return{ui:{component:"PredictionWithdrawCard",props:{signer:r,wallet:o.address,recipient:r,cashUsd:c,destinations:l,defaultDestination:Che(l,t.chain,t.token),prefillAmount:ET(t.amount)?"all":PT(t.amount)}},cashUsd:c,_instructions:["The withdraw card is ALREADY RENDERED below your reply: the user picks the chain and stablecoin, sees the","live quote (what arrives and the route cost) and confirms there; funds go to their own connected wallet.","Write ONE or TWO short sentences in the user's language:",c===null?"that they can withdraw their Polymarket cash with the card below.":c>0?`that they have $${c} cash available to withdraw with the card below.`:"that the account has no cash to withdraw right now \u2014 positions must be sold (or winnings claimed) first.","Do NOT claim a withdrawal was made or funds arrived, do NOT repeat addresses, and do NOT mention tool names."].join(" ")}}};function Che(e,t,n){let r=typeof t=="string"?lt(t).replace(/\bchain\b|\bmainnet\b/g,"").trim():"",o=typeof n=="string"?lt(n):"";if(!r&&!o)return null;let s=c=>{if(!r)return!0;let u=lt(c.chainName);return u===r||u.startsWith(r)||r.startsWith(u.split(" ")[0])},i=c=>!o||lt(c.symbol).startsWith(o),a=e.findIndex(c=>s(c)&&i(c));if(a>=0)return a;let l=e.findIndex(s);return l>=0?l:null}var CT="https://ipfs.pantograph.app/ipfs/",Dj=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function dc(e){let t=e?.trim();if(!t)return null;if(/^(https?:\/\/|data:image\/)/i.test(t))return t;let n=t.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return n?`${CT}${n[1]}`:Dj.test(t)?`${CT}${t}`:null}function Uj(e){let t=e?.trim();if(!t)return null;if(/^https?:\/\//i.test(t))return t;let n=t.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return n?`${CT}${n[1]}`:Dj.test(t)?`${CT}${t}`:null}function Bj(e){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(e)}function gL(e){if(!e||typeof e!="object")return;let t=e,n=t.image??t.image_url??t.imageUrl;return typeof n=="string"&&n.trim()?n.trim():void 0}function Nhe(e){if(typeof atob=="function"){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return new TextDecoder().decode(n)}if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Ohe(e){let t=e.match(/^data:application\/json([^,]*),(.*)$/is);if(!t)return null;let n=t[1]??"",r=t[2]??"";try{let o=/;base64/i.test(n)?Nhe(r):decodeURIComponent(r);return JSON.parse(o)}catch{try{return JSON.parse(r)}catch{return null}}}function Mj(e){let t=e?.trim();if(!t||!/^data:/i.test(t))return null;if(/^data:image\//i.test(t))return t;let n=Ohe(t);return n?dc(gL(n)):null}var Lhe=12,Dhe=6e3;async function Uhe(e,t,n){let r=new Array(e.length),o=0,s=new Array(Math.max(1,Math.min(t,e.length))).fill(0).map(async()=>{for(;o<e.length;){let i=o++;r[i]=await n(e[i],i)}});return await Promise.all(s),r}async function Bhe(e,t){try{let n=await se.get(e,{timeout:t});if(!n.ok)return null;let r=n.data;if(r&&typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return null}return null}catch{return null}}async function Mhe(e,t){let n=e?.trim();if(!n)return null;if(/^data:/i.test(n))return Mj(n);let r=Uj(n);if(!r)return null;if(Bj(r))return r;let o=await Bhe(r,t);if(o){let s=dc(gL(o));if(s)return s}return null}async function NT(e,t,n){if(t.length===0)return[];let r=n?.concurrency??Lhe,o=n?.timeoutMs??Dhe,s=await B1(e,t,n?.rpcUrl);return Uhe(s,r,i=>Mhe(i,o))}var Fj=100,Fhe=100,ap="{name}",qj="{chain}",lp=class extends K{name="get-wallet-nfts";description=`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`;category="nft";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n),s=o?[o]:nr(),i=Whe(t.contract_address),a=Vj(t.collection_name);return i||a?this.listNfts({address:r,chains:s,singleChain:!!o,contract:i,collectionName:a}):this.listCollections({address:r,chains:s,singleChain:!!o,args:t})}async listCollections(t){let{address:n,chains:r,singleChain:o,args:s}=t,i=await Promise.all(r.map(async c=>{let u=await this.service.getWalletNftCollections({address:n,chain:c,limit:Fj});return{chain:c,rows:u.success?Hj(u.data?.result??[]):[],ok:u.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFT collections"};let a=i.flatMap(c=>c.rows.map(u=>({name:Hhe(u),contractAddress:u.token_address,chain:j(c.chain),nftCount:u.count??null})));if(a.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:n,collectionCount:0,collections:[]};let l=Vhe(a,s);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:n,collectionCount:a.length,collections:a,...l.length>0?{actionButtons:l}:{}}}async listNfts(t){let{address:n,chains:r,singleChain:o,contract:s,collectionName:i}=t,a=await Promise.all(r.map(async m=>{let g=await this.service.getWalletNFTs({address:n,chain:m,limit:Fj,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:g.success?Hj(g.data?.result??[]):[],ok:g.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=a.flatMap(m=>m.rows.filter(g=>qhe(g,{contract:s,collectionName:i})).map(g=>({chain:m.chain,row:g})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${i??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||i||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:m,row:g},f)=>{let y=$he(g);return{name:y.name,tokenId:y.tokenId,contractAddress:y.contractAddress,image:u[f]??y.image,chain:j(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:n,collectionName:c,nfts:d}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:n,collectionName:c,nftCount:l.length}}async resolveOnchainImages(t){let n=new Array(t.length).fill(null),r=new Map;t.forEach((o,s)=>{let i=r.get(o.chain)??[];i.push(s),r.set(o.chain,i)});try{await Promise.all([...r.entries()].map(async([o,s])=>{let i=s.map(l=>({contract:t[l].row.token_address,tokenId:t[l].row.token_id})),a=await NT(o,i);s.forEach((l,c)=>{n[l]=a[c]??null})}))}catch{}return n}};function Hj(e){return e.filter(t=>(t.contract_type||"").toUpperCase()==="ERC721")}function qhe(e,t){if(t.contract)return e.token_address.toLowerCase()===t.contract.toLowerCase();if(t.collectionName){let n=t.collectionName.toLowerCase();return(e.name??"").toLowerCase().includes(n)}return!1}function Hhe(e){let t=e.name?.trim();if(t)return t;let n=e.token_address??"";return n.length>10?`${n.slice(0,6)}\u2026${n.slice(-4)}`:n}function $he(e){return{name:e.normalized_metadata?.name||e.name||`#${e.token_id}`,tokenId:e.token_id,contractAddress:e.token_address,image:dc(e.normalized_metadata?.image||e.media?.original_media_url)}}function Vhe(e,t){let n=typeof t.pick_button_label=="string"?t.pick_button_label:"",r=typeof t.pick_prompt_template=="string"?t.pick_prompt_template:"",o=[];for(let s of e){if(o.length>=Fhe)break;if(!s.contractAddress)continue;let i=typeof s.chain=="string"?s.chain.trim():"",a=i?`show my ${ap} NFTs on ${qj}`:`show my ${ap} NFTs`,l=$j(r,{[ap]:s.name,[qj]:i},a);i&&!l.includes(i)&&(l=`${l} (${i})`),o.push({label:jhe(n,s.name,ap),prompt:`${l} (${s.contractAddress})`})}return o}function $j(e,t,n){let r=e&&e.includes(ap)?e:n;for(let[o,s]of Object.entries(t))r=r.split(o).join(s);return r.replace(/\s+/g," ").trim()}function jhe(e,t,n){return $j(e,{[ap]:t},n)}function Vj(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}function Whe(e){let t=Vj(e);return t&&/^0x[a-fA-F0-9]{40}$/.test(t)?t:void 0}var zhe="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",ws=class extends K{kind="data";category="nft";llm;constructor(t){super(),this.llm=new jt(t??{})}static promptParams(t){return[{name:"prompt",type:"string",description:t,required:!0}]}async run(t){let n=typeof t.prompt=="string"?t.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=await this.askGeminiWithSearch(n);return r?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:r}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(t){let n=Date.now();try{return(await this.llm.chat([{role:"system",content:zhe,timestamp:n},{role:"user",content:t,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var cp=class extends ws{name="get-nft-contract-info";description='Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.';parameters=ws.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`);presentInstructions="Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks."};var up=class extends ws{name="get-nft-metadata";description='Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.';parameters=ws.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`);presentInstructions="Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points."};var yL={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},bL="amazon.com";function Ghe(e){return e?e.trim().toLowerCase().split(/[-_]/)[0]:""}function wL(e){let t=Ghe(e);return yL[t]??bL}function OT(e){return`https://${wL(e)}/s?k=NFC%20Tag`}function LT(e){if(!e)return"";let t=e.trim().toUpperCase().split(/[-_]/),n=t.length>1?t[t.length-1]:t[0];return/^[A-Z]{2}$/.test(n)?n:""}var Khe=720*60*1e3,jj=new Map,Wj=3;function Yhe(e){return[`A user in country "${e}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Wj} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function Qhe(e){if(!e)return[];let t=e.indexOf("["),n=e.lastIndexOf("]");if(t===-1||n===-1||n<=t)return[];let r;try{r=JSON.parse(e.slice(t,n+1))}catch{return[]}if(!Array.isArray(r))return[];let o=[],s=new Set;for(let i of r){if(!i||typeof i!="object")continue;let a=i.label,l=i.url;if(typeof a!="string"||!a.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!s.has(c)&&(s.add(c),o.push({label:a.trim(),url:l.trim()}),o.length>=Wj))break}return o}async function vL(e,t){let n=LT(e);if(!n||!t)return null;let r=jj.get(n);if(r&&r.expires>Date.now())return r.links;let o=Date.now(),s=[{role:"user",content:Yhe(n),timestamp:o}];try{let i=await t.chat(s,void 0,{googleSearch:!0,maxRetries:1}),a=Qhe(i.text);if(a.length)return jj.set(n,{links:a,expires:Date.now()+Khe}),a}catch{}return null}async function dp(e){let t=await vL(e.country,e.llm);return t&&t.length?t:[{label:"Amazon",url:OT(e.language)}]}function Xhe(e){return e.length<=1?e.length===1?`[${e[0].label}](${e[0].url})`:"":e.map((t,n)=>`${n+1}. [${t.label}](${t.url})`).join(`
|
|
49
|
+
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:r?j(r):"all",timeFrame:s??null,count:c.length,tokens:c}}};function fu(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,r=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(r+"00").slice(0,2)}`}function gu(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<=0))return`($${fu(e)})`}var yu=class extends K{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n);if(o){let a=await this.service.getWalletTokenBalances({address:r,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return a.success?this.renderBalances(r,o,a.data?.result||[]):{error:a.error||"Failed to fetch token balances"}}let s=nr(),i=await Promise.all(s.map(async a=>{let l=await this.service.getWalletTokenBalances({address:r,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:a,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(r,i)}toTokenLine(t){let n=t.name||t.symbol||"Unknown",r=t.balance_formatted??"0",o=t.symbol||"",s=typeof t.usd_value=="number"?`$${fu(t.usd_value)}`:"$-";return`- ${n}: ${r} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(t,n,r){let o=r.reduce((s,i)=>s+(i.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:t,chain:n,totalUsdValue:`$${fu(o)}`,tokens:r.map(s=>this.toTokenLine(s))}}renderBalancesByChain(t,n){let r=n.map(s=>{let i=s.tokens.reduce((l,c)=>l+(c.usd_value||0),0),a=s.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:j(s.chain),total:i,tokens:a}}).filter(s=>s.tokens.length>0).sort((s,i)=>i.total-s.total),o=r.reduce((s,i)=>s+i.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:t,chain:"all",totalUsdValue:`$${fu(o)}`,chains:r.map(s=>({chain:s.chain,totalUsdValue:`$${fu(s.total)}`,tokens:s.tokens.map(i=>this.toTokenLine(i))}))}}};var bu=class extends K{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=rn(t.chain,n),s=typeof t.fromDate=="string"&&t.fromDate?t.fromDate:void 0,i=typeof t.toDate=="string"&&t.toDate?t.toDate:void 0,a=typeof t.fromBlock=="number"?t.fromBlock:typeof t.fromBlock=="string"&&t.fromBlock?Number(t.fromBlock):void 0,l=typeof t.toBlock=="number"?t.toBlock:typeof t.toBlock=="string"&&t.toBlock?Number(t.toBlock):void 0,c=Number.isFinite(a)?a:void 0,u=Number.isFinite(l)?l:void 0,d=typeof t.cursor=="string"&&t.cursor?t.cursor:void 0,m=(typeof t.order=="string"?t.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",g=typeof t.includeInternalTransactions=="boolean"?t.includeInternalTransactions:void 0,f=typeof t.nftMetadata=="boolean"?t.nftMetadata:void 0,y=typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,w=Number.isFinite(y)&&y>0?y:10,v=await this.service.getWalletHistory({address:r,chain:o,limit:w,fromDate:s,toDate:i,fromBlock:c,toBlock:u,cursor:d,order:m,includeInternalTransactions:g,nftMetadata:f});if(!v.success)return{error:v.error||"Failed to fetch wallet history"};let k=(v.data?.result||[]).map(T=>{let D=K1(o,T.hash);return D?{...T,explorerUrl:D}:T});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:r,chain:o||"default",pagination:{cursor:v.data?.cursor??null,hasMore:!!v.data?.cursor},transactionCount:k.length,transactions:k}}};function hK(e){if(e.value_decimal)return e.value_decimal;let t=parseInt(e.token_decimals??"18",10);if(isNaN(t)||t===0)return e.value;try{let n=BigInt(e.value),r=BigInt(10)**BigInt(t),o=n/r,i=(n%r).toString().padStart(t,"0").replace(/0+$/,"");return i?`${o}.${i}`:`${o}`}catch{return e.value}}var wu=class extends K{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=rn(t.chain,n),s=typeof t.limit=="number"?t.limit:Number(t.limit),i=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,a=typeof t.fromDate=="string"&&t.fromDate?t.fromDate:void 0,l=typeof t.toDate=="string"&&t.toDate?t.toDate:void 0,c=this.parseBlock(t.fromBlock),u=this.parseBlock(t.toBlock),d=typeof t.cursor=="string"&&t.cursor?t.cursor:void 0,m=(typeof t.order=="string"?t.order.toUpperCase():"")==="ASC"?"ASC":"DESC",g=typeof t.direction=="string"?t.direction.trim().toLowerCase():"all",f=g==="send"?"send":g==="receive"?"receive":"all",y=typeof t.tokenSymbol=="string"&&t.tokenSymbol?t.tokenSymbol.trim():void 0,w=Array.isArray(t.contractAddresses)?t.contractAddresses.filter(te=>typeof te=="string"&&!!te).map(te=>te.trim()):void 0,v,A;if(y){let te=await this.resolveContractAddressBySymbol(y,r,o);te&&(w=[te.address],v=te.symbol,A=te.name)}let k=await this.service.getWalletTokenTransfers({address:r,chain:o,contractAddresses:w,limit:i,fromDate:a,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let T=r.toLowerCase(),q=(k.data?.result||[]).map(te=>{let de=te.from_address.toLowerCase()===T,oe=de?"send":"receive",F=de?te.to_address:te.from_address,z=de?te.to_address_label??void 0:te.from_address_label??void 0,_=de?te.to_address_entity??void 0:te.from_address_entity??void 0;return{...te,direction:oe,amount_formatted:hK(te),counterparty:F,counterparty_label:z,counterparty_entity:_}}),V=f==="all"?q:q.filter(te=>te.direction===f);if(y&&!w){let te=y.toLowerCase();V=V.filter(de=>(de.token_symbol??"").toLowerCase()===te)}let Y=this.buildCounterparties(V);return{walletAddress:r,chain:o||"default",resolvedToken:v?{symbol:v,name:A,contractAddress:w?.[0]}:null,filters:{tokenSymbol:y||null,contractAddresses:w||null,direction:f,limit:i,order:m,fromDate:a||null,toDate:l||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??i,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:V.length,transfers:V,counterparties:Y}}async resolveContractAddressBySymbol(t,n,r){let o=t.toLowerCase(),s=await this.service.getWalletTokenBalances({address:n,chain:r});if(s.success&&s.data?.result?.length){let a=s.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}let i=await this.service.searchTokensByKey({key:t,chain:r});if(i.success&&i.data?.length){let l=i.data.find(c=>(c.symbol??"").toLowerCase()===o)??i.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(t){let n=new Map,r=new Map;for(let s of t){let i=s.direction==="send"?n:r,a=s.counterparty.toLowerCase(),l=parseFloat(s.amount_formatted)||0,c=i.get(a);c?(c.total+=l,c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):i.set(a,{label:s.counterparty_label,entity:s.counterparty_entity,total:l,count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((i,a)=>a[1].count-i[1].count).map(([i,a])=>({address:i,label:a.label,entity:a.entity,total_amount:a.total.toFixed(6).replace(/\.?0+$/,""),tx_count:a.count,first_seen:a.first,last_seen:a.last}));return{sent:o(n),received:o(r)}}parseBlock(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t=="string"&&t){let n=Number(t);return Number.isFinite(n)?n:void 0}}};var vu=class extends K{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=rn(t.chain,n),s=typeof t.limit=="number"?t.limit:Number(t.limit),i=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,a=typeof t.fromDate=="string"&&t.fromDate?t.fromDate:void 0,l=typeof t.toDate=="string"&&t.toDate?t.toDate:void 0,c=this.parseBlock(t.fromBlock),u=this.parseBlock(t.toBlock),d=typeof t.cursor=="string"&&t.cursor?t.cursor:void 0,m=(typeof t.order=="string"?t.order.toUpperCase():"")==="ASC"?"ASC":"DESC",g=typeof t.includePrices=="boolean"?t.includePrices:void 0,f=typeof t.direction=="string"?t.direction.trim().toLowerCase():"all",y=f==="send"?"send":f==="receive"?"receive":"all",w=Array.isArray(t.contractAddresses)?t.contractAddresses.filter(V=>typeof V=="string"&&!!V).map(V=>V.trim()):void 0,v=await this.service.getWalletNftTransfers({address:r,chain:o,contractAddresses:w,limit:i,fromDate:a,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m,includePrices:g});if(!v.success)return{error:v.error||"Failed to fetch NFT transfers"};let A=r.toLowerCase(),T=(v.data?.result||[]).map(V=>{let Y=V.from_address.toLowerCase()===A,te=Y?"send":"receive",de=Y?V.to_address:V.from_address,oe=Y?V.to_address_label??void 0:V.from_address_label??void 0,F=Y?V.to_address_entity??void 0:V.from_address_entity??void 0;return{...V,direction:te,counterparty:de,counterparty_label:oe,counterparty_entity:F}}),D=y==="all"?T:T.filter(V=>V.direction===y),q=this.buildCounterparties(D);return{walletAddress:r,chain:o||"default",filters:{contractAddresses:w||null,direction:y,limit:i,order:m,fromDate:a||null,toDate:l||null,fromBlock:c??null,toBlock:u??null,includePrices:g??null},pagination:{cursor:v.data?.cursor??null,pageSize:v.data?.page_size??i,page:v.data?.page??null,hasMore:!!v.data?.cursor},transferCount:D.length,transfers:D,counterparties:q}}buildCounterparties(t){let n=new Map,r=new Map;for(let s of t){let i=s.direction==="send"?n:r,a=s.counterparty.toLowerCase(),l=s.token_name??s.token_address,c=i.get(a);c?(c.tokenIds.add(s.token_id),c.collections.add(l),c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):i.set(a,{label:s.counterparty_label,entity:s.counterparty_entity,tokenIds:new Set([s.token_id]),collections:new Set([l]),count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((i,a)=>a[1].count-i[1].count).map(([i,a])=>({address:i,label:a.label,entity:a.entity,token_ids:Array.from(a.tokenIds),collections:Array.from(a.collections),tx_count:a.count,first_seen:a.first,last_seen:a.last}));return{sent:o(n),received:o(r)}}parseBlock(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t=="string"&&t){let n=Number(t);return Number.isFinite(n)?n:void 0}}};var fK=["all","7","30","60","90"],ku=class extends K{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n),s=typeof t.days=="string"?t.days.trim().toLowerCase():"",i=fK.includes(s)?s:void 0;if(o){let f=await this.service.getWalletPnlSummary({address:r,chain:o,days:i});return f.success?{walletAddress:r,chain:o,days:i??"all",summary:this.mapSummary(f.data)}:{error:f.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(nr().map(async f=>{let y=await this.service.getWalletPnlSummary({address:r,chain:f,days:i});return{chain:f,data:y.success?y.data:void 0}}))).flatMap(f=>f.data&&f.data.total_count_of_trades>0?[{chain:f.chain,data:f.data}]:[]),c=l.map(f=>({chain:j(f.chain),summary:this.mapSummary(f.data)})),u=l.reduce((f,y)=>f+Number(y.data.total_realized_profit_usd||0),0),d=l.reduce((f,y)=>f+Number(y.data.total_bought_volume_usd||0),0),p=l.reduce((f,y)=>f+Number(y.data.total_sold_volume_usd||0),0),m=l.reduce((f,y)=>f+Number(y.data.total_trade_volume||0),0),g={totalCountOfTrades:l.reduce((f,y)=>f+y.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:l.reduce((f,y)=>f+y.data.total_buys,0),totalSells:l.reduce((f,y)=>f+y.data.total_sells,0),totalBoughtVolumeUsd:d,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:r,chain:"all",days:i??"all",summary:g,chains:c}}mapSummary(t){return{totalCountOfTrades:t.total_count_of_trades,totalTradeVolume:t.total_trade_volume,totalRealizedProfitUsd:t.total_realized_profit_usd,totalRealizedProfitPercentage:t.total_realized_profit_percentage,totalBuys:t.total_buys,totalSells:t.total_sells,totalBoughtVolumeUsd:t.total_bought_volume_usd,totalSoldVolumeUsd:t.total_sold_volume_usd}}};var gK=["all","7","30","60","90"],yy=25,xu=class extends K{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${yy}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${yy}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${yy}.`,required:!1,items:{type:"string"}}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n),s=typeof t.days=="string"?t.days.trim().toLowerCase():"",i=gK.includes(s)?s:void 0,a=Array.isArray(t.tokenSymbols)?t.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],l=Array.isArray(t.tokenAddresses)?t.tokenAddresses.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[];if(o){let d=await this.fetchChainPnl(r,o,i,a,l);return d.ok?{walletAddress:r,chain:o,days:i??"all",filters:{tokenAddresses:d.tokenAddresses??null,resolvedSymbols:d.resolvedFromSymbols.length>0?d.resolvedFromSymbols:null,unresolvedSymbols:d.unresolvedSymbols.length>0?d.unresolvedSymbols:null},tokenCount:d.tokens.length,tokens:d.tokens}:{error:d.error||"Failed to fetch wallet PnL"}}let u=(await Promise.all(nr().map(async d=>({chain:d,res:await this.fetchChainPnl(r,d,i,a,l)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:j(d.chain),tokenCount:d.res.tokens.length,tokens:d.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:r,chain:"all",days:i??"all",filters:{requestedSymbols:a.length>0?a:null,requestedAddresses:l.length>0?l:null},tokenCount:u.reduce((d,p)=>d+p.tokenCount,0),chains:u}}async fetchChainPnl(t,n,r,o,s){let i=[],a=[];o.length>0&&(await Promise.all(o.map(p=>this.resolveContractAddress(p,n,t)))).forEach((p,m)=>{p?i.push({symbol:o[m],address:p.address}):a.push(o[m])});let l=yK([...i.map(d=>d.address),...s]).slice(0,yy),c=l.length>0?l:void 0,u=await this.service.getWalletPnl({address:t,chain:n,days:r,tokenAddresses:c});return{ok:u.success,error:u.error,tokens:u.data?.result??[],tokenAddresses:c,resolvedFromSymbols:i,unresolvedSymbols:a}}async resolveContractAddress(t,n,r){let o=t.toLowerCase();if(r){let i=await this.service.getWalletTokenBalances({address:r,chain:n});if(i.success&&i.data?.result?.length){let a=i.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let s=await this.service.searchTokensByKey({key:t,chain:n});if(s.success&&s.data?.length){let a=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};function yK(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}var bK=BigInt(2)**BigInt(255),Au=class extends K{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=rn(t.chain,n),s=typeof t.limit=="number"?t.limit:Number(t.limit),i=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):100,a=typeof t.cursor=="string"&&t.cursor?t.cursor:void 0,l=await this.service.getWalletApprovals({address:r,chain:o,limit:i,cursor:a});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,d=(c.result||[]).map(f=>wK(f)),p=0,m=0,g=[];for(let f of d){f.isUnlimited&&(m+=1);let y=parseFloat(f.token.usdAtRisk??"");Number.isFinite(y)&&(p+=y);let w=f.token.possibleSpam||f.token.verifiedContract===!1,v=!f.spender.label&&!f.spender.entity;(w||f.isUnlimited&&v)&&g.push(f)}return{walletAddress:r,chain:o||"default",filters:{limit:i,cursor:a??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??i,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:g.length},approvals:d,riskyApprovals:g}}};function wK(e){let t=vK(e.value);return{blockNumber:e.block_number,blockTimestamp:e.block_timestamp??null,transactionHash:e.transaction_hash??null,value:e.value,valueFormatted:e.value_formatted??null,isUnlimited:t,token:{address:e.token.address,addressLabel:e.token.address_label??null,name:e.token.name??null,symbol:e.token.symbol??null,logo:e.token.logo??null,possibleSpam:!!e.token.possible_spam,verifiedContract:e.token.verified_contract??null,currentBalance:e.token.current_balance??null,currentBalanceFormatted:e.token.current_balance_formatted??null,usdPrice:e.token.usd_price??null,usdAtRisk:e.token.usd_at_risk??null},spender:{address:e.spender.address,label:e.spender.address_label??null,entity:e.spender.entity??null,entityLogo:e.spender.entity_logo??null}}}function vK(e){if(!e)return!1;try{return BigInt(e)>=bK}catch{return!1}}var pD=.01,Tu=class extends K{name="get-wallet-defi-positions";description=`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n);if(o){let a=await this.service.getWalletDefiPositions({address:r,chain:o});if(!a.success)return{error:a.error||"Failed to fetch wallet DeFi positions"};let l=(a.data||[]).filter(mD);return{walletAddress:r,chain:o,positionCount:l.length,positions:l.map(hD)}}let i=(await Promise.all(nr().map(async a=>{let l=await this.service.getWalletDefiPositions({address:r,chain:a});return{chain:a,rows:l.success?(l.data||[]).filter(mD):[]}}))).filter(a=>a.rows.length>0).map(a=>({chain:j(a.chain),positionCount:a.rows.length,positions:a.rows.map(hD)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:r,chain:"all",positionCount:i.reduce((a,l)=>a+l.positionCount,0),chains:i}}};function mD(e){let t=e.position?.balance_usd,n=e.position?.total_unclaimed_usd_value;return typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=pD?!0:typeof n=="number"&&n>=pD}function hD(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,accountHealthFactor:e.account_data?.health_factor??null,position:kK(e.position)}}function kK(e){return{label:e.label,address:e.address,balanceUsd:e.balance_usd,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,tokens:(e.tokens||[]).map(t=>({tokenType:t.token_type,name:t.name,symbol:t.symbol,contractAddress:t.contract_address,decimals:t.decimals,logo:t.logo,thumbnail:t.thumbnail,balance:t.balance,balanceFormatted:t.balance_formatted,usdPrice:t.usd_price,usdValue:t.usd_value})),details:e.position_details??null}}var Su=class extends K{name="get-wallet-defi-protocol-positions";description=`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=t.protocol?.trim();if(!r)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=gt(t.address,n),s=at(t.chain,n);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,chain:s});return l.success?l.data?{walletAddress:o,chain:s,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let a=(await Promise.all(nr().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:j(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${r} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:r,totalUsdValue:a.reduce((l,c)=>l+c.totalUsdValue,0),chains:a}}protocolFields(t){return{protocolName:t.protocol_name,protocolId:t.protocol_id,protocolUrl:t.protocol_url,protocolLogo:t.protocol_logo,totalUsdValue:t.total_usd_value,totalUnclaimedUsdValue:t.total_unclaimed_usd_value,accountHealthFactor:t.account_data?.health_factor??null,positionCount:(t.positions||[]).length,positions:(t.positions||[]).map(xK)}}};function xK(e){return{label:e.label,address:e.address,balanceUsd:e.balance_usd,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,tokens:(e.tokens||[]).map(t=>({tokenType:t.token_type,name:t.name,symbol:t.symbol,contractAddress:t.contract_address,decimals:t.decimals,logo:t.logo,thumbnail:t.thumbnail,balance:t.balance,balanceFormatted:t.balance_formatted,usdPrice:t.usd_price,usdValue:t.usd_value})),details:e.position_details??null}}function AK(e){try{return(Number(BigInt(e))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return e}}var Pu=class extends K{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=t.transactionHash;if(!r)return{error:"Transaction hash is required."};let o=rn(t.chain,n),s=await this.service.getTransactionByHash({transactionHash:r,chain:o});if(!s.success||!s.data)return{error:s.error||"Failed to fetch transaction"};let i=s.data,a=(i.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=i.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:i.hash,status:i.receipt_status==="1"?"success":i.receipt_status==="0"?"failed":"unknown",timestamp:i.block_timestamp,blockNumber:i.block_number,from:{address:i.from_address,label:i.from_address_label||null,entity:i.from_address_entity||null},to:i.to_address?{address:i.to_address,label:i.to_address_label||null,entity:i.to_address_entity||null}:null,valueEth:AK(i.value||"0"),fee:i.transaction_fee,gasUsed:i.receipt_gas_used,gasPriceGwei:i.gas_price?(Number(i.gas_price)/1e9).toFixed(4):null,decodedCall:i.decoded_call?{signature:i.decoded_call.signature,label:i.decoded_call.label,params:i.decoded_call.params}:null,decodedEvents:a,contractCreated:i.receipt_contract_address||null,logs:l}}};var fD=new Map;function TK(e){let t=fD.get(e);if(t)return t;let n=Ii({rpcUrl:e});return fD.set(e,n),n}async function gD(e,t,n=[]){let r=await TK(e).rpc(t,n);if(r===void 0)throw new Error(`RPC ${t}: empty result`);return r}function yD(e,t,n){return gD(e,"eth_call",[{to:t,data:n},"latest"])}async function SK(e,t,n){let r=$o(e);if(!r)return null;try{return await yD(r,t,n)}catch{return null}}function Te(e,t){globalThis.__LENDING_DEBUG__!==!1&&(t===void 0?console.log(`[LEND] ${e}`):console.log(`[LEND] ${e}`,JSON.stringify(t,PK)))}function PK(e,t){return typeof t=="bigint"?`${t}n`:t}var EK=6e4,vP=new Map;async function Mm(e,t){let n=Os(t),r=n?parseInt(n,16):NaN;if(!n||!Number.isFinite(r))return[];let o=`${e}|${n}`,s=vP.get(o);if(s&&Date.now()-s.at<EK)return s.markets;let i=RK(e,n,r),a=i.then(l=>l.markets);return vP.set(o,{at:Date.now(),markets:a}),i.then(l=>{l.answered||vP.delete(o)}),a}async function by(e,t){return(await Mm(e,t)).length>0}async function RK(e,t,n){try{let r=`${e}/supply/v2?chainId=${n}&limit=100&page=1`;Te("catalog: GET",r);let o=await se.get(r);if(!o.ok){let i=o.status>=400&&o.status<500;return Te(i?"catalog: chain not served":"catalog: FAILED",{chain:t,status:o.status,message:he(o)}),{markets:[],answered:i}}let s=(o.data?.data?.items||[]).flatMap(i=>{let a=_K(i,t);return a?[a]:[]});return Te("catalog: got markets",{chain:t,rawItems:o.data?.data?.items?.length??0,usable:s.length,tokens:s.map(i=>i.token)}),{markets:s,answered:!0}}catch(r){return Te("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:t,message:r?.message}),{markets:[],answered:!1}}}function bD(e,t){let n=t.trim().toLowerCase();if(!n)return[];if(ge(n))return e.filter(o=>o.contract===n||o.token===n);let r=e.filter(o=>o.name.trim().toLowerCase()===n);return r.length>0?r:e.filter(o=>{let s=o.name.trim().toLowerCase(),i=o.protocol.trim().toLowerCase();return s.includes(n)||n.includes(s)||i.includes(n)||n.includes(i)})}function _K(e,t){if(e?.isDeleted===!0)return null;let n=typeof e?.contract=="string"?e.contract.toLowerCase():"";if(!ge(n))return null;let r=typeof e?.token=="string"&&ge(e.token)?e.token.toLowerCase():n,o=Number(e?.rating?.balanceScore),s=e?.type?.trim()||"unknown";return{chain:t,name:e?.name?.trim()||"USDC lending market",protocol:e?.protocolId?.name?.trim()||"Unknown",protocolLabel:yr(s),protocolUrl:e?.protocolId?.domain?.trim()||null,type:s,contract:n,token:r,platformScore:Number.isFinite(o)?o:null}}function kP(){return nr()}async function wy(e){let t=kP(),n=await Promise.all(t.map(r=>by(e,r)));return t.filter((r,o)=>n[o])}async function vy(e,t){let n=Ce(t);return n?by(e,n):!1}async function wD(e,t){let n=t.map(s=>Ce(s)).filter(s=>!!s),r=[...new Set(n)],o=await Promise.all(r.map(s=>by(e,s)));return r.filter((s,i)=>o[i])}function Ka(e){return Nm(e)}var vD=6;async function kD(e,t,n){let r=t.map(A=>ge(A)?A.toLowerCase():null);if(r.every(A=>A===null))return Te("discovery: ABORT \u2014 no valid token address",{tokens:t}),t.map(()=>null);let o=hy(e),s;try{Te("discovery: probing 5 accessors per token",{chain:e,tokens:r,psm:o}),s=await Qt(e,[...r.flatMap(A=>A?IK(A):[]),...o?oD(o):[]])}catch(A){return Te("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:e,message:A?.message}),t.map(()=>null)}let i=o?s.slice(s.length-sD):[],a=Ge(i[0])?.toLowerCase()??null,l=Ge(i[1]),c=Ge(i[2]),u=a&&l&&c?{susds:a,usds:l,oracle:c}:null;o&&Te("discovery: PSM3 lookup",{psm:o,susds:a,usds:l,oracle:c});let d=0,p=r.map(A=>{if(!A)return null;let k=s.slice(d,d+vD);return d+=vD,Te("discovery: probe answers",{token:A,"POOL()":Ge(k[0]),"UNDERLYING_ASSET_ADDRESS()":Ge(k[1]),"baseToken()":Ge(k[2]),"asset()":Ge(k[3]),"vsr()":ft(k[4])?.toString()??null,"manager()":Ge(k[5])}),{token:A,slice:k}}),m=new Set;for(let A of p){if(!A)continue;let k=Ge(A.slice[0]);k&&Ge(A.slice[1])&&m.add(k.toLowerCase())}let g=await CK(e,[...m]);m.size>0&&Te("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let f=new Map;for(let A of p){if(!A||Ge(A.slice[0])&&Ge(A.slice[1])||Ge(A.slice[2])||!Ge(A.slice[3]))continue;let T=Ge(A.slice[5]);T&&f.set(A.token,T.toLowerCase())}let y=await NK(e,f);f.size>0&&Te("discovery: Maple manager authentication",{claimed:[...f.keys()],genuine:[...y]});let w=p.flatMap(A=>A?Ge(A.slice[0])&&Ge(A.slice[1])||Ge(A.slice[2])?[]:y.has(A.token)?[]:Ge(A.slice[3])?[A.token]:[]:[]),v=await OK(e,[...new Set(w)],n);return w.length>0&&Te("discovery: Morpho vault lookup",{asked:[...new Set(w)],recognised:[...v.keys()]}),p.map(A=>{if(!A)return null;let{token:k,slice:T}=A,D={chain:e,protocolUrl:null,token:k,platformScore:null};if(u&&k===u.susds)return Te("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...D,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:yr("spark-l2-susds"),protocolUrl:Ka("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let q=Ge(T[0]);if(q&&Ge(T[1])){let V=g.has(q.toLowerCase());return Te("discovery: classified",{token:k,as:V?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:q}),V?{...D,name:"Aave v3",protocol:"AAVE",protocolLabel:yr("aave-v3"),protocolUrl:Ka("aave-v3"),type:"aave-v3",contract:q}:null}if(Ge(T[2]))return Te("discovery: classified",{token:k,as:"compound-v3"}),{...D,name:"Compound v3",protocol:"COMPOUND",protocolLabel:yr("compound-v3"),protocolUrl:Ka("compound-v3"),type:"compound-v3",contract:k};if(Ge(T[3])){if(y.has(k))return Te("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...D,name:"Maple",protocol:"MAPLE",protocolLabel:yr("maple"),protocolUrl:Ka("maple"),type:"maple",contract:k};if(v.has(k)){Te("discovery: classified",{token:k,as:"morpho-v2"});let te=v.get(k)||"Morpho V2";return{...D,name:te,protocol:"MORPHO",protocolLabel:yr("morpho-v2"),protocolUrl:Ka("morpho-v2"),type:"morpho-v2",contract:k}}let Y=ft(T[4])!==null;return Te("discovery: classified",{token:k,as:Y?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),Y?{...D,name:"Spark",protocol:"SPARK",protocolLabel:yr("spark-ethereum"),protocolUrl:Ka("spark-ethereum"),type:"spark-ethereum",contract:k}:{...D,name:"Spark",protocol:"SPARK",protocolLabel:yr("spark"),protocolUrl:Ka("spark"),type:"spark",contract:k}}return Te("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function IK(e){return[{target:e,callData:Le({abi:su,functionName:"POOL"})},{target:e,callData:Le({abi:su,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:e,callData:Le({abi:Ns,functionName:"baseToken"})},{target:e,callData:Le({abi:Mo,functionName:"asset"})},{target:e,callData:Le({abi:iu,functionName:"vsr"})},{target:e,callData:Le({abi:hP,functionName:"manager"})}]}async function CK(e,t){if(t.length===0)return new Set;try{let n=await Qt(e,t.map(r=>({target:r,callData:Le({abi:dP,functionName:"ADDRESSES_PROVIDER"})})));return new Set(t.filter((r,o)=>Ge(n[o])!==null))}catch{return new Set}}async function NK(e,t){if(t.size===0)return new Set;let n=[...t.entries()];try{let r=await Qt(e,n.map(([,o])=>({target:o,callData:Le({abi:fP,functionName:"pool"})})));return new Set(n.filter(([o],s)=>Ge(r[s])?.toLowerCase()===o.toLowerCase()).map(([o])=>o))}catch{return new Set}}async function OK(e,t,n){let r=parseInt(e,16);if(t.length===0||!Number.isFinite(r))return new Map;let o=await Promise.all(t.map(async s=>{try{let i=await se.post(n,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:r}}),a=i.ok?i.data?.data?.vaultV2ByAddress:null;return a?[s,a.name?.trim()||""]:null}catch{return null}}));return new Map(o.filter(s=>s!==null))}var LK=.01;function DK(e){return e.reduce((t,n)=>n.conditions===null?t+n.apyPercent:t,0)}function UK(e,t){if(typeof t!="string"||!t.trim())return;let n=t.trim(),r=gm();r[e]!==n&&Ma({...r,[e]:n})}var Eu=class{constructor(t,n,r){this.coinPoolBaseUrl=t;this.endpoints=n;this.describer=r}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(t,n,r){let o=Date.now();Te("describeReceiptTokens: START",{chain:t,tokens:n,hasRpcUrl:!!r});let s=Os(t);s&&UK(s,r);let i=s?Om(s):null,a=[...new Set(n.filter(ge).map(p=>p.toLowerCase()))];if(Te("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!i,wanted:a}),!s||!i||a.length===0)return Te("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!i,wantedCount:a.length}),new Map;Te("describeReceiptTokens: on-chain discovery for",a);let l=await kD(s,a,this.endpoints.morphoApiUrl),u=[...new Map(a.flatMap((p,m)=>{let g=l[m];return Te("describeReceiptTokens: discovery result",{token:p,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[p,g]]:[]})).entries()];if(u.length===0)return Te("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;Te("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([p,m])=>({token:p,type:m.type,contract:m.contract}))});let d=await this.describer.describe(s,i,u.map(([,p])=>p));return Te("describeReceiptTokens: DONE",{ms:Date.now()-o,overviews:d.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(d.map((p,m)=>[u[m][0],p]))}async findMarketByReceiptToken(t,n,r){if(Te("findMarketByReceiptToken: called",{chain:t,receiptToken:n,hasRpcUrl:!!r}),!ge(n))return Te("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:n}),null;let s=(await this.describeReceiptTokens(t,[n],r)).get(n.toLowerCase())??null;return Te("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(t){if(!ge(t.address))return[];let n=await wD(this.coinPoolBaseUrl,t.chains);return(await Promise.all(n.map(o=>this.positionsForChain(o,t.address)))).flat().sort((o,s)=>s.suppliedUsdc-o.suppliedUsdc||(s.avgApyPercent??0)-(o.avgApyPercent??0))}async describeResolvedMarkets(t,n){let r=Os(t),o=r?Om(r):null;return r&&o?this.describer.describe(r,o,n):[]}async positionsForChain(t,n){let r=Om(t),o=await Mm(this.coinPoolBaseUrl,t);if(!r||o.length===0)return[];let s=await this.describer.readBalances(t,n,o);if(s.length===0)return[];let i=await this.describer.describe(t,r,s.map(l=>l.market)),a=await this.describer.convertToUnderlying(t,s,i.map(l=>l.asset));return i.flatMap((l,c)=>{let u=a[c];return u<LK?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+DK(l.rewards))/100}]})}};var xP=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Ru=class{constructor(t){this.coinPoolBaseUrl=t}coinPoolBaseUrl;async listChains(){return wy(this.coinPoolBaseUrl)}async isSupported(t){return vy(this.coinPoolBaseUrl,t)}async getMarkets(t){let n=Ce(t);return n?Mm(this.coinPoolBaseUrl,n):[]}async findMarket(t,n){let r=await this.getMarkets(t);return bD(r,n)}canSupply(t){return xP.includes(t.type)}async readReceiptToken(t,n){let r=Bi(n).balanceIsUnderlying;try{let o=await Qt(t,[{target:n.token,callData:Le({abi:Ve,functionName:"symbol"})},{target:n.token,callData:Le({abi:Ve,functionName:"decimals"})}]);return{symbol:Rc(o[0]),decimals:_c(o[1]),isUnderlying:r}}catch{return{symbol:null,decimals:null,isUnderlying:r}}}};var AD=6e5,ky=new Map;async function xD(e){let t=ky.get(e);if(t&&Date.now()-t.at<AD)return t.chains;let n=HK(e);return ky.set(e,{at:Date.now(),chains:n}),n.then(r=>{r===null&&ky.delete(e)}),n}async function BK(e){try{let t=e==="morpho"?await MK():await FK();return!t||t.size===0?(Te(`protocolChains: ${e} returned no chains`),null):(Te(`protocolChains: ${e} live on`,[...t].sort((n,r)=>n-r)),t)}catch(t){return Te(`protocolChains: ${e} FAILED`,t instanceof Error?t.message:t),null}}async function MK(){let e=await se.post("https://api.morpho.org/graphql",{query:"{ chains { id network } }"});if(!e.ok)return null;let t=e.data?.data?.chains;if(!Array.isArray(t))return null;let n=new Set;for(let r of t)typeof r?.id=="number"&&Number.isInteger(r.id)&&r.id>0&&(n.add(r.id),typeof r.network=="string"&&r.network.trim()&&TD.set(r.id,r.network.trim()));return n}async function FK(){let e=await se.get("https://v3-api.compound.finance/market/all-networks/all-contracts/summary");if(!e.ok||!Array.isArray(e.data))return null;let t=new Set;for(let n of e.data)typeof n?.chain_id=="number"&&Number.isInteger(n.chain_id)&&n.chain_id>0&&t.add(n.chain_id);return t}var TD=new Map;function SD(e){return TD.get(e)??null}var qK=1500;async function PD(){let e=Promise.all([xD("morpho").catch(()=>null),xD("compound").catch(()=>null)]),t,n=new Promise(r=>{t=setTimeout(r,qK),t?.unref?.()});try{await Promise.race([e,n])}finally{t&&clearTimeout(t)}}function AP(e){let t=ky.get(e);return!t||Date.now()-t.at>=AD?null:ED.get(t.chains)??null}var ED=new WeakMap;function HK(e){let t=BK(e);return t.then(n=>{n&&ED.set(t,n)}),t}var $K={1:"ethereum",10:"opmainnet",130:"unichain",137:"polygon",143:"monad",480:"world-chain",988:"stable",999:"hyperevm",4217:"tempo",4663:"robinhood-chain",5042:"arc",8453:"base",42161:"arbitrum",747474:"katana"},VK={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},jK={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},WK={1:"mainnet",10:"op",130:"unichain",137:"polygon",2020:"ronin",5e3:"mantle",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function xy(e){let t=rY(e.chain);return(t===null?null:zK(e,t))??Nm(e.type)??nY(e,t)}function zK(e,t){switch(e.type){case"morpho-v2":{let n=$K[t]??YK(t);if(!n||!e.contract)return null;let r=`https://app.morpho.org/${n}/vault/${TP(e.contract)}`,o=QK(e.name);return o?`${r}/${o}`:r}case"aave-v3":{let n=VK[t],r=GK(e);return!n||!r?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${TP(r)}&marketName=${n}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let n=jK[t],r=eY(e);return!n||!r?null:`https://app.spark.finance/savings/${n}/${r}`}case"compound-v3":{if(XK(t))return null;let n=WK[t],r=JK(e);return!n||!r?null:`https://app.compound.finance/?market=${r}-${n}`}default:return null}}function GK(e){let t=e.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(t)?/^0x0+$/.test(t)?null:t:null}var KK=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function YK(e){if(!AP("morpho")?.has(e))return null;let n=SD(e);return n&&n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function QK(e){let t=e?.trim().toLowerCase()||"";return!t||KK.has(t)?null:t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function XK(e){let t=AP("compound");return t!==null&&!t.has(e)}function JK(e){let t=e.asset?.address?.trim().toLowerCase()||"",n=ZK[t];if(n)return n;let r=e.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(r)&&r.length<=12?r:null}var ZK={"0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"usdc.e","0xff970a61a04b1ca14834a43f5de4533ebddb5cc8":"usdc.e"};function eY(e){let t=e.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(t))return t;let n=`${e.name||""} ${e.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(n.includes(o))return o;if(e.type==="spark-ethereum")return tY[e.contract?.trim().toLowerCase()||""]??null;let r=e.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(r)||r.startsWith("s")?null:`s${r}`}var tY={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function nY(e,t){let n=e.protocolUrl?.trim();if(!n)return null;let r=/^https?:\/\//i.test(n)?n:`https://${n.replace(/^\/+/,"")}`;try{let o=new URL(r);return t!==null&&o.searchParams.set("chainId",String(t)),e.contract&&o.searchParams.set("contract",TP(e.contract)),o.toString()}catch{return r}}function TP(e){let t=e.trim().toLowerCase();return t.startsWith("0x")?t:`0x${t}`}function rY(e){let t=e?.trim();if(!t)return null;let n=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(n)&&n>0?n:null}var oY=new Set(["spark","spark-ethereum"]),sY=8;function iY(e,t,n){if(e.market.type!=="spark-l2-susds")return ft(t);let r=ft(t);return r===null||e.tokenDecimals===null?null:za(e.rawBalance,r,e.tokenDecimals,n)}var Ay=class{constructor(t){this.endpoints=t}endpoints;apyLimiter=new SP(sY);pantograph=new Ft;async describe(t,n,r){if(r.length===0)return[];Te("describe: START",{chain:t,count:r.length,types:r.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(t,r);Te("describe: assets resolved",o);let[i,a]=await Promise.all([this.readMarketState(t,r,o),Promise.all(r.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,n,o[c])))),PD()]);return Te("describe: on-chain state",i),Te("describe: APY fetched",a.map((l,c)=>({type:r[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),r.map((l,c)=>{let{totalSuppliedUsdc:u,liveApyFraction:d}=i[c],p=a[c].sizeOverride??u,m=lY(a[c].samples,d??a[c].current,a[c].rewards,a[c].avgOverride??null);return Te("describe: summarised",{market:l.name,type:l.type,liveFrom:d!==null?"on-chain":a[c].current!==null?"api":"none",rawSamples:a[c].samples.length,historyPoints:m.history.length,currentApyPercent:m.currentApyPercent,avgApyPercent:m.avgApyPercent,apyChangePercent:m.apyChangePercent,totalSuppliedUsdc:p,asset:o[c]?.symbol}),{...l,protocolUrl:xy({...l,asset:o[c],shareSymbol:s[c]}),asset:o[c],totalSuppliedUsdc:p,avgApyPercent:m.avgApyPercent,currentApyPercent:m.currentApyPercent,baseApyPercent:m.baseApyPercent,rewardApyPercent:m.rewardApyPercent,rewards:m.rewards,apyChangePercent:m.apyChangePercent,apyHistory:m.history}})}async readBalances(t,n,r){let o=Le({abi:Ve,functionName:"balanceOf",args:[n]}),s=Le({abi:Ve,functionName:"decimals"}),i=r.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),a=await Qt(t,i);return r.flatMap((l,c)=>{let u=ft(a[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:_c(a[c*2+1])}]})}async convertToUnderlying(t,n,r){let o=[],s=n.map(a=>{let l=Bi(a.market).convertToAssetsCall(a.market,a.rawBalance);return l?(o.push(l),o.length-1):-1}),i=await Qt(t,o);return n.map((a,l)=>{let c=r[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return Vr(a.rawBalance,c);let u=iY(a,i[s[l]],c);return u===null?Vr(a.rawBalance,a.tokenDecimals??c):Vr(u,c)})}async resolveAssets(t,n){let r={address:Ga,decimals:NaN,symbol:null,logo:null},o=[],s=n.map(p=>{let m=Bi(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),i;try{let p=o.length>0?await Qt(t,o):[];i=s.map(m=>m<0?null:Ge(p[m]))}catch{i=n.map(()=>null)}i=i.map((p,m)=>p??n[m]?.assetAddress??null);let a=[...new Set(i.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,u]=await Promise.all([this.readAssetMetadata(t,a),this.fetchAssetLogos(t,a),this.readShareSymbols(t,n)]);return{assets:i.map(p=>{if(!p)return r;let m=p.toLowerCase(),g=l.get(m),f=c.get(m)??null;return g?.decimals!==null&&g?.decimals!==void 0?{address:p,decimals:g.decimals,symbol:g.symbol??null,logo:f}:{address:p,decimals:NaN,symbol:null,logo:f}}),shareSymbols:u}}async readShareSymbols(t,n){let r=Le({abi:Ve,functionName:"symbol"}),o=[],s=n.map(i=>!oY.has(i.type)||!i.contract?-1:(o.push({target:i.contract,callData:r}),o.length-1));if(o.length===0)return n.map(()=>null);try{let i=await Qt(t,o);return s.map(a=>a<0?null:Rc(i[a]))}catch{return n.map(()=>null)}}async readAssetMetadata(t,n){let r=new Map;if(n.length===0)return r;let o=Le({abi:Ve,functionName:"decimals"}),s=Le({abi:Ve,functionName:"symbol"});try{let i=await Qt(t,n.flatMap(a=>[{target:a,callData:o},{target:a,callData:s}]));n.forEach((a,l)=>{r.set(a,{decimals:_c(i[l*2]),symbol:Rc(i[l*2+1])})})}catch{}return r}async fetchAssetLogos(t,n){let r=new Map;if(n.length===0)return r;try{let o=await this.pantograph.getTokensMetadata(n,t);for(let[s,i]of Object.entries(o)){let a=i.icon_image||i.logo||i.logoURI;a&&r.set(s.toLowerCase(),a)}}catch{}return Te("resolveAssets: logos",{chain:t,requested:n.length,found:r.size}),r}async readMarketState(t,n,r){let o=[],s=n.map((u,d)=>{let p=Bi(u),m=r[d],g={market:u,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(u,m));let f=p.liveRateCall(u,m);return f&&(g.rate=o.length,o.push(f)),g}),i=await Qt(t,o),a=[],l=s.map(u=>{if(u.rate<0)return-1;let d=u.protocol.followUpRateCall(u.market,i[u.rate]);return d?(a.push(d),a.length-1):-1}),c=a.length>0?await Qt(t,a):[];return s.map((u,d)=>{let p=u.rate<0?null:i[u.rate],m=l[d]>=0?c[l[d]]:p;return{totalSuppliedUsdc:u.protocol.decodeSize(i[u.size],u.asset),liveApyFraction:m===null?null:u.protocol.decodeLiveRate(m)}})}async fetchApy(t,n,r){try{Te("fetchApy: requesting",{market:t.name,type:t.type,asset:r?.symbol});let o=await Bi(t).fetchApy(t,n,this.endpoints,r);return Te("fetchApy: got",{market:t.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return Te("fetchApy: FAILED \u2014 market listed without APY",{market:t.name,type:t.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},SP=class{constructor(t){this.limit=t}limit;active=0;waiting=[];async run(t){this.active>=this.limit?await new Promise(n=>this.waiting.push(n)):this.active++;try{return await t()}finally{let n=this.waiting.shift();n?n():this.active--}}};function aY(e,t){let n=Tm(Date.now()),r=new Map,o=null;for(let a of e)!Number.isFinite(a.timeMs)||!Number.isFinite(a.fraction)||a.fraction<0||Tm(a.timeMs)>n||((!o||a.timeMs>o.timeMs)&&(o=a),r.set(a.timeMs,a.fraction));let s=[...r.entries()].sort((a,l)=>a[0]-l[0]).map(([a,l])=>({date:new Date(a).toISOString(),apyPercent:l*100})),i=t??(o&&Tm(o.timeMs)===n?o.fraction:null);return{history:s,live:i}}function lY(e,t,n=[],r=null){let{history:o,live:s}=aY(e,t),i=s===null?null:s*100,a=n.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=a.length===0?null:a.reduce((m,g)=>m+g.apyPercent,0),c=i===null?null:i+(l??0),u={baseApyPercent:i,rewardApyPercent:l,rewards:a},d=r!==null&&Number.isFinite(r)?r*100:null;if(o.length===0)return{history:o,avgApyPercent:d,currentApyPercent:c,apyChangePercent:null,...u};let p=o.reduce((m,g)=>m+g.apyPercent,0);return{history:o,avgApyPercent:d??p/o.length,currentApyPercent:c,apyChangePercent:uY(o,i),...u}}var RD=3600*1e3,cY=RD/2;function uY(e,t){if(t===null)return null;let n=Date.now()-RD,r=null,o=Number.POSITIVE_INFINITY;for(let s=e.length-1;s>=0;s--){let i=Math.abs(Date.parse(e[s].date)-n);if(i>o)break;o=i,r=e[s]}return!r||o>cY?null:t-r.apyPercent}function _D(e,t){if(!Number.isFinite(e))return e;let n=10**t,r=Number((e*n).toPrecision(15));return(e<0?-Math.floor(-r):Math.floor(r))/n+0}var io=class{read;supply;constructor(t={}){let n=t.coinPoolBaseUrl||"https://api.coinpool.app",r={lendingRatesBaseUrl:t.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:t.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:t.morphoApiUrl||"https://api.morpho.org/graphql"},o=new Ay(r);this.read=new Eu(n,r,o),this.supply=new Ru(n)}async listSupportedChains(){return this.supply.listChains()}async isSupported(t){return this.supply.isSupported(t)}async getMarkets(t){return this.supply.getMarkets(t)}async findMarket(t,n){return this.supply.findMarket(t,n)}canSupply(t){return this.supply.canSupply(t)}async readReceiptToken(t,n){return this.supply.readReceiptToken(t,n)}async describeReceiptTokens(t,n,r){return this.read.describeReceiptTokens(t,n,r)}async findMarketByReceiptToken(t,n,r){return this.read.findMarketByReceiptToken(t,n,r)}async describeResolvedMarkets(t,n){return this.read.describeResolvedMarkets(t,n)}async getMarketOverviews(t){return(await Promise.all(t.chains.map(async r=>this.read.describeResolvedMarkets(r,await this.getMarkets(r))))).flat().sort((r,o)=>(o.avgApyPercent??-1)-(r.avgApyPercent??-1))}async getSupplyPositions(t){return this.read.getSupplyPositions(t)}};var Fm="{market}",ND=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],Sy=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],jr="[[LIST]]",OD=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',LD=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function DD(e,t,n){let[r]=dY([e],t,n),[o]=e.canSupply?PP(e,t,n):[];return{name:e.name?.trim()||e.protocol,protocol:e.protocol,protocolUrl:e.protocolUrl,chain:n,apyPercent:e.apyPercent,detailPrompt:r?.prompt??"",detailLabel:r?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function dY(e,t,n){return UD(e,{labelTemplate:Ty(t.detail_button_label),promptTemplate:Ty(t.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Fm}`,...n===void 0?{}:{chainName:n}})}function PP(e,t,n){return UD([e],{labelTemplate:Ty(t.supply_button_label),promptTemplate:Ty(t.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Fm}`,promptFallback:`supply to ${Fm}`,...n===void 0?{}:{chainName:n},max:1})}function UD(e,t){let n=typeof t.chainName=="string"?t.chainName.trim():"",r=[],o=new Set;for(let s of e){if(t.max!==void 0&&r.length>=t.max)break;let i=s.name?.trim();!i||o.has(i.toLowerCase())||(o.add(i.toLowerCase()),r.push({label:ID(t.labelTemplate,i,t.labelFallback,t.labelNamesMarket===!0),prompt:ID(pY(t.promptTemplate),i,t.promptFallback)+mY(s.contract,n)}))}return r}function pY(e){let[t,n]=[e[0],e[1]];return t===void 0||t===t.toLowerCase()||n!==void 0&&n!==n.toLowerCase()?e:t.toLowerCase()+e.slice(1)}function Ty(e){return typeof e=="string"?e:""}function mY(e,t){let n=e?.trim();if(!n||!/^0x[a-fA-F0-9]{40}$/.test(n))return"";let r=t?.trim();return r?` (market: ${n} - ${r})`:` (market: ${n})`}function ID(e,t,n,r=!0){let s=e&&(!r||e.includes(Fm))?e:n;return hY(s).split(Fm).join(t).replace(/\s+/g," ").trim()}var CD="{chain}";function hY(e){if(!e.includes(CD))return e;let t=CD.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${t}`,"g"),"").replace(new RegExp(`${t}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(t,"g"),"")}var Py=[{id:"aave-v3",label:"Aave v3",types:["aave-v3"],aliases:["aave","aavev3","aave3","ave"]},{id:"compound-v3",label:"Compound v3",types:["compound-v3"],aliases:["compound","compoundv3","compound3","comet","comp"]},{id:"spark-any",label:"Spark",types:["spark","spark-ethereum"],aliases:["spark","sparkfi","sparklend","sparkprotocol"]},{id:"morpho-v2",label:"Morpho",types:["morpho-v2"],aliases:["morpho","morphov2","morpho2","morphoblue","metamorpho"]}],RP=Py.map(e=>e.label),EP={euler:"Euler",venus:"Venus",radiant:"Radiant",benqi:"Benqi",qi:"Benqi",fluid:"Fluid",instadapp:"Fluid",silo:"Silo",moonwell:"Moonwell",sonne:"Sonne",granary:"Granary",ironbank:"Iron Bank",cream:"Cream",maker:"Maker",makerdao:"Maker",sky:"Sky",justlend:"JustLend",kamino:"Kamino",solend:"Solend",marginfi:"marginfi",save:"Save",curve:"Curve",yearn:"Yearn",convex:"Convex",pendle:"Pendle",ethena:"Ethena",gearbox:"Gearbox",notional:"Notional",exactly:"Exactly",seamless:"Seamless",zerolend:"ZeroLend",dforce:"dForce",tectonic:"Tectonic",liqee:"Liqee"};function BD(e){let t=typeof e=="string"?e.trim():"";if(!t)return{kind:"none"};let n=bY(t);if(!n)return{kind:"none"};let r=fY(n);if(r){let s=new Set(r.types);return{kind:"supported",label:r.label,matches:i=>s.has(i.type)}}let o=yY(n);return o?{kind:"unsupported",label:o,requested:t}:{kind:"unknown",requested:t}}function fY(e){let t=Py.filter(n=>n.aliases.includes(e));if(t.length===1)return t[0];if(t.length>1)return null;if(e.length>=3){let n=Py.filter(r=>r.aliases.some(o=>o.includes(e)||e.includes(o)));if(n.length===1)return n[0];if(n.length>1)return null}return gY(e)}function gY(e){let t=null,n=!1;for(let r of Py)for(let o of r.aliases){let s=MD(o);if(s===0||Math.abs(o.length-e.length)>s)continue;let i=FD(e,o,s);i>s||(!t||i<t.distance?(t={spec:r,distance:i},n=!1):i===t.distance&&r!==t.spec&&(n=!0))}return t&&!n?t.spec:null}function MD(e){return e.length<=4?0:e.length<=9?2:3}function yY(e){let t=EP[e];if(t)return t;if(e.length>=4){let o=new Set(Object.entries(EP).filter(([s])=>s.length>=4&&(s.includes(e)||e.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let n=null,r=!1;for(let[o,s]of Object.entries(EP)){let i=MD(o);if(i===0||Math.abs(o.length-e.length)>i)continue;let a=FD(e,o,i);a>i||(!n||a<n.distance?(n={label:s,distance:a},r=!1):a===n.distance&&s!==n.label&&(r=!0))}return n&&!r?n.label:null}function bY(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function FD(e,t,n){if(e===t)return 0;if(!e.length)return t.length;if(!t.length)return e.length;let r=new Array(t.length+1),o=Array.from({length:t.length+1},(i,a)=>a),s=new Array(t.length+1);for(let i=1;i<=e.length;i++){s[0]=i;let a=s[0];for(let c=1;c<=t.length;c++){let u=o[c-1]+(e[i-1]===t[c-1]?0:1),d=Math.min(s[c-1]+1,o[c]+1,u);i>1&&c>1&&e[i-1]===t[c-2]&&e[i-2]===t[c-1]&&(d=Math.min(d,r[c-2]+1)),s[c]=d,d<a&&(a=d)}if(a>n)return n+1;let l=r;r=o,o=s,s=l}return o[t.length]}function qt(e,t){return e==null?null:_D(e,t)}var Bn=2,Mi=2;function Ey(e){let t=qt(e.currentApyPercent,Bn),n=e.rewards.map(s=>({apyPercent:qt(s.apyPercent,Bn)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),r=e.rewardApyPercent===null?null:n.reduce((s,i)=>s+Math.round(i.apyPercent*100),0)/100;if(r===null||t===null)return{currentApyPercent:t,rewardApyPercent:r,rewards:n,baseApyPercent:qt(e.baseApyPercent,Bn)};let o=Math.round(t*100)-Math.round(r*100);return{currentApyPercent:t,rewardApyPercent:r,rewards:n,baseApyPercent:o/100}}var wY=["apy","score","size"],qD=3,HD=40,_u=class extends K{name="get-lending-markets";kind="ui";description='BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${RP.join(", ")}. Set it whenever the user names a protocol \u2014 "supply aave", "morpho vaults", "l\xE3i su\u1EA5t b\xEAn Compound" \u2014 and pass what they wrote, VERBATIM. Do NOT correct their spelling, do NOT translate it, and do NOT map it to a name from the supported list yourself: misspellings are resolved for you, and a protocol that is NOT supported is reported back so you can tell the user. Pass it even when you believe the protocol is unsupported \u2014 that is how the user gets told. OMIT it when the user named no protocol; never guess one to narrow a list they asked for in full.`,required:!1},{name:"limit",type:"number",description:`How many markets to return, 1-${HD}. Default ${qD} \u2014 the top markets by the chosen ranking, which answers "where can I earn on my USDC" on its own. Raise it ONLY when the user asks for more than that, for the full list, or to compare broadly; lower it when they want a shorter shortlist.`,required:!1},{name:"sort",type:"string",description:'Ranking: "apy" (default, highest live protocol APY first), "score" (safest / best-rated first \u2014 use when the user asks for safe, reliable or trusted markets), or "size" (largest market first \u2014 use when the user asks for the biggest or most liquid markets).',required:!1},...ND,...Sy];service;constructor(t){super(),this.service=new io(t)}async run(t,n){let r=at(t.chain,void 0),o=r?null:Ce(n?.chain),s=r??o,i=s?await this.service.isSupported(s):!1,a=i?[]:await this.service.listSupportedChains();if(s&&!i)return{_instructions:`There are no lending markets on ${j(s)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:j(s),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:a.map(v=>j(v))};let l=BD(t.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:a,u=kY(t.sort),d=xY(t.limit),p=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?p.filter(v=>l.matches(v)):p;if(l.kind==="supported"&&m.length===0&&p.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?j(s):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?j(s):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(p.map(v=>v.protocol))]};let g=[...m].sort(vY[u]).slice(0,d),f=g.map(v=>DD({name:v.name,contract:v.contract,protocol:v.protocol,protocolUrl:v.protocolUrl,apyPercent:qt(v.currentApyPercent,Bn),canSupply:this.service.supply.canSupply(v)},t,j(v.chain))),w={component:"LendingMarketList",props:{chain:s?j(s):"all",multiChain:new Set(f.map(v=>v.chain)).size>1,markets:f}};return{...f.length>0?{ui:w}:{},_instructions:this.instructions(g,u,f.length>0,l.kind==="supported"?l.label:null),chain:s?j(s):"all",chainsQueried:c.map(v=>j(v)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:u,marketCount:f.length,totalMarketsAvailable:m.length,marketNames:f.map(v=>v.name)}}unsupportedProtocol(t){let n=t.kind==="unsupported",r=n?t.label:`"${t.requested}"`;return{_instructions:`The user asked about ${r}, which has no lending markets here. In their language: tell them plainly that ${r} is ${n?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${r} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:n?t.label:t.requested,protocolSupported:!1,supportedProtocols:[...RP],marketCount:0,marketNames:[]}}instructions(t,n,r=!1,o=null){if(t.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let s={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[n];return[o?`These are the ${o} lending markets the user can supply to, ${s}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,`Write your reply in TWO parts separated by a line containing exactly ${jr} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",n==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(t.map(i=>i.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${j(t[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${s} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",r?OD:""].filter(Boolean).join(" ")}},vY={apy:(e,t)=>(t.currentApyPercent??-1)-(e.currentApyPercent??-1),score:(e,t)=>(t.platformScore??-1)-(e.platformScore??-1),size:(e,t)=>(t.totalSuppliedUsdc??-1)-(e.totalSuppliedUsdc??-1)};function kY(e){let t=typeof e=="string"?e.trim().toLowerCase():"";return wY.includes(t)?t:"apy"}function xY(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?qD:Math.min(Math.floor(t),HD)}function $D(e){let{currentApyPercent:t,avgApyPercent:n,totalSuppliedUsdc:r,rewardApyPercent:o,baseApyPercent:s,platformScore:i}=e;return e.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:o!==null&&s!==null&&o>s*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:t!==null&&n!==null&&n>0&&t>n*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:r!==null&&r<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:i!==null&&i<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:i!==null&&i>=8.5&&r!==null&&r>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:r!==null&&r>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}function Ry(e){let t=typeof e=="string"?e.trim():"",n=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(t);if(n)return n[1];let r=/0x[a-fA-F0-9]{40}/.exec(t);return r&&r[0]!==t?r[0]:t}var Iu=class extends K{name="get-lending-market-detail";category="blockchain-data";description='Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...Sy];service;constructor(t){super(),this.service=new io(t)}async run(t,n){let o=at(t.chain,void 0)??Ce(n?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let d=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:j(o),chainsWithLendingMarkets:d.map(p=>j(p)),_instructions:`There are no lending markets on ${j(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=Ry(t.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let i=await this.service.findMarket(o,s);if(i.length===0)return{error:"market_not_found",market:s,chain:j(o),_instructions:`No lending market matching "${s}" exists on ${j(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(i.length>1)return{error:"ambiguous_market",market:s,chain:j(o),candidates:i.map(d=>({marketName:d.name,protocol:d.protocol})),_instructions:`"${s}" matches ${i.length} different markets on ${j(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${j(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let a=i[0],l=await this.describeOne(o,a);if(!l)return{error:"market_unavailable",marketName:a.name,chain:j(o),_instructions:`${a.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let c=this.service.supply.canSupply(a),u=c?PP({name:a.name,contract:a.contract},t,j(o)):[];return{_instructions:this.instructions(l,u.length>0,c),...u.length>0?{actionButtons:u}:{},marketName:l.name,protocol:l.protocolLabel??l.protocol,protocolUrl:l.protocolUrl,chain:j(l.chain),suppliedAssetSymbol:l.asset.symbol,totalSuppliedUsdc:qt(l.totalSuppliedUsdc,Mi),...Ey(l),avgApyPercent:qt(l.avgApyPercent,Bn),apyChangePercent:qt(l.apyChangePercent,Bn),platformScore:l.platformScore,supplySupported:c}}async describeOne(t,n){try{let[r]=await this.service.describeResolvedMarkets(t,[n]);return r??null}catch{return null}}instructions(t,n,r){let o=$D(t);return[`This is the full picture of ONE lending market, ${t.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',r?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",n?LD:""].filter(Boolean).join(" ")}};var Cu=class extends K{name="get-wallet-lending-positions";description='Get a wallet\'s own LENDING / SUPPLY (earn, deposit, savings) positions in the curated lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much it has supplied there, the AVERAGE supply APY over the last week (plus the live rate and the day-over-day change), the estimated yearly yield on that balance, and the market total supplied. Balances are read on-chain, so they match the app. Use for questions like: "Which protocols am I supplying on?", "Show my lending positions", "How much am I earning on my USDC?", "What APY am I getting?", "Where is my USDC deposited?", "My Aave / Compound / Spark / Morpho supply", "what am I earning on Aave", "my savings positions". This is the PREFERRED tool for any "what am I earning / supplying / depositing" question, even when the user names a protocol ("my Aave v3 supply", "my Spark deposit") \u2014 it is the only source of the 7-day average APY, the estimated yearly yield and the platform safety score. Each position reports its OWN asset, which is usually USDC but need not be \u2014 never assume the amounts are dollars without checking `suppliedAssetSymbol`. Chains and markets come from the live catalogue, so do not rule a chain out from memory: call the tool and let it answer. For protocols outside Aave v3 / Compound v3 / Spark / Morpho (Aave v2, MakerDAO\u2026), or when this tool reports nothing but the user insists they have a deposit, fall back to get-wallet-defi-positions. Do NOT use for: markets the wallet has NOT supplied to yet \u2014 where to deposit, best available APY, "promising lending" \u2192 get-lending-markets; the BORROW side of these same protocols, plus LP / staking \u2192 get-wallet-defi-positions (or get-wallet-defi-protocol-positions for one named protocol); plain token balances \u2192 get-wallet-token-balances.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:`Hex chain ID to scope to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry lending markets is resolved at call time, so do NOT filter the request against a list you remember. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 positions are then read on the connected wallet's own chain.`,required:!1}];service;constructor(t){super(),this.service=new io(t)}async run(t,n){let r=gt(t.address,n);if(!ge(r))return{error:`"${r}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=at(t.chain,n),s=o?await this.service.isSupported(o):!1,i=s?[]:await this.service.listSupportedChains();if(o&&!s)return{_instructions:`There are no lending markets on ${j(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:r,chain:j(o),positionCount:0,positions:[],chainsWithLendingMarkets:i.map(c=>j(c))};let a=o?[o]:i,l=await this.service.getSupplyPositions({address:r,chains:a});return{_instructions:this.instructions(l),walletAddress:r,chain:o?j(o):"all",chainsQueried:a.map(c=>j(c)),positionCount:l.length,totals:AY(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:j(c.chain),suppliedUsdc:qt(c.suppliedUsdc,Mi),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:qt(c.avgApyPercent,Bn),...Ey(c),apyChangePercent:qt(c.apyChangePercent,Bn),estimatedAnnualYieldUsdc:qt(c.estimatedAnnualYieldUsdc,Mi),marketTotalSuppliedUsdc:qt(c.totalSuppliedUsdc,Mi),apyHistory:c.apyHistory.map(u=>({...u,apyPercent:qt(u.apyPercent,Bn)})),platformScore:c.platformScore}))}}instructions(t){return t.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(t.map(r=>r.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function AY(e){if(new Set(e.map(i=>i.asset.symbol??i.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let r=e.reduce((i,a)=>i+a.suppliedUsdc,0),o=e.filter(i=>i.avgApyPercent!==null),s=o.reduce((i,a)=>i+a.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:e[0]?.asset.symbol??null,suppliedUsdc:qt(r,Mi),estimatedAnnualYieldUsdc:qt(e.reduce((i,a)=>i+(a.estimatedAnnualYieldUsdc??0),0),Mi),weightedAvgApyPercent:qt(s>0?o.reduce((i,a)=>i+a.suppliedUsdc*a.avgApyPercent,0)/s:null,Bn)}}var Nu=class extends K{name="open-supply-usdc-form";kind="ui";category="lending-action";description='Open the SUPPLY form so the user can DEPOSIT into a specific lending market and start earning yield. This is the tool for a supply COMMAND: the user names a market and tells you to act on it, in any wording and any language \u2014 "supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare "Supply Aave", or a tapped "Supply \u2026" button. A supply verb plus a market name is already a complete command; terseness is not ambiguity, and the words the user left out are supplied by context rather than looked up. Each market deposits its OWN asset (usually USDC), resolved from the market itself \u2014 so a message that names no asset is still this tool: resolve the market from whatever the user did name. An amount is optional. Pass `market` \u2014 the market name or protocol exactly as it was shown to them (e.g. "Aave v3 USDC", "Spark"), and `amount` ONLY when they named one. Supports Aave v3, Compound v3, Spark and Morpho vaults, on whichever chains currently carry them \u2014 that set is resolved at call time, so never refuse a chain from memory. PRECONDITION: a connected wallet. The boundary is command vs question: use this to ACT on one market; to LIST or compare markets \u2192 get-lending-markets; for what the wallet already supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}];service;moralis;constructor(t){super(),this.service=new io(t),this.moralis=new De(t?.moralis)}async run(t,n){let r=n?.walletAddress;if(!r)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let s=at(t.chain,void 0)??Ce(n?.chain);if(!s)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};if(!await this.service.isSupported(s)){let w=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:j(s),chainsWithLendingMarkets:w.map(v=>j(v)),_instructions:`There are no lending markets on ${j(s)}, so nothing can be supplied there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let i=Ry(t.market);if(!i)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let a=await this.service.findMarket(s,i);if(a.length===0)return{error:"market_not_found",market:i,chain:j(s),_instructions:`No lending market matching "${i}" exists on ${j(s)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(a.length>1)return{error:"ambiguous_market",market:i,chain:j(s),candidates:a.map(w=>({marketName:w.name,protocol:w.protocol})),_instructions:`"${i}" matches ${a.length} different markets on ${j(s)}, so the supply cannot target one yet. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+i+`" and chain for ${j(s)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let l=a[0];if(!this.service.supply.canSupply(l))return{error:"unsupported_protocol",marketName:l.name,protocol:l.protocol,_instructions:`Supplying to ${l.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let c=await this.describeOne(s,l),u=TY(c);if(!u)return{error:"asset_unresolved",marketName:l.name,chain:j(s),_instructions:`The asset ${l.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[d,p]=await Promise.all([this.assetBalance(r,s,u.address),this.service.readReceiptToken(s,l)]);if(d&&Ci(d.amount,"0")<=0)return{error:"no_asset_balance",marketName:l.name,chain:j(s),assetSymbol:u.symbol,assetBalance:"0",_instructions:`The user has no ${u.symbol} available to supply to ${l.name} on ${j(s)}. In the user's language, tell them plainly that they have no ${u.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let m=SY(t.amount),g=m?gr(m,u.decimals):null;if(g&&d&&Ci(g,d.amount)>0)return{error:"insufficient_asset_balance",marketName:l.name,chain:j(s),assetSymbol:u.symbol,requestedAmount:m,assetBalance:d.amount,_instructions:`The user wants to supply ${m} ${u.symbol} to ${l.name}, but they only hold ${d.amount} ${u.symbol} on ${j(s)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${m} ${u.symbol} exceeds their balance of ${d.amount} ${u.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let f={action:"supply_usdc",chainId:s,chainName:j(s),walletAddress:r,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??xy(l),contract:l.contract,token:l.token,apyPercent:c?.currentApyPercent??c?.avgApyPercent??null,receiptToken:p},asset:u,...g?{prefillAmount:g}:{},...d?{spendable:d.amount}:{},...d?.usd?{spendableUsd:d.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:f},marketName:l.name,protocol:l.protocol,chain:j(s),apyPercent:qt(f.market.apyPercent,Bn),assetSymbol:u.symbol,assetBalance:d?.amount??null,_instructions:this.instructions(l,u.symbol)}}async describeOne(t,n){try{let[r]=await this.service.describeResolvedMarkets(t,[n]);return r??null}catch{return null}}async assetBalance(t,n,r){try{let o=await this.moralis.getWalletTokenBalances({address:t,chain:n,tokenAddresses:[r]});if(!o.success)return null;let s=(o.data?.result??[]).find(a=>(a.token_address||"").toLowerCase()===r.toLowerCase());if(!s?.balance_formatted)return{amount:"0",usd:null};let i=typeof s.usd_value=="number"?String(s.usd_value):null;return{amount:String(s.balance_formatted),usd:i}}catch{return null}}instructions(t,n){return[`The supply action for ${t.name} is ready.`,`In the user's language, invite them to enter the amount of ${n} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${n}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function TY(e){let t=e?.asset;return!t?.address||t.address===Ga||!Number.isFinite(t.decimals)?null:{address:t.address,symbol:t.symbol||"the market asset",decimals:t.decimals}}function SY(e){let t=typeof e=="string"?e.trim():typeof e=="number"?String(e):"";return/^\d*\.?\d+$/.test(t)&&Number(t)>0?t:null}var Fi={GAMMA:"https://gamma-api.polymarket.com",DATA:"https://data-api.polymarket.com",BRIDGE:"https://bridge.polymarket.com",CLOB:"https://clob.polymarket.com",RELAYER:"https://relayer-v2.polymarket.com"},_y="/submit",Iy={INTERVAL_MS:3e3,TIMEOUT_MS:9e4},IP="0xebd1cc31700311ef8259fc9337f7a04317bfee851a71bf628420669d75124374",PY=/^0x[0-9a-fA-F]{64}$/,_P=IP;function CP(e){let t=e?.trim();if(!t){_P=IP;return}if(!PY.test(t))throw new Error(`Invalid Polymarket builder code: ${t}`);_P=t.toLowerCase()}function Ou(){return _P}var EY=1e4,RY="https://intercom.help/funxyz/en/articles/10732578-contact-us",NP="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",qi="https://polymarket.com",OP="wss://ws-live-data.polymarket.com",Hi="0x89",qm="137",LP="0xDCa4af75705dbB50f62437045afF9921947917d2",DP="Trading setup approvals",on={DEPLOY:"deploy",ENABLE_TRADING:"enable_trading",APPROVE:"approve",DONE:"done"},Cy={INTERVAL_MS:2e3,MAX_ATTEMPTS:30},Hm=["USDC","USDC.E","USDT","USD\u20AE0","USDT0","DAI","USDE","AUSD","USDG"],Ya={"1151111081099710":"svm",8253038:"btc",728126428:"tron",29780:null},Ls="0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB",zo=6,Wr={depositWalletFactory:"0x00000000000Fb5C9ADea0298D729A0CB3823Cc07",depositWalletImplementation:"0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB",safeFactory:"0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b",safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf",factoryBeaconSelector:"0x49493a4d"},Ds={PREFIX:BigInt("0x61003d3d8160233d3973"),CONST1:"0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",CONST2:"0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",BEACON_PREFIX:BigInt("0x6100523d8160233d3973"),BEACON_CONST1:"0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",BEACON_CONST2:"0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",BEACON_CONST3:"0x60195155f3363d3d373d3d363d602036600436635c60da"},$i=[{key:"politics",tagId:"2",label:"Politics",aliases:["politic","chinh tri","ch\xEDnh tr\u1ECB","\u653F\u6CBB","\uC815\uCE58"]},{key:"sports",tagId:"1",label:"Sports",aliases:["sport","the thao","th\u1EC3 thao","\u30B9\u30DD\u30FC\u30C4","\u4F53\u80B2","\uC2A4\uD3EC\uCE20"]},{key:"crypto",tagId:"21",label:"Crypto",aliases:["cryptocurrency","tien dien tu","ti\u1EC1n \u0111i\u1EC7n t\u1EED","tien ma hoa","ti\u1EC1n m\xE3 h\xF3a","\u6697\u53F7\u8CC7\u7523","\u52A0\u5BC6\u8D27\u5E01","\uC554\uD638\uD654\uD3D0"]},{key:"esports",tagId:"64",label:"Esports",aliases:["e-sports","the thao dien tu","th\u1EC3 thao \u0111i\u1EC7n t\u1EED","e\u30B9\u30DD\u30FC\u30C4","\u7535\u7ADE"]},{key:"iran",tagId:"78",label:"Iran",aliases:["\u30A4\u30E9\u30F3","\u4F0A\u6717","\uC774\uB780"]},{key:"finance",tagId:"120",label:"Finance",aliases:["tai chinh","t\xE0i ch\xEDnh","\u91D1\u878D","\uAE08\uC735"]},{key:"geopolitics",tagId:"100265",label:"Geopolitics",aliases:["dia chinh tri","\u0111\u1ECBa ch\xEDnh tr\u1ECB","\u5730\u653F\u5B66","\u5730\u7F18\u653F\u6CBB"]},{key:"tech",tagId:"1401",label:"Tech",aliases:["technology","cong nghe","c\xF4ng ngh\u1EC7","\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC","\u79D1\u6280","\uAE30\uC220"]},{key:"elections",tagId:"144",label:"Elections",aliases:["election","bau cu","b\u1EA7u c\u1EED","\u9078\u6319","\u9009\u4E3E","\uC120\uAC70"]},{key:"culture",tagId:"596",label:"Culture",aliases:["pop culture","pop-culture","entertainment","van hoa","v\u0103n h\xF3a","giai tri","gi\u1EA3i tr\xED","\u30A8\u30F3\u30BF\u30E1","\u5A31\u4E50"]},{key:"economy",tagId:"100328",label:"Economy",aliases:["economics","kinh te","kinh t\u1EBF","\u7D4C\u6E08","\u7ECF\u6D4E","\uACBD\uC81C"]},{key:"weather",tagId:"84",label:"Weather",aliases:["climate","thoi tiet","th\u1EDDi ti\u1EBFt","\u5929\u6C17","\u5929\u6C14"]},{key:"science",tagId:"74",label:"Science",aliases:["khoa hoc","khoa h\u1ECDc","\u79D1\u5B66","\uACFC\uD559"]},{key:"awards",tagId:"18",label:"Awards",aliases:["giai thuong","gi\u1EA3i th\u01B0\u1EDFng","\u8CDE","\u5956\u9879"]}],$m={trending:{order:"volume24hr",ascending:!1},new:{order:"startDate",ascending:!1},volume:{order:"volume",ascending:!1},liquidity:{order:"liquidity",ascending:!1},competitive:{order:"competitive",ascending:!1},ending_soon:{order:"endDate",ascending:!0}},UP="102127",BP="100639",MP="102169",FP=["TRADE","REDEEM","SPLIT","MERGE","CONVERSION","REWARD"],qP=.01,Vm={MIN_BUY_USD:1,DEFAULT_SLIPPAGE:.05,SLIPPAGE_OPTIONS:[.02,.05,.1]},Ny={POLL_MS:1e3,TIMEOUT_MS:2e4},gn={STABLE_SYMBOLS:["USDC","USDT","USDT0","USD\u20AE0"],CHAIN_ORDER:["137","8453","42161","1","10","56"],LARGE_USD:5e4,ERROR:{INVALID_AMOUNT:"invalid_amount",BELOW_MINIMUM:"below_minimum",INSUFFICIENT_BALANCE:"insufficient_balance",CANCELLED:"cancelled",FAILED:"failed"}},Qa={POSITIONS_READ_LIMIT:500,ERROR:{NOTHING_TO_CLAIM:"nothing_to_claim",CANCELLED:"cancelled",FAILED:"failed"}},Us={ENTER_AMOUNT:"enter_amount",NO_LIQUIDITY:"no_liquidity",NOT_ENOUGH_LIQUIDITY:"not_enough_liquidity",BELOW_MINIMUM:"below_minimum",EXCEEDS_HOLDING:"exceeds_holding",TOO_SMALL:"too_small"},bt={REGION_RESTRICTED:"region_restricted",MARKET_CLOSED:"market_closed",NOT_FILLED:"not_filled",INSUFFICIENT_BALANCE:"insufficient_balance",NOT_ENOUGH_LIQUIDITY:"not_enough_liquidity",TRADING_PAUSED:"trading_paused",BELOW_MIN_SIZE:"below_min_size",CLOSE_ONLY:"close_only",ACCOUNT_BANNED:"account_banned",CANCELLED:"cancelled",FAILED:"failed"},jm={THROTTLE_MS:1e3,STALE_MS:3e4,FALLBACK_POLL_MS:5e3};function WD(e){return`btc-updown-5m-${Math.floor(e/1e3/300)*300}`}var _Y=e=>/^btc-updown-(5m|15m)-/.test((e.slug??"").toLowerCase()),ao={MAX:8,INDEX:2,PREGAME_MINUTES:720,VOLUME_FLOOR:15e4,MAX_PER_SERIES:2,GAME_MINUTES:180,PAIR_VOLUME:3e5,PROXIMITY_WEIGHT:10},zD={nfl:2160,cbb:1440,cwbb:1440},IY={cwbb:1e5,"world-cup":25e3,wimbledon:25e3},CY={cwbb:3,"world-cup":6,wimbledon:4},NY={nba:150,wnba:120,ufc:60,f1:120,cs2:90,"dota-2":90,"league-of-legends":60,valorant:60},OY="world-cup";function HP(e){if(!e)return null;let t=e.trim().replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),n=Date.parse(t);return Number.isFinite(n)?n:null}function LY(e){return(e.seriesSlug||e.series?.[0]?.slug||(e.slug??"").split("-")[0]||"").toLowerCase().replace(/-\d{4}(-\d{2,4})?$/,"")}var DY=e=>(e.tags??[]).some(t=>["1","64"].includes(String(t?.id))||t?.slug==="sports"||t?.slug==="esports");function UY(e){let t=(e.markets??[]).find(n=>n.gameStartTime)?.gameStartTime;return HP(e.startTime)??HP(t)??HP(e.startDate)}var BY=e=>{let t=Number(e.volume);return Number.isFinite(t)?t:0},VD=e=>e.closed!==!0;function MY(e,t){if(e.parentEventId!=null||e.closed===!0||e.ended===!0||!DY(e))return null;let n=LY(e);if(!n)return null;let r=UY(e);if(r===null)return null;let o=BY(e);if(o<(IY[n]??ao.VOLUME_FLOOR))return null;let s=(r-t)/6e4,i=NY[n]??ao.GAME_MINUTES,a=e.live===!0&&-s<=i+15+180+10;if(!a&&s<-30)return null;let l=zD[n]??ao.PREGAME_MINUTES;return!a&&!(s>=-5&&s<=l)?null:{row:e,league:n,volume:o,minutes:s,live:a}}function FY(e){let t=new Map;for(let r of e)t.set(r.league,[...t.get(r.league)??[],r]);let n=[];for(let[r,o]of t){let s=[...o].sort((u,d)=>d.volume-u.volume),i=CY[r]??ao.MAX_PER_SERIES,a=r===OY,l=a?Math.min(s.length,i):1;if(!a&&s.length>=2){let[u,d]=s,p=u.volume>=ao.PAIR_VOLUME&&d.volume>=ao.PAIR_VOLUME,m=[u,d].filter(g=>g.live||g.minutes<=60).length>=2;(p||m)&&(l=Math.min(s.length,i))}let c=zD[r]??ao.PREGAME_MINUTES;for(let u of s.slice(0,l)){let d=Math.log1p(u.volume),p=Math.max(0,Math.min(1,(c-Math.max(0,u.minutes))/c));n.push({...u,worldCup:a,score:u.live?d:d+ao.PROXIMITY_WEIGHT*p})}}return n.sort((r,o)=>{if(r.worldCup!==o.worldCup)return r.worldCup?-1:1;let s=r.minutes<0,i=o.minutes<0;return s!==i?s?-1:1:o.score-r.score}).slice(0,ao.MAX).map(r=>r.row)}function jD(e){let t=new Set;return e.filter(n=>{let r=String(n.id??"");return!r||t.has(r)?!1:(t.add(r),!0)})}function GD(e,t){let n=e.btc5m&&VD(e.btc5m)?e.btc5m:null,r=d=>jD(d.filter(p=>VD(p)&&!_Y(p))),o=r(e.feed),s=r(e.featured);if(s.length>0){let d=new Set(s.map(m=>String(m.id))),p=new Set(s.map(m=>(m.series?.[0]?.slug??"").toLowerCase()).filter(Boolean));o=[...s,...o.filter(m=>!d.has(String(m.id))&&!p.has((m.series?.[0]?.slug??"").toLowerCase()))]}let i=o.slice(0,ao.INDEX),a=o.slice(ao.INDEX),l=new Set(i.map(d=>String(d.id))),c=jD([...a,...r(e.sports)]).filter(d=>!l.has(String(d.id))).map(d=>MY(d,t)).filter(d=>d!==null),u=FY(c);if(u.length>0){let d=new Set(u.map(p=>String(p.id)));o=[...i,...u,...a.filter(p=>!d.has(String(p.id)))]}return n&&(o=[...o.slice(0,1),n,...o.slice(1)]),o}var qY=/^([a-z0-9]+)-updown-(5m|15m|4h)-(\d+)$/,HY={"5m":300,"15m":900,"4h":14400},$Y={"5m":"fiveminute","15m":"fifteen","4h":"fourhour"},KD=e=>new Date(e*1e3).toISOString().replace(".000Z","Z");function Dy(e,t){let n=qY.exec((e??"").toLowerCase());if(!n)return null;let[,r,o,s]=n,i=Number(s),a=t?.cryptoMarketConfig;return{symbol:r.toUpperCase(),priceFeed:`${r}/usd`,duration:o,startTime:t?.eventStartTime||KD(i),endTime:t?.endDate||KD(i+HY[o]),twapSeconds:a?.twapEnabled===!0?Math.max(0,Number(a.twapLookbackSeconds)||0):0}}function XD(e){return{symbol:e.symbol,eventStartTime:e.startTime,variant:$Y[e.duration]??"hourly",endDate:e.endTime,...e.twapSeconds>0?{twapEnabled:"true",twapLookbackSeconds:String(e.twapSeconds)}:{}}}var VY="crypto_prices_chainlink",jY=15e3,WY=1e4,YD=[1e3,2e3,5e3,1e4],Bs=new Map,$P=new Map,Ms=null,Oy=null,Lu=null,Ly=null,VP=0,jP=(e,t)=>JSON.stringify({action:e,subscriptions:t.map(n=>({topic:VY,type:"*",filters:JSON.stringify({symbol:n})}))});function zY(e,t){let n=$P.get(e);n&&n.timestamp>t.timestamp||($P.set(e,t),Bs.get(e)?.forEach(r=>r(t)))}function GY(e){if(typeof e!="string"||!e.startsWith("{"))return;let t;try{t=JSON.parse(e)}catch{return}let n=t.payload??{},r=typeof n.symbol=="string"?n.symbol.toLowerCase():"";if(!r)return;let o=Array.isArray(n.data)?n.data:[n],s=o[o.length-1],i=Number(s?.value),a=Number(s?.timestamp);Number.isFinite(i)&&i>0&&zY(r,{value:i,timestamp:Number.isFinite(a)?a:Date.now()})}function KY(){Oy&&clearInterval(Oy),Lu&&clearTimeout(Lu),Ly&&clearTimeout(Ly),Oy=Lu=Ly=null}function JD(){KY();let e=Ms;if(Ms=null,e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.close()}catch{}}}function QD(){Lu&&clearTimeout(Lu),Lu=setTimeout(WP,jY)}function WP(){if(JD(),Bs.size===0)return;let e=YD[Math.min(VP,YD.length-1)];VP+=1,Ly=setTimeout(ZD,e)}function ZD(){if(Ms||Bs.size===0)return;let e=globalThis.WebSocket;if(!e)return;let t=new e(OP);Ms=t,t.onopen=()=>{t.send(jP("subscribe",[...Bs.keys()])),Oy=setInterval(()=>t.readyState===1&&t.send("ping"),WY),QD()},t.onmessage=n=>{VP=0,QD(),GY(n.data)},t.onclose=WP,t.onerror=WP}function eU(e,t){let n=e.toLowerCase(),r=Bs.get(n)??new Set,o=r.size===0;r.add(t),Bs.set(n,r);let s=$P.get(n);return s&&t(s),Ms?o&&Ms.readyState===1&&Ms.send(jP("subscribe",[n])):ZD(),()=>{let i=Bs.get(n);!i?.delete(t)||i.size>0||(Bs.delete(n),Bs.size===0?JD():Ms?.readyState===1&&Ms.send(jP("unsubscribe",[n])))}}var YY=.1;function Oe(e,t){if(e==null||e==="")return t;let n=typeof e=="number"?e:Number.parseFloat(String(e));return Number.isFinite(n)?n:t}function Uy(e){if(Array.isArray(e))return e;if(typeof e!="string"||e==="")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Wm(e){let t=String(e.version??"").trim().toLowerCase();return t===""||t==="v1"?"v1":t==="v2"?"v2":null}function zm(e){let t=e.feeSchedule??null,n=e.feesEnabled===!0?Oe(t?.rate,0):0,r=Oe(t?.exponent,1);return{rate:n>0&&n<1?n:0,exponent:r>0?r:1}}function Gm(e){return e.active!==!1&&e.archived!==!0&&e.closed!==!0&&e.acceptingOrders===!0&&e.enableOrderBook!==!1}function tU(e,t){return Uy(t==="v2"?e.positionIds:e.clobTokenIds).map(n=>String(n??"")).filter(Boolean)}function nU(e,t){let n=Uy(e.outcomes).map(o=>String(o)),r=tU(e,t);return n.length>=2&&r.length===n.length?n.map((o,s)=>({label:o,tokenId:r[s]})):[]}function zP(e){let t=Uy(e.outcomes).map(c=>String(c)),n=Uy(e.outcomePrices).map(c=>Oe(c,null)),r=Wm(e);if(r===null)return null;let o=tU(e,r);if(t.length<2||n.length!==t.length||o.length!==t.length||n.some(c=>c===null||c<0||c>1)||!e.id||!e.conditionId)return null;let s=(e.question??"").trim(),i=Oe(e.bestBid,null),a=Oe(e.bestAsk,null),l=Oe(e.lastTradePrice,null);return{id:String(e.id),slug:e.slug??"",conditionId:e.conditionId,question:s,label:(e.groupItemTitle??"").trim()||s,outcomes:t.map((c,u)=>({label:c,chance:n[u]})),clobTokenIds:o,protocol:r,volume:Oe(e.volumeNum??e.volume,0),volume24h:Oe(e.volume24hr,0),liquidity:Oe(e.liquidityNum??e.liquidity,0),endDate:e.endDate??null,open:Gm(e),fee:zm(e),priced:i!==null&&a!==null&&a-i<=YY+1e-9||l!==null&&l>0,negRisk:e.negRisk===!0,sportsMarketType:e.sportsMarketType??null,bestBid:i,bestAsk:a,oneDayPriceChange:Oe(e.oneDayPriceChange,null),groupItemThreshold:Oe(e.groupItemThreshold,null)}}function QY(e){let t=String(e.abbreviation??"").trim(),n=/^[a-z]{2,}\d+$/i.test(t)?t.replace(/\d+$/,""):t;return n?n.toUpperCase():null}function XY(e,t){if(e.sportsMarketType!=="moneyline"||t.length===0)return e;let n=new Map(t.map(r=>[lt(String(r.name??"")),QY(r)]));return{...e,outcomes:e.outcomes.map(r=>{let o=n.get(lt(r.label));return o?{...r,shortLabel:o}:r})}}function GP(e){return`${qi}/event/${e}`}function By(e){if(!e.id||!e.slug)return null;let t=e.negRisk===!0,n=Array.isArray(e.teams)?e.teams:[],r=(e.markets??[]).map(zP).filter(o=>o!==null).map(o=>XY({...o,negRisk:o.negRisk||t},n));return t?r.sort((o,s)=>s.outcomes[0].chance-o.outcomes[0].chance):r.every(o=>o.groupItemThreshold!==null)&&r.sort((o,s)=>(o.groupItemThreshold??0)-(s.groupItemThreshold??0)),{id:String(e.id),slug:e.slug,title:(e.title??"").trim(),description:(e.description??"").trim(),resolutionSource:(e.resolutionSource??"").trim(),image:e.image||e.icon||null,url:GP(e.slug),startDate:e.startDate??null,endDate:e.endDate??null,volume:Oe(e.volume,0),volume24h:Oe(e.volume24hr,0),liquidity:Oe(e.liquidity,0),negRisk:t,ended:e.ended===!0,markets:r,upDown:Dy(e.slug,e.markets?.[0])}}function Xa(e){return e.markets.find(t=>t.sportsMarketType==="moneyline")}function My(e,t=2){let n=e.markets.filter(l=>l.open);if(n.length===0)return null;let r=l=>l.priced?l.outcomes.slice(0,t):[],o=Xa(e);return o?o.open?{kind:"binary",outcomes:r(o),openMarketCount:n.length}:null:e.markets.length===1?{kind:"binary",outcomes:r(n[0]),openMarketCount:1}:{kind:"multi",outcomes:[...n.filter(l=>l.priced)].sort((l,c)=>c.outcomes[0].chance-l.outcomes[0].chance).slice(0,t).map(l=>({label:l.label,chance:l.outcomes[0].chance})),openMarketCount:n.length}}function Km(e){let t=/polymarket\.com\/(?:[a-z]{2}(?:-[a-z]{2})?\/)?event\/([a-z0-9-]+)(?:\/([a-z0-9-]+))?/i.exec(e);return t?{eventSlug:t[1].toLowerCase(),...t[2]?{marketSlug:t[2].toLowerCase()}:{}}:null}function rU(e){return`(prediction: ${e})`}function Ym(e){let t=/\(prediction:\s*([a-z0-9-]+)\s*\)/i.exec(e);return t?t[1].toLowerCase():null}function lt(e){let t=e.toLowerCase().replace(/đ/g,"d");try{t=t.normalize("NFD").replace(/[̀-ͯ]/g,"")}catch{}return t.replace(/[\s!-/:-@[-`{-~]+/g," ").trim()}function Fy(e){if(typeof e!="string"||!e.trim())return null;let t=lt(e);for(let n of $i)if([n.key,n.label,...n.aliases].map(lt).includes(t))return n;for(let n of $i)if([n.key,n.label,...n.aliases].map(lt).some(o=>o.length>=4&&(t.startsWith(o)||o.startsWith(t))))return n;return null}var fPe=$i.map(e=>e.key);var Go=1e-9,Ja=e=>Math.floor(e*100+Go)/100,oU=e=>Math.ceil(e*100-Go)/100;function Vi(e,t){return!t||!(t.rate>0)||!(e>0)||!(e<1)?0:t.rate*(e*(1-e))**t.exponent}function sU(e,t,n){return t>0?e/(1+Vi(t,n)/t):e}function iU(e,t,n){let r=[...e].sort((i,a)=>i.price-a.price),o=t,s=0;for(let i of r){if(o<=Go)break;if(!(i.price>0))continue;let a=1+Vi(i.price,n)/i.price,l=i.price*i.size,c=l*a;c>=o?(s+=o/a,o=0):(s+=l,o-=c)}return{notional:s,filled:o<=Go}}function aU(e,t,n){return Math.max(0,t-Du(e,t,n).feeUsd)}function KP(e,t,n){if(!(e>0)||e>1||!(t>0))return{usd:0,shares:0};let r=t*Vi(e,n),o=Number.isFinite(r)?Math.round(r*1e4)/1e4:0;return{usd:o,shares:o/e}}function YP(e,t,n){let r=Du(e,t,n),o=r.shares>0?t/r.shares:0,s=r.filled?KP(o,r.shares,n):{usd:0,shares:0},i=Math.max(0,r.shares-s.shares);return{shares:i,usd:t,feeUsd:s.usd,avgPrice:i>0?t/i:0,worstPrice:r.worstPrice,filled:r.filled}}function QP(e,t,n,r,o=0){if(!(t>0))return e;let s=Vi(t,r)*(1+o/100),a=Math.min(e,n)/t*s;return n<=e+a?Math.max(n-a,0):e}function Du(e,t,n){let r=[...e].sort((c,u)=>c.price-u.price),o=t,s=0,i=0,a=r[0]?.price??0;for(let c of r){if(o<=Go)break;let u=c.price*c.size;a=c.price;let d=u>=o?o/c.price:c.size;s+=d,i+=d*Vi(c.price,n),o=u>=o?0:o-u}let l=t-o;return{shares:s,usd:l,feeUsd:i,avgPrice:s>0?l/s:0,worstPrice:a,filled:o<=Go}}function XP(e,t,n){let r=[...e].sort((c,u)=>u.price-c.price),o=t,s=0,i=0,a=r[0]?.price??0;for(let c of r){if(o<=Go)break;let u=Math.min(o,c.size);a=c.price,s+=u*c.price,i+=u*Vi(c.price,n),o-=u}let l=t-o;return{shares:l,usd:s-i,feeUsd:i,avgPrice:l>0?s/l:0,worstPrice:a,filled:o<=Go}}function JP(e,t,n){return e?t.side==="BUY"?t.usd>0?Du(e.asks,t.usd,n):null:t.shares>0?XP(e.bids,t.shares,n):null:null}function qy(e,t,n,r=Vm.DEFAULT_SLIPPAGE){if(!(t>0))return e;let o=Math.max(0,Math.round(-Math.log10(t))),s=Math.round(e/t),i=n==="BUY"?Math.min(Math.ceil(s*(1+r)-Go),Math.round(1/t)-1):Math.max(Math.floor(s*(1-r)+Go),1);return Number((i*t).toFixed(o))}function lU(e,t,n,r=Vm.DEFAULT_SLIPPAGE,o="v1",s){let i=JP(t,n,s);if(!i||!t)return{error:Us.ENTER_AMOUNT,quote:null};if(i.shares<=0)return{error:Us.NO_LIQUIDITY,quote:i};if(n.side==="BUY"){let u=Ja(n.usd),d=qy(i.worstPrice,t.tickSize,"BUY",r),p=typeof n.cash=="number"&&n.cash>=0?n.cash:null,m=p===null?u:Ja(QP(u,d,p,s)),g=YP(t.asks,u,s);return u<Vm.MIN_BUY_USD?{error:Us.BELOW_MINIMUM,quote:g}:!g.filled||!Du(t.asks,m,s).filled?{error:Us.NOT_ENOUGH_LIQUIDITY,quote:g}:{quote:g,order:{tokenId:e,protocol:o,side:"BUY",amount:u,notional:m,maxPrice:d,...p===null?{}:{maxSpend:p}}}}let a=i,l=n.heldShares;if(l!==void 0&&n.shares>l+1e-6)return{error:Us.EXCEEDS_HOLDING,quote:a,maxShares:Ja(l)};if(!a.filled)return{error:Us.NOT_ENOUGH_LIQUIDITY,quote:a,maxShares:Ja(a.shares)};let c=Ja(l!==void 0?Math.min(n.shares,l):n.shares);return c<=0?{error:Us.TOO_SMALL,quote:a}:{quote:a,order:{tokenId:e,protocol:o,side:"SELL",shares:c,minPrice:qy(a.worstPrice,t.tickSize,"SELL",r)}}}function cU(e,t){let n=t==="BUY"?e?.asks[0]:e?.bids[0];return n?n.price:null}function Za(e,t){return e.filter(n=>Number.isFinite(n.price)&&Number.isFinite(n.size)&&n.size>0).sort((n,r)=>t==="bids"?r.price-n.price:n.price-r.price)}fw();var O_="0x0000000000000000000000000000000000000000",gw=(e,t)=>!!e&&!!t&&e.toLowerCase()===t.toLowerCase();function zr(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)}function yw(){return Rt(Hi)}var Eh=e=>e.toLowerCase();function UF(e){return Wt.encode([{type:"address"},{type:"bytes32"}],[Eh(Wr.depositWalletFactory),_t.padLeft(Eh(e),32)])}function KX(e,t){let n=BigInt((t.length-2)/2),r=Ds.PREFIX+(n<<BigInt(56));return Je.keccak256(_t.concat(_t.fromNumber(r,{size:10}),Eh(e),"0x6009",Ds.CONST2,Ds.CONST1,t))}function YX(e,t){let n=BigInt((t.length-2)/2),r=Ds.BEACON_PREFIX+(n<<BigInt(56));return Je.keccak256(_t.concat(_t.fromNumber(r,{size:10}),Eh(e),Ds.BEACON_CONST3,Ds.BEACON_CONST2,Ds.BEACON_CONST1,t))}function L_(e){let t=UF(e);return ho.fromCreate2({from:Wr.depositWalletFactory,salt:Je.keccak256(t),bytecodeHash:KX(Wr.depositWalletImplementation,t)})}function D_(e,t){let n=UF(e);return ho.fromCreate2({from:Wr.depositWalletFactory,salt:Je.keccak256(n),bytecodeHash:YX(t,n)})}function U_(e){return ho.fromCreate2({from:Wr.safeFactory,salt:Je.keccak256(Wt.encode([{type:"address"}],[Eh(e)])),bytecodeHash:Wr.safeInitCodeHash})}var Sh=null;function QX(e){return Sh||(Sh=XX(e),Sh.catch(()=>{Sh=null})),Sh}async function XX(e){try{let{data:t}=await e.call({to:Wr.depositWalletFactory,data:Wr.factoryBeaconSelector});return t&&t.length>=66?`0x${t.slice(-40)}`:O_}catch(t){if(jg(t)!==void 0)return O_;throw t}}async function Ph(e,t){return await e.getCode({address:t})!==void 0}async function B_(e,t=yw()){let n=L_(e),r=await QX(t);return gw(r,O_)||await Ph(t,n)?n:D_(e,r)}async function bw(e,t,n=yw()){if(t&&gw(t,e))return{address:e,owner:e,kind:"profile",deployed:await Ph(n,e)};let r=await B_(e,n),o=U_(e),[s,i]=await Promise.all([Ph(n,r),Ph(n,o)]);if(t){if(gw(t,o))return{address:o,owner:e,kind:"safe",deployed:i};if(gw(t,r))return{address:r,owner:e,kind:"deposit-wallet",deployed:s};if(await Ph(n,t))return{address:t,owner:e,kind:"profile",deployed:!0}}return s?{address:r,owner:e,kind:"deposit-wallet",deployed:!0}:i?{address:o,owner:e,kind:"safe",deployed:!0}:{address:r,owner:e,kind:"deposit-wallet",deployed:!1}}async function Rh(e,t=yw()){return t.readContract({address:Ls,abi:Ve,functionName:"balanceOf",args:[e]})}async function cd(e,t=yw()){return Number(await Rh(e,t))/10**zo}var Ys=class extends Error{status;constructor(t,n){super(n),this.name="PolymarketApiError",this.status=t}},_h=3e4,Ih=1e4,JX=60*6e4,ZX=64,BF=100,MF=1e3,eJ=new Set([429,500,502,503,504]),FF=2,tJ=3e3,nJ={active:"true",archived:"false",closed:"false",featured_order:"true",order:"featuredOrder",ascending:"true"},qF={closed:"false",order:"volume",ascending:"false",limit:"50"},rJ=50,oJ=5e3,sJ="1",iJ="64",HF=e=>new Promise(t=>setTimeout(t,e));function $F(e,t){let n=t?Number(t)*1e3:NaN;return Number.isFinite(n)&&n>=0?Math.min(n,tJ):400*2**e}async function ww(e,t){try{return await e}catch(n){if(WF(n))throw n;return t}}function WF(e){let t=e?.name,n=e?.code;return t==="AbortError"||t==="CanceledError"||n==="ERR_CANCELED"}var Ye=class{gamma;data;bridge;builderCode;clob;web;cache=new Map;accounts=new Map;constructor(t={}){this.gamma=(t.gammaBaseUrl??Fi.GAMMA).replace(/\/+$/,""),this.data=(t.dataBaseUrl??Fi.DATA).replace(/\/+$/,""),this.bridge=(t.bridgeBaseUrl??Fi.BRIDGE).replace(/\/+$/,""),this.builderCode=t.builderCode,this.clob=(t.clobBaseUrl??Fi.CLOB).replace(/\/+$/,""),this.web=(t.webBaseUrl??qi).replace(/\/+$/,"")}async listEvents({sort:t,tagId:n,limit:r}){let{order:o,ascending:s}=$m[t],i={closed:"false",order:o,ascending:String(s),limit:String(Math.min(Math.max(1,r),BF))};n&&(i.tag_id=n),t==="ending_soon"&&(i.end_date_min=new Date(Math.floor(Date.now()/6e4)*6e4).toISOString()),(t==="ending_soon"||t==="competitive")&&(i.exclude_tag_id=[UP]),t==="new"&&!n&&(i.exclude_tag_id=[BP,MP]);let a=this.eventRows(i);if(t!=="trending"||n)return vw(await a);let l=Date.now(),[c,u,d,p,m]=await Promise.all([a,ww(this.eventRows({...nJ,limit:String(rJ)}),[]),ww(this.eventRows({...qF,tag_id:sJ}),[]),ww(this.eventRows({...qF,tag_id:iJ}),[]),ww(this.eventRows({slug:WD(l),limit:"1"}).then(g=>g[0]??null),null)]);return vw(GD({feed:c,featured:u,sports:[...d,...p],btc5m:m},l))}async eventRows(t){let n=await this.getJson(`${this.gamma}/events/keyset`,t,_h);return Array.isArray(n.events)?n.events:[]}async getUpDownPrices(t){let n=await this.getJson(`${this.web}/api/crypto/crypto-price`,XD(t),oJ),r=o=>{let s=Oe(o,null);return s!==null&&s>0?s:null};return{openPrice:r(n?.openPrice),closePrice:r(n?.closePrice),completed:n?.completed===!0}}async searchEvents(t,n){let r=t.trim();if(!r)return[];let s=((await this.getJson(`${this.gamma}/public-search`,{q:r,events_status:"active",limit_per_type:String(Math.min(Math.max(1,n),50)),keep_closed_markets:"0"},_h)).events??[]).map(l=>l.id).filter(l=>typeof l=="string"&&!!l);if(s.length===0)return[];let i=await this.getJson(`${this.gamma}/events/keyset`,{id:s,limit:String(Math.min(s.length,BF))},_h),a=new Map(vw(i.events).map(l=>[l.id,l]));return s.map(l=>a.get(l)).filter(l=>l!==void 0)}async getEventBySlug(t){let n=await this.getJson(`${this.gamma}/events/keyset`,{slug:t,limit:"1"},_h);return vw(n.events)[0]??null}async getMarketTradeInfo(t){if(!/^0x[0-9a-fA-F]{64}$/.test(t))return null;let r=(await this.getJson(`${this.gamma}/markets/keyset`,{condition_ids:t,limit:"1"},_h)).markets?.[0];if(!r)return null;let o=Wm(r);return o===null?null:{conditionId:t,protocol:o,fee:zm(r),negRisk:r.negRisk===!0,open:Gm(r),outcomes:nU(r,o),question:(r.question??"").trim(),label:(r.groupItemTitle??"").trim(),eventTitle:(r.events?.[0]?.title??"").trim()}}async getProfileWallet(t){try{let n=await this.getJson(`${this.gamma}/public-profile`,{address:t},Ih);return typeof n.proxyWallet=="string"&&n.proxyWallet?n.proxyWallet:null}catch(n){if(n instanceof Ys&&n.status===404)return null;throw n}}async resolveAccount(t){let n=t.toLowerCase(),r=this.accounts.get(n);if(r&&(r.account.deployed||Date.now()-r.at<Ih))return r.account;let o=await bw(t,await this.getProfileWallet(t));return this.accounts.set(n,{account:o,at:Date.now()}),o}async getCash(t){return cd(t)}async getPositionsValue(t){let n=await this.getJson(`${this.data}/v2/value`,{user:t},Ih);return Oe(n?.data?.value,0)}async getPositions(t,n,r={}){let o=await this.getJson(`${this.data}/v2/positions`,{user:t,status:"OPEN",filter_type:"TOKENS",filter_amount:String(qP),sort_by:"CURRENT_VALUE",sort_direction:"DESC",limit:String(Math.min(Math.max(1,n),MF))},r.fresh?0:Ih);return jF(o).map(uJ)}async getActivity(t,n){let r=await this.getJson(`${this.data}/v2/activity`,{user:t,type:FP.join(","),sort_direction:"DESC",limit:String(Math.min(Math.max(1,n),MF))},Ih);return jF(r).map(dJ)}async getBridgeAssets(){return((await this.getJson(`${this.bridge}/supported-assets`,{},JX)).supportedAssets??[]).map(mJ).filter(n=>n!==null)}async getDepositAddresses(t){let r=(await this.requestJson("POST",`${this.bridge}/deposit`,{body:{address:t},headers:{"X-Builder-Code":this.builderCode??Ou()}})).address??{},o=typeof r.evm=="string"&&/^0x[0-9a-fA-F]{40}$/.test(r.evm)?r.evm:"";if(!o)throw new Ys(502,"Bridge returned no EVM deposit address");return{evm:o,svm:Ze(r.svm),btc:Ze(r.btc),tron:Ze(r.tron)}}async createWithdrawalAddresses(t){let r=(await this.requestJson("POST",`${this.bridge}/withdraw`,{body:{address:t.wallet,toChainId:t.toChainId,toTokenAddress:t.toTokenAddress,recipientAddr:t.recipient},headers:{"X-Builder-Code":this.builderCode??Ou()}})).address??{},o=typeof r.evm=="string"&&/^0x[0-9a-fA-F]{40}$/.test(r.evm)?r.evm:"";if(!o)throw new Ys(502,"Bridge returned no EVM withdrawal address");return{evm:o,svm:Ze(r.svm),btc:Ze(r.btc),tron:Ze(r.tron)}}async getBridgeQuote(t){let n=await this.requestJson("POST",`${this.bridge}/quote`,{body:t}),r=n.estFeeBreakdown??{},o=Ze(n.estToTokenBaseUnit);if(!/^\d+$/.test(o))throw new Ys(502,"Bridge returned no quote");return{estToTokenBaseUnit:o,estOutputUsd:Oe(n.estOutputUsd,0),estInputUsd:Oe(n.estInputUsd,0),estCheckoutTimeMs:Oe(n.estCheckoutTimeMs,null),minReceived:Oe(r.minReceived,null),totalImpactUsd:Oe(r.totalImpactUsd,0),totalImpactPercent:Oe(r.totalImpact,0),quoteId:Ze(n.quoteId)}}async getBridgeTransfers(t){return/^0x[0-9a-fA-F]{40}$/.test(t)?((await this.requestJson("GET",`${this.bridge}/status/${t}`)).transactions??[]).map(hJ).sort((r,o)=>(o.createdTimeMs??0)-(r.createdTimeMs??0)):[]}async getOrderBook(t,n){let r=await this.requestJson("GET",`${this.clob}/book?${VF({token_id:t})}`,{signal:n});return aJ(t,r)}getJson(t,n,r){let o=VF(n),s=o?`${t}?${o}`:t,i=this.cache.get(s);if(i&&Date.now()-i.at<i.ttl)return i.value;let a=this.requestJson("GET",s);if(a.catch(()=>{this.cache.get(s)?.value===a&&this.cache.delete(s)}),this.cache.size>=ZX){let l=this.cache.keys().next().value;l!==void 0&&this.cache.delete(l)}return this.cache.set(s,{at:Date.now(),ttl:r,value:a}),a}async requestJson(t,n,r={}){for(let o=0;;o++){let s;try{s=await se.request(t,n,r.body,{...r.signal?{signal:r.signal}:{},headers:{...r.body!==void 0?{"Content-Type":"application/json"}:{},...r.headers}})}catch(i){if(WF(i)||o>=FF)throw i;await HF($F(o));continue}if(s.ok)return s.data;if(!eJ.has(s.status)||o>=FF)throw new Ys(s.status,he(s));await HF($F(o,s.headers["retry-after"]))}}};function VF(e){let t=[];for(let[n,r]of Object.entries(e))for(let o of Array.isArray(r)?r:[r])t.push(`${encodeURIComponent(n)}=${encodeURIComponent(o)}`);return t.join("&")}function vw(e){return(Array.isArray(e)?e:[]).map(By).filter(t=>t!==null)}var Ze=e=>typeof e=="string"?e:"";function aJ(e,t){let n=r=>(r??[]).map(o=>({price:Oe(o.price,NaN),size:Oe(o.size,NaN)}));return{tokenId:e,bids:Za(n(t.bids),"bids"),asks:Za(n(t.asks),"asks"),tickSize:Oe(t.tick_size,.01),minOrderSize:Oe(t.min_order_size,0),negRisk:t.neg_risk===!0,lastTradePrice:Oe(t.last_trade_price,null),updatedAt:Date.now()}}var jF=e=>Array.isArray(e?.data)?e.data:[],lJ="1970-01-01",cJ=999;function uJ(e){let t=Ze(e.end_date),n=Oe(e.outcome_index,0);return{title:Ze(e.title),outcome:Ze(e.outcome),eventSlug:Ze(e.event_slug),conditionId:Ze(e.condition_id),asset:Ze(e.token_id),outcomeIndex:n===cJ?0:n,oppositeOutcome:Ze(e.opposite_outcome),oppositeAsset:Ze(e.opposite_token_id),icon:Ze(e.icon)||null,shares:Oe(e.current_size,0),avgPrice:Oe(e.avg_price,0),curPrice:Oe(e.current_price,0),initialValue:Oe(e.entry_cost_usdc,0),currentValue:Oe(e.current_value,0),cashPnl:Oe(e.unrealized_pnl,0),percentPnl:Oe(e.percent_pnl,0),redeemable:e.redeemable===!0,endDate:t&&t!==lJ?t:null}}function dJ(e){let t=Ze(e.side).toUpperCase();return{type:Ze(e.type).toUpperCase(),side:t==="BUY"||t==="SELL"?t:null,title:Ze(e.title),outcome:Ze(e.outcome),eventSlug:Ze(e.event_slug),shares:Oe(e.size,0),usd:Oe(e.usdc_size,0),price:Oe(e.price,0),timestamp:Oe(e.timestamp,0),transactionHash:Ze(e.transaction_hash)}}var pJ="0x0000000000000000000000000000000000000000";function mJ(e){let t=e.token??{},n=Ze(t.address).toLowerCase(),r=Oe(t.decimals,NaN);return!e.chainId||!n||!Number.isInteger(r)?null:{chainId:String(e.chainId),chainName:Ze(e.chainName),symbol:Ze(t.symbol),name:Ze(t.name),address:n===NP?pJ:n,decimals:r,minUsd:Oe(e.minCheckoutUsd,0)}}function hJ(e){return{fromChainId:String(e.fromChainId??""),fromTokenAddress:Ze(e.fromTokenAddress).toLowerCase(),fromAmountBaseUnit:String(e.fromAmountBaseUnit??"0"),toChainId:String(e.toChainId??""),status:Ze(e.status).toUpperCase(),txHash:Ze(e.txHash)||null,createdTimeMs:Oe(e.createdTimeMs,null)}}var zF=require("@noble/hashes/hmac"),GF=require("@noble/hashes/sha2");function M_(e,t,n,r,o){let s=`${t}${n}${r}${o??""}`,i=(0,zF.hmac)(GF.sha256,gJ(e),new TextEncoder().encode(s));return yJ(i).replace(/\+/g,"-").replace(/\//g,"_")}function ts(e){return typeof e?.authorize=="function"?e:F_(e)}var fJ=["POLY_BUILDER_API_KEY","POLY_BUILDER_PASSPHRASE","POLY_BUILDER_SIGNATURE","POLY_BUILDER_TIMESTAMP"];function KF(e){return{isBuilderKey:!0,supportGasless:!0,async authorize({method:t,path:n,body:r}){let o=typeof e.headers=="function"?await e.headers():e.headers,s=await fetch(e.url,{method:"POST",headers:{...o??{},"Content-Type":"application/json"},body:JSON.stringify({method:t,path:n,body:r}),credentials:e.credentials});if(!s.ok)throw new Error(`Remote builder signer rejected the request (${s.status})`);let i=await s.json(),a={};for(let l of fJ){let c=i?.[l];if(typeof c!="string"||!c)throw new Error(`Remote builder signer answered without ${l}`);a[l]=c}return a}}}function F_(e){return{isBuilderKey:!0,supportGasless:!0,async authorize({method:t,path:n,body:r}){let o=Math.floor(Date.now()/1e3);return{POLY_BUILDER_API_KEY:e.key,POLY_BUILDER_PASSPHRASE:e.passphrase,POLY_BUILDER_SIGNATURE:M_(e.secret,o,t,n,r),POLY_BUILDER_TIMESTAMP:String(o)}}}}function gJ(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}function yJ(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}var bJ=new Set(["STATE_CONFIRMED","STATE_FAILED","STATE_INVALID"]),wJ=e=>new Promise(t=>setTimeout(t,e));async function YF(e,t={}){let n=await fetch(`${Fi.RELAYER}${e}`,t),r=await n.text(),o;try{o=r?JSON.parse(r):null}catch{o=null}if(!n.ok){let s=o?.error||r||`HTTP ${n.status}`;throw new Error(`Relayer ${t.method??"GET"} ${e} failed (${n.status}): ${s}`)}return o}async function vJ(e,t,n){let r=JSON.stringify({type:"WALLET-CREATE",from:e,to:Wr.depositWalletFactory,metadata:"Deploy Deposit Wallet"}),o=await ts(t).authorize({method:"POST",path:_y,body:r});return YF(_y,{method:"POST",headers:{"Content-Type":"application/json",...o},body:r,signal:n})}async function kJ(e,t){let n=Date.now();for(;Date.now()-n<Iy.TIMEOUT_MS;){let r=await YF(`/transaction?id=${encodeURIComponent(e)}`,{signal:t}),o=Array.isArray(r)?r[0]:null;if(!o)throw new Error("Relayer transaction not found");if(bJ.has(o.state))return o;if(t?.aborted)throw new Error("Cancelled");await wJ(Iy.INTERVAL_MS)}throw new Error("Deploy timed out")}async function kw(e,t,n){let r=await vJ(e,t,n),o=await kJ(r.transactionID,n);if(o.state!=="STATE_CONFIRMED")throw new Error(`Deposit wallet deployment failed: ${o.error_msg||o.state}`);return{transactionHash:o.transactionHash,proxyAddress:o.proxyAddress,state:o.state}}var mT=null;function Vme(){let e=globalThis.URLSearchParams;typeof e!="function"||"size"in e.prototype||Object.defineProperty(e.prototype,"size",{configurable:!0,get(){let t=0;return this.forEach(()=>{t+=1}),t}})}function ca(){return Vme(),mT??=Promise.all([Promise.resolve().then(()=>(oj(),rj)),Promise.resolve().then(()=>(ij(),sj))]).then(([e,t])=>({sdk:e,actions:t})),mT.catch(()=>{mT=null}),mT}async function ua(){let{sdk:e}=await ca(),t=$o(Hi);return t?e.forkEnvironmentConfig({name:"production",rpc:t},e.production):e.production}var tL=new Map,hT=()=>{let e=$o(Hi)??"",t=tL.get(e);return t||(t=ua().then(async n=>(await ca()).sdk.createPublicClient({environment:n})),t.catch(()=>tL.delete(e)),tL.set(e,t)),t};function da(e){return{async getAddress(){return e.address},async signTypedData(t){let{EIP712Domain:n,...r}=t.types;return await e.signTypedData({...t,types:r})},async signMessage(t){if(!e.signMessage)throw new Error("Polymarket signer: signMessage is not supported by this wallet");return await e.signMessage(t)},async sendTransaction(){throw new Error("Polymarket signer: direct transactions are not supported \u2014 use the gasless relayer")}}}var jme=(BigInt(1)<<BigInt(256))-BigInt(1),Wme=[{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]}];async function fT(e){let[t,n]=await Promise.all([hT().then(i=>i.fetchTradingApprovalsState({user:e})),ua()]),r=new Set(zme(n).map(i=>i.toLowerCase())),o=(t.missing?.erc20??[]).map(i=>({tokenAddress:i.tokenAddress,spenderAddress:i.spenderAddress})).filter(i=>!r.has(String(i.spenderAddress).toLowerCase())),s=(t.missing?.erc1155??[]).map(i=>({tokenAddress:i.tokenAddress,operatorAddress:i.operatorAddress})).filter(i=>!r.has(String(i.operatorAddress).toLowerCase()));return{isFullyApproved:o.length===0&&s.length===0,missing:{erc20:o,erc1155:s}}}function zme(e){let t=e?.contracts?.perpsDepositContract;return[typeof t=="string"&&t?t:LP]}async function ys(e,t=new Ye){let n=await t.resolveAccount(e),r=n.deployed?await fT(n.address):null;return{account:n,approvals:r}}function lj(e){return e.isDeployed?e.isTradingEnabled?e.isApproved?on.DONE:on.APPROVE:on.ENABLE_TRADING:on.DEPLOY}function nL(e){return[...e.erc20.map(t=>({to:t.tokenAddress,data:Le({abi:Ve,functionName:"approve",args:[t.spenderAddress,jme]})})),...e.erc1155.map(t=>({to:t.tokenAddress,data:Le({abi:Wme,functionName:"setApprovalForAll",args:[t.operatorAddress,!0]})}))]}var hi=class extends Error{step;constructor(t,n,r){super(n),this.name="PolymarketOnboardingError",this.step=t,r!==void 0&&(this.cause=r)}};async function cj(e){let t=e.service??new Ye,n=e.tracking??{intervalMs:Cy.INTERVAL_MS,maxAttempts:Cy.MAX_ATTEMPTS},r=da(e.signer),o=e.chain?.approvals??fT,s=f=>{Gme(e.signal,f),e.onStep?.(f)},i=await t.resolveAccount(e.signer.address);if(i.kind==="profile")throw new hi(on.ENABLE_TRADING,"This address is a Polymarket account wallet, not a wallet that can sign for one.");let a=e.chain?.isDeployed??(async f=>await Rt(Hi).getCode({address:f})!==void 0);i.deployed||(s(on.DEPLOY),await Kd(on.DEPLOY,async()=>{await kw(e.signer.address,e.builder,e.signal),await aj(()=>a(i.address),f=>f,n,e.signal)}),i={...i,deployed:!0});let{sdk:l,actions:c}=await ca(),u=ts(e.builder),d=await ua();s(on.ENABLE_TRADING);let p=await Kd(on.ENABLE_TRADING,()=>l.createSecureClient({environment:d,signer:r,apiKey:u,wallet:i.address,...e.credentials?{credentials:{...e.credentials}}:{}})),m=og(p);if(!m)throw new hi(on.ENABLE_TRADING,"No CLOB credentials were issued.");await Kd(on.ENABLE_TRADING,async()=>e.onCredentials?.(m));let g=await Kd(on.APPROVE,()=>o(i.address));return g.isFullyApproved||(s(on.APPROVE),g=await Kd(on.APPROVE,async()=>{let f=nL(g.missing),y=await c.prepareGaslessTransaction(p,{calls:f,metadata:DP});return await(await Kme(y,r)).wait(),aj(()=>o(i.address),v=>v.isFullyApproved,n,e.signal)})),await Kd(on.APPROVE,()=>c.updateBalanceAllowance(p,{assetType:"COLLATERAL"})),s(on.DONE),{account:i,credentials:m,approvals:g}}function og(e){let{key:t,secret:n,passphrase:r}=e?.credentials??{};return typeof t=="string"&&t&&typeof n=="string"&&n&&typeof r=="string"&&r?{key:t,secret:n,passphrase:r}:null}async function Kd(e,t){try{return await t()}catch(n){if(n instanceof hi)throw n;let r=n instanceof Error&&n.message?n.message:String(n);throw new hi(e,r,n)}}function Gme(e,t){if(e?.aborted)throw new hi(t,"Cancelled")}async function aj(e,t,n,r){for(let o=1;;o++){let s=await e();if(t(s))return s;if(o>=n.maxAttempts)throw new Error("Not confirmed on-chain yet \u2014 please try again in a moment.");if(r?.aborted)throw new Error("Cancelled");await new Promise(i=>setTimeout(i,n.intervalMs))}}async function Kme(e,t){let n=await e.next();for(;!n.done;){let r=n.value;try{switch(r.kind){case"requestAddress":n=await e.next(await t.getAddress());break;case"signGaslessTypedData":n=await e.next(await t.signTypedData(r.payload));break;case"signGaslessMessage":n=await e.next(await t.signMessage(r.payload));break;default:throw new Error(`Unsupported gasless workflow request: ${String(r.kind)}`)}}catch(o){n=await e.throw(o)}}return n.value}var uj=new Set(Hm),Yme="0x0000000000000000000000000000000000000000";function rL(e){return e.filter(t=>/^\d+$/.test(t.chainId)&&Number(t.chainId)>0&&Number(t.chainId)<2**32&&t.address!==Yme&&/^0x[0-9a-f]{40}$/.test(t.address)&&uj.has(t.symbol.toUpperCase()))}async function gT(e,t){let n=new Map;for(let o of rL(t)){let s=Number(o.chainId),i=n.get(s)??[];i.some(a=>a.address===o.address)||i.push(o),n.set(s,i)}return(await Promise.allSettled([...n.entries()].map(async([o,s])=>{let i=`0x${o.toString(16)}`,l=await Rt(i).multicall({contracts:s.flatMap(c=>[{address:c.address,abi:Ve,functionName:"balanceOf",args:[e]},{address:c.address,abi:Ve,functionName:"decimals"}]),allowFailure:!0});return s.flatMap((c,u)=>{let d=l[2*u],p=l[2*u+1],m=d?.status==="success"&&typeof d.result=="bigint"?d.result:BigInt(0),g=p?.status==="success"&&(typeof p.result=="number"||typeof p.result=="bigint")?Number(p.result):NaN;return m<=BigInt(0)||!Number.isInteger(g)?[]:[{chainId:o,chainHex:i,chainName:j(i)||c.symbol,tokenAddress:c.address,symbol:c.symbol,decimals:g,balance:Jc(m,g),minUsd:c.minUsd}]})}))).flatMap(o=>o.status==="fulfilled"?o.value:[]).sort((o,s)=>Number(s.balance)-Number(o.balance))}var Qme=e=>/^\d+$/.test(e)&&Number(e)>0&&Number(e)<2**32&&!(e in Ya);function yT(e){let t=o=>{let s=gn.CHAIN_ORDER.indexOf(o);return s===-1?gn.CHAIN_ORDER.length:s},n=o=>{let s=Hm.indexOf(o.toUpperCase());return s===-1?Hm.length:s},r=new Set;return e.filter(o=>Qme(o.chainId)&&/^0x[0-9a-f]{40}$/.test(o.address)&&o.symbol).filter(o=>{let s=`${o.chainId}:${o.address}`;return r.has(s)?!1:(r.add(s),!0)}).map(o=>({chainId:o.chainId,chainName:o.chainName,symbol:o.symbol,tokenAddress:o.address,decimals:o.decimals,minUsd:o.minUsd,stable:uj.has(o.symbol.toUpperCase())})).sort((o,s)=>t(o.chainId)-t(s.chainId)||o.chainName.localeCompare(s.chainName)||n(o.symbol)-n(s.symbol)||o.symbol.localeCompare(s.symbol))}async function sg(e,t=new Ye){let n=Is(String(e.amount??"").trim(),e.asset.decimals);if(n===null||n<=BigInt(0))throw new Error("Enter an amount");let r=await t.getBridgeQuote({fromAmountBaseUnit:n.toString(),fromChainId:e.asset.chainId,fromTokenAddress:e.asset.tokenAddress,recipientAddress:e.wallet,toChainId:qm,toTokenAddress:Ls});return{estInputUsd:r.estInputUsd,estOutputUsd:r.estOutputUsd,priceImpactPercent:r.totalImpactPercent,totalFeeUsd:r.totalImpactUsd,minReceivedUsd:r.minReceived,estTimeMs:r.estCheckoutTimeMs}}var oL=100;async function dj(e,t,n=new Ye){let r=Math.max(oL,e.minUsd||0);if(e.stable)return sg({asset:e,amount:String(r),wallet:t},n);let o=await sg({asset:e,amount:"1",wallet:t},n);if(!(o.estInputUsd>0))return o;let s=(r/o.estInputUsd).toFixed(Math.min(e.decimals,8));return sg({asset:e,amount:s,wallet:t},n)}var Dr=e=>{let t=typeof e=="number"?e:Number.parseFloat(String(e??""));return Number.isFinite(t)?t:NaN},bT=e=>{let t=Dr(e);return Number.isFinite(t)?String(t):""};function pj(e,t){return Za([...e.entries()].map(([n,r])=>({price:Number(n),size:r})),t)}function Xme(e){return{bids:new Map(e.bids.map(t=>[bT(t.price),t.size])),asks:new Map(e.asks.map(t=>[bT(t.price),t.size])),tickSize:e.tickSize,minOrderSize:e.minOrderSize,negRisk:e.negRisk,lastTradePrice:e.lastTradePrice,updatedAt:e.updatedAt}}function Jme(e,t){return{tokenId:e,bids:pj(t.bids,"bids"),asks:pj(t.asks,"asks"),tickSize:t.tickSize,minOrderSize:t.minOrderSize,negRisk:t.negRisk,lastTradePrice:t.lastTradePrice,updatedAt:t.updatedAt}}function sL(e,t,n=Date.now()){let r=t?.payload??{};switch(t?.type){case"book":{let o=e.get(String(r.assetId));if(!o)return!1;let s=i=>[bT(i.price),Dr(i.size)];return o.bids=new Map((r.bids??[]).map(s).filter(([i,a])=>i&&a>0)),o.asks=new Map((r.asks??[]).map(s).filter(([i,a])=>i&&a>0)),Number.isFinite(Dr(r.tickSize))&&(o.tickSize=Dr(r.tickSize)),Number.isFinite(Dr(r.minOrderSize))&&(o.minOrderSize=Dr(r.minOrderSize)),typeof r.negRisk=="boolean"&&(o.negRisk=r.negRisk),Number.isFinite(Dr(r.lastTradePrice))&&(o.lastTradePrice=Dr(r.lastTradePrice)),o.updatedAt=n,!0}case"price_change":{let o=!1;for(let s of r.priceChanges??[]){let i=e.get(String(s.assetId)),a=bT(s.price);if(!i||!a)continue;let l=String(s.side).toUpperCase()==="BUY"?i.bids:i.asks,c=Dr(s.size);c>0?l.set(a,c):l.delete(a),i.updatedAt=n,o=!0}return o}case"last_trade_price":{let o=e.get(String(r.assetId));return!o||!Number.isFinite(Dr(r.price))?!1:(o.lastTradePrice=Dr(r.price),o.updatedAt=n,!0)}case"tick_size_change":{let o=e.get(String(r.assetId));return!o||!Number.isFinite(Dr(r.newTickSize))?!1:(o.tickSize=Dr(r.newTickSize),o.updatedAt=n,!0)}default:return!1}}function mj(e,t){let n=[...new Set(e.filter(Boolean))],r=t.service??new Ye,o=t.throttleMs??jm.THROTTLE_MS,s=t.staleMs??jm.STALE_MS,i=t.fallbackPollMs??jm.FALLBACK_POLL_MS,a=new Map,l=new AbortController,c=!1,u=null,d=null,p=Date.now(),m=0,g=null,f=null,y=null,w=V=>{u!==V&&(u=V,t.onStatus?.(V))},v=()=>{let V={};for(let[Y,te]of a)V[Y]=Jme(Y,te);return V},A=()=>{c||(g&&clearTimeout(g),g=null,m=Date.now(),t.onUpdate(v()))},k=()=>{if(c||g)return;let V=o-(Date.now()-m);V<=0?A():g=setTimeout(A,V)},T=()=>(y??=Promise.all(n.map(async V=>{try{let Y=await r.getOrderBook(V,l.signal);a.set(V,Xme(Y))}catch(Y){c||t.onError?.(Y)}})).then(()=>(p=Date.now(),A(),v())).finally(()=>{y=null}),y),D=V=>new Promise(Y=>{let te=setTimeout(Y,V);l.signal.addEventListener("abort",()=>{clearTimeout(te),Y()})}),q=async()=>{for(w("connecting"),await T();!c;){try{let V=await hT();if(c)break;if(d=await V.subscribe([{topic:"market",assetIds:n,customFeatureEnabled:!1}]),c){d.close();break}w("live");for await(let Y of d){if(c)break;p=Date.now(),sL(a,Y,p)&&k()}}catch(V){c||t.onError?.(V)}if(d=null,c)break;w("polling"),await T(),await D(i)}};return f=setInterval(()=>{!c&&Date.now()-p>s&&T()},Math.max(1e3,Math.floor(s/2))),q(),{refresh:T,stop(){c||(c=!0,l.abort(),g&&clearTimeout(g),f&&clearInterval(f),d?.close(),w("stopped"))}}}var Zme=(e,t)=>!!e&&!!t&&e.key===t.key&&e.secret===t.secret&&e.passphrase===t.passphrase;async function Yd(e){let{sdk:t}=await ca(),n=await t.createSecureClient({environment:await ua(),signer:da(e.signer),apiKey:ts(e.builder),wallet:e.wallet,...e.credentials?{credentials:{...e.credentials}}:{}}),r=og(n);return r&&!Zme(r,e.credentials)&&await e.onCredentials?.(r),n}function Qd(e){let t=e??{},n=String(t.message??"");return t.name==="CancelledSigningError"||/user (rejected|denied)|cancel(l)?ed/i.test(n)&&!/order (was )?cancel/i.test(n)}var pa=class extends Error{code;constructor(t,n,r){super(n),this.name="PolymarketTradeError",this.code=t,r!==void 0&&(this.cause=r)}},ehe=15e3,hj={unmatched:bt.NOT_FILLED,fak_not_filled:bt.NOT_FILLED,fok_not_filled:bt.NOT_FILLED,insufficient_balance_or_allowance:bt.INSUFFICIENT_BALANCE,market_not_ready:bt.MARKET_CLOSED,post_only_mode:bt.TRADING_PAUSED},the=[[/not enough balance \/ allowance/i,bt.INSUFFICIENT_BALANCE],[/lower than the minimum/i,bt.BELOW_MIN_SIZE],[/closed only mode/i,bt.CLOSE_ONLY],[/address banned/i,bt.ACCOUNT_BANNED],[/no orders found to match|couldn't be fully filled|not filled/i,bt.NOT_FILLED],[/not yet ready to process|market (is )?(closed|not active|resolved)|orderbook .* does not exist/i,bt.MARKET_CLOSED],[/post-only mode|trading is (currently )?(paused|disabled)|cancel-only/i,bt.TRADING_PAUSED]],nhe=e=>/not enough balance \/ allowance/i.test(String(e?.message??""));function aL(e){if(e instanceof pa)return e;let t=e??{},n=t.message||String(e),r=the.find(([s])=>s.test(n))?.[1],o=r===bt.CLOSE_ONLY||r===bt.ACCOUNT_BANNED?r:/restrict|region|geoblock|jurisdiction|not available in your/i.test(n)||t.status===403&&!t.restriction?bt.REGION_RESTRICTED:t.restriction?bt.TRADING_PAUSED:t.name==="InsufficientLiquidityError"?bt.NOT_ENOUGH_LIQUIDITY:Qd(e)?bt.CANCELLED:(r??(t.code&&hj[t.code]))||bt.FAILED;return new pa(o,n,e)}var rhe=(e,t)=>!!e&&!!t&&e.key===t.key&&e.secret===t.secret&&e.passphrase===t.passphrase,iL=e=>{let t=Number.parseFloat(String(e??""));return Number.isFinite(t)?t:0};async function fj(e){let{order:t}=e;try{let{sdk:n,actions:r}=await ca(),o=await n.createSecureClient({environment:await ua(),signer:da(e.signer),apiKey:ts(e.builder),wallet:e.wallet,...e.credentials?{credentials:{...e.credentials}}:{}}),s=og(o);s&&!rhe(s,e.credentials)&&await e.onCredentials?.(s);let i=e.builderCode??Ou(),a=t.side==="BUY"?{assetId:t.tokenId,side:n.OrderSide.BUY,amount:t.notional&&t.notional>0?t.notional:t.amount,...t.maxSpend!==void 0&&t.maxSpend>0?{maxSpend:t.maxSpend}:{},maxPrice:t.maxPrice,builderCode:i,orderType:n.OrderType.FAK}:{assetId:t.tokenId,side:n.OrderSide.SELL,shares:t.shares,minPrice:t.minPrice,builderCode:i,orderType:n.OrderType.FAK},c=await(async()=>{try{return await o.placeMarketOrder(a)}catch(g){if(nhe(g))return{ok:!1,code:"insufficient_balance_or_allowance",error:g};throw g}})();if(!c.ok&&c.code==="insufficient_balance_or_allowance"&&(await r.updateBalanceAllowance(o,ohe(t)),c=await o.placeMarketOrder(a)),!c.ok)throw new pa(hj[c.code]??bt.FAILED,c.message||c.code||"Order rejected");if(String(c.status).toLowerCase()===wT.DELAYED)return await she(o,String(c.orderId),t,e.delayedTimeoutMs);let u=iL(c.makingAmount),d=iL(c.takingAmount),p=Array.isArray(c.transactionsHashes)?c.transactionsHashes:[],m=e.settlementTimeoutMs??ehe;if(p.length===0&&m>0&&(c.tradeIds?.length??0)>0){let g;p=await Promise.race([r.waitForOrderFillSettlement(o,c).catch(()=>[]),new Promise(f=>{g=setTimeout(()=>f([]),m)})]).finally(()=>clearTimeout(g))}return{orderId:String(c.orderId),status:String(c.status),pending:!1,side:t.side,shares:t.side==="BUY"?d:u,usd:t.side==="BUY"?u:d,transactionHashes:p}}catch(n){throw aL(n)}}var wT={DELAYED:"delayed",LIVE:"live",MATCHED:"matched",UNMATCHED:"unmatched"};function ohe(e){return e.side==="BUY"?{assetType:"COLLATERAL"}:{assetType:e.protocol==="v2"?"CONDITIONAL-V2":"CONDITIONAL",assetId:e.tokenId}}async function she(e,t,n,r){let o=Date.now()+(r??Ny.TIMEOUT_MS);for(;;){await new Promise(c=>setTimeout(c,Ny.POLL_MS));let s=null;try{s=await e.fetchOrder({orderId:t})}catch{}let i=String(s?.status??"").toLowerCase(),a=iL(s?.sizeMatched),l=!!s&&!i.includes(wT.DELAYED);if(l&&a>0)return{orderId:t,status:wT.MATCHED,pending:!1,side:n.side,shares:a,usd:null,transactionHashes:[]};if(l)throw new pa(bt.NOT_FILLED,`Delayed order ${t} ended unmatched (${i})`);if(Date.now()>=o)return{orderId:t,status:wT.DELAYED,pending:!0,side:n.side,shares:0,usd:null,transactionHashes:[]}}}var Io=class extends Error{code;constructor(t,n,r){super(n),this.name="PolymarketWithdrawError",this.code=t,r!==void 0&&(this.cause=r)}},gj=/^0x[0-9a-fA-F]{40}$/,ihe=new Set(gn.STABLE_SYMBOLS);function vT(e){let t=o=>{let s=gn.CHAIN_ORDER.indexOf(o);return s===-1?gn.CHAIN_ORDER.length:s},n=o=>gn.STABLE_SYMBOLS.indexOf(o),r=new Set;return e.filter(o=>!(o.chainId in Ya)).filter(o=>gj.test(o.address)&&o.address.toLowerCase()!==Ls.toLowerCase()).filter(o=>ihe.has(o.symbol.toUpperCase())).filter(o=>{let s=`${o.chainId}:${o.address.toLowerCase()}`;return r.has(s)?!1:(r.add(s),!0)}).sort((o,s)=>t(o.chainId)-t(s.chainId)||o.chainName.localeCompare(s.chainName)||n(o.symbol.toUpperCase())-n(s.symbol.toUpperCase())).map(o=>({chainId:o.chainId,chainName:o.chainName,tokenAddress:o.address,symbol:o.symbol,decimals:o.decimals,minUsd:o.minUsd}))}function kT(e,t){return typeof t=="number"&&t>0?e<BigInt(Math.round(t*10**zo)):!1}async function ahe(e,t){if(typeof e.minUsd=="number")return e.minUsd;let n=e.tokenAddress.toLowerCase();return(await t.getBridgeAssets()).find(o=>o.chainId===e.chainId&&o.address.toLowerCase()===n)?.minUsd??0}function yj(e){return new Io(gn.ERROR.BELOW_MINIMUM,`Below the bridge minimum of $${e} for this destination`)}function xT(e){let t=String(e??"").trim(),n=/^(\d+)(?:\.(\d+))?$/.exec(t);if(!n)return null;let[,r,o=""]=n;if(o.length>zo)return null;let s=BigInt(r)*BigInt(10)**BigInt(zo)+BigInt(o.padEnd(zo,"0")||"0");return s>BigInt(0)?s:null}function lL(e){let t=BigInt(10)**BigInt(zo),n=e/t,r=(e%t).toString().padStart(zo,"0").replace(/0+$/,"");return r?`${n}.${r}`:n.toString()}async function bj(e,t=new Ye){let n=xT(e.amount);if(n===null)throw new Io(gn.ERROR.INVALID_AMOUNT,"Enter an amount");let r=e.destination.minUsd;if(kT(n,r))throw yj(r);let o=await t.getBridgeQuote({fromAmountBaseUnit:n.toString(),fromChainId:qm,fromTokenAddress:Ls,recipientAddress:e.recipient,toChainId:e.destination.chainId,toTokenAddress:e.destination.tokenAddress});return{estOutputBaseUnit:o.estToTokenBaseUnit,estOutputUsd:o.estOutputUsd,minReceivedUsd:o.minReceived,totalFeeUsd:o.totalImpactUsd,estTimeMs:o.estCheckoutTimeMs}}async function wj(e){let t=e.service??new Ye,n=xT(e.amount);if(n===null)throw new Io(gn.ERROR.INVALID_AMOUNT,"Enter an amount");if(!gj.test(e.recipient))throw new Io(gn.ERROR.FAILED,`Invalid recipient ${e.recipient}`);try{let r=await ahe(e.destination,t);if(kT(n,r))throw yj(r);let o=await Rh(e.wallet);if(o<n)throw new Io(gn.ERROR.INSUFFICIENT_BALANCE,`Cash ${lL(o)} is below ${e.amount}`);let s=await Yd(e),i=await t.createWithdrawalAddresses({wallet:e.wallet,toChainId:e.destination.chainId,toTokenAddress:e.destination.tokenAddress,recipient:e.recipient}),l=await(await s.transferErc20({tokenAddress:Ls,recipientAddress:i.evm,amount:n})).wait();return{bridgeAddress:i.evm,transactionHash:typeof l?.transactionHash=="string"?l.transactionHash:null,amountBaseUnit:n.toString()}}catch(r){throw cL(r)}}function cL(e){if(e instanceof Io)return e;let t=e?.message||String(e),n=Qd(e)?gn.ERROR.CANCELLED:/insufficient|exceeds balance|not enough balance/i.test(t)?gn.ERROR.INSUFFICIENT_BALANCE:gn.ERROR.FAILED;return new Io(n,t,e)}var ma=class extends Error{code;constructor(t,n,r){super(n),this.name="PolymarketRedeemError",this.code=t,r!==void 0&&(this.cause=r)}};async function vj(e){let t=e.service??new Ye;if(!/^0x[0-9a-fA-F]{64}$/.test(e.conditionId))throw new ma(Qa.ERROR.FAILED,`Invalid condition id ${e.conditionId}`);try{if((await t.getPositions(e.wallet,Qa.POSITIONS_READ_LIMIT,{fresh:!0})).filter(a=>a.conditionId.toLowerCase()===e.conditionId.toLowerCase()&&a.redeemable&&a.shares>0).length===0)throw new ma(Qa.ERROR.NOTHING_TO_CLAIM,"Nothing left to redeem in this market");let i=await(await(await Yd(e)).redeemPositions({conditionId:e.conditionId})).wait();return{transactionHash:typeof i?.transactionHash=="string"?i.transactionHash:null}}catch(n){if(n instanceof ma)throw n;let r=n?.message||String(n);throw new ma(Qd(n)?Qa.ERROR.CANCELLED:Qa.ERROR.FAILED,r,n)}}var lhe=6,che=.6,uhe=.1,dhe=200,phe=8,cc=new Map;function kj(e,t){let n=lt(e);if(n.length<phe||!t)return;let r=cc.get(n)??new Set;r.add(t),cc.delete(n),cc.set(n,r),cc.size>dhe&&cc.delete(cc.keys().next().value)}function mhe(e,t){let n=lt(e),r=lt(t),o=null;for(let[s,i]of cc)(n===s||r!==""&&` ${r} `.includes(` ${s} `))&&(!o||s.length>o.title.length)&&(o={title:s,slugs:i});return o&&o.slugs.size===1?[...o.slugs][0]:null}async function AT(e,t,n){let r=Ym(t)??Km(t)?.eventSlug??Ym(n)??Km(n)?.eventSlug??mhe(t,n)??null;if(r){let c=await e.getEventBySlug(r);return c?{kind:"event",event:c}:{kind:"not_found",query:t||r}}if(!t)return{kind:"unnamed"};let o=(await e.searchEvents(t,lhe)).filter(c=>c.markets.some(u=>u.open));if(o.length===0)return{kind:"not_found",query:t};let s=o.map(c=>({event:c,match:uL(t,c.title)})).sort((c,u)=>u.match.score-c.match.score),[i,a]=s;return o.length===1||i.match.exact||i.match.recall>=che&&(!a||i.match.score-a.match.score>=uhe)?{kind:"event",event:i.event}:{kind:"ambiguous",query:t,candidates:o}}function uL(e,t){let n=c=>lt(c).split(" ").filter(u=>u.length>1),r=n(e),o=n(t);if(r.length===0||o.length===0)return{recall:0,precision:0,score:0,exact:!1};let s=new Set(o),i=new Set(r),a=r.filter(c=>s.has(c)).length/r.length,l=o.filter(c=>i.has(c)).length/o.length;return{recall:a,precision:l,score:a*.7+l*.3,exact:r.join(" ")===o.join(" ")}}var TT="{market}",hhe=`Show me details of the prediction market ${TT}`,ha=[{name:"detail_button_label",type:"string",description:`Label for the "Details" button rendered on EVERY event card, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it. Just the word "Details" translated: English "Details", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the event \u2014 the button sits on that event's own card. One or two words.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this prediction market in detail" request IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a card's button is tapped. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the event title. English: "Show me details of the prediction market {market}". Vietnamese: "Xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng d\u1EF1 \u0111o\xE1n {market}". Always include {market}.`,required:!1}],xj=e=>typeof e=="string"?e.trim():"";function dL(e){return xj(e.detail_button_label).replace(TT,"").replace(/\s+/g," ").trim()}function pL(e,t,n){kj(e,t);let r=xj(n.detail_prompt_template);return(r.includes(TT)?r:hhe).split(TT).join(e).replace(/\s+/g," ").trim()}function fhe(e){return Math.round(e*1e3)/10}function fi(e,t){let n=10**t;return Math.trunc(Number((e*n).toFixed(6)))/n}function fa(e){return fi(e,2)}function ST(e){return fi(e,6)}function uc(e){return Math.round(e)}function mL(e){return e.map(t=>({label:t.label,chancePercent:fhe(t.chance),...t.shortLabel?{shortLabel:t.shortLabel}:{}}))}function Xd(e,t){let n=My(e);return n?{title:e.title,slug:e.slug,url:e.url,image:e.image,endDate:e.endDate,volumeUsd:uc(e.volume),volume24hUsd:uc(e.volume24h),kind:n.kind,outcomes:mL(n.outcomes),openMarketCount:n.openMarketCount,detailPrompt:pL(e.title,e.slug,t),detailLabel:dL(t),upDown:e.upDown}:null}var ga='A chance shown here is the PRICE traders currently pay for that outcome \u2014 the market-implied probability \u2014 never a forecast of yours: phrase it as "the market prices X at N%", never "X will win" or "X is likely". Do NOT give your own opinion or analysis of the underlying event (an election, a game, a policy decision), do NOT tell the user which side to buy or how much to stake, and never state a chance, price or volume the tool did not return. Prediction markets can lose the whole stake; this is information, not advice. Do NOT mention tool names.';var Tj=5,hL=20,ghe=3,Sj=Object.keys($m),Aj={trending:"ordered as polymarket.com's homepage Trending view: its featured events, live or upcoming games and the live 5-minute Bitcoin market first, then by 24-hour trading volume",new:"ordered by creation date, newest first",volume:"ordered by all-time trading volume, largest first",liquidity:"ordered by liquidity, deepest first",competitive:"ordered by how close the odds are (the most contested first)",ending_soon:"ordered by end date, the soonest-ending first"},Jd=class extends K{name="get-prediction-markets";kind="ui";category="prediction";description='BROWSE or SEARCH Polymarket prediction markets \u2014 real-world questions people trade on (elections, sports games, crypto prices, economics, geopolitics, tech, weather\u2026). Returns event cards with the current market-implied odds of each, volume and end date, plus a "Details" button per event. Use for: "trending predictions", "hot Polymarket markets", "sports prediction markets", "d\u1EF1 \u0111o\xE1n v\u1EC1 crypto", "new markets", "markets ending soon", "most contested markets", "is there a market on <topic>?", "odds on the next Fed decision", "Polymarket odds for the election". Pass `query` when the user names a TOPIC or event (a person, team, coin, event); pass `category` when they name a broad section; pass neither for the general feed. Do NOT use for: ONE event in full (all its options, rules, deadline) \u2192 get-prediction-market-detail; the user\'s own positions \u2192 get-prediction-portfolio; their trade history \u2192 get-prediction-activity.';parameters=[{name:"query",type:"string",description:`Search text when the user names a topic, event, person, team or coin ("bitcoin", "world cup", "Fed rates", "Lakers"). Write it in ENGLISH keywords \u2014 market titles are English \u2014 translating the user's words ("b\u1EA7u c\u1EED M\u1EF9" \u2192 "US election"). OMIT for a general or category feed.`,required:!1},{name:"category",type:"string",description:`Category to scope a feed to. One of: ${$i.map(t=>t.key).join(", ")}. Pass the user's word as-is if unsure \u2014 it is matched for you, and an unknown one is reported back. OMIT when the user named none, and when \`query\` is set.`,required:!1},{name:"sort",type:"string",description:`Feed order: ${Sj.map(t=>`"${t}" (${Aj[t]})`).join(", ")}. Default "trending". Ignored when \`query\` is set (search results are ordered by relevance).`,required:!1},{name:"limit",type:"number",description:`How many events, 1-${hL}. Default ${Tj}. Raise only when the user asks for more.`,required:!1},...ha];service;constructor(t){super(),this.service=new Ye(t)}async run(t){let n=typeof t.query=="string"?t.query.trim():"",r=bhe(t.limit),o=typeof t.category=="string"?t.category.trim():"",s=n?null:Fy(o);if(!n&&o&&!s)return{requestedCategory:o,categoriesAvailable:$i.map(p=>p.label),_instructions:`"${o}" is not a prediction-market category here. In the user's language, say so in one short sentence and name the categories in \`categoriesAvailable\`, offering to show one of them or to search a specific topic. Do NOT invent markets. Do NOT mention tool names.`};let i=yhe(t.sort),l=(n?await this.service.searchEvents(n,Math.min(hL*2,r*2+5)):await this.service.listEvents({sort:i,tagId:s?.tagId,limit:r*ghe})).map(p=>Xd(p,t)).filter(p=>p!==null).slice(0,r);if(l.length===0)return{query:n||null,category:s?.label??null,eventCount:0,_instructions:(n?`No open prediction market matches "${n}" right now. `:"No open prediction markets could be loaded for this view right now. ")+"Say so briefly in the user's language and offer to show the trending markets or another topic. Do NOT invent markets or odds. Do NOT mention tool names."};let c={sort:n?"relevance":i,category:s?.label??null,query:n||null,events:l},u={component:"PredictionMarketList",props:c},d=n?`prediction markets matching "${n}", most relevant first`:`${s?`${s.label} `:""}prediction markets ${Aj[i]}`;return{ui:u,query:n||null,category:s?.label??null,sortedBy:c.sort,eventCount:l.length,eventTitles:l.map(p=>p.title),_instructions:[`These are ${d}. They are ALREADY RENDERED as cards below your reply, each with its title, the`,'current odds, volume, end date and a "Details" button. Do NOT write the list out: no numbered or',"bullet list, no per-event lines, no odds, no links, no mention of the buttons.",`Write your reply in TWO parts separated by a line containing exactly ${jr} and nothing`,"else \u2014 include that marker EXACTLY ONCE, on its own line; do not translate, style or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: ONE short sentence noting that the odds are live market prices that move","constantly and that this is information, not betting advice \u2014 in the user's language.",ga].join(" ")}}};function yhe(e){let t=typeof e=="string"?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):"";return Sj.includes(t)?t:"trending"}function bhe(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?Tj:Math.min(Math.floor(t),hL)}function Zd(e){return!e.open||e.clobTokenIds.length!==e.outcomes.length||e.clobTokenIds.length<2?null:{question:e.question,conditionId:e.conditionId,negRisk:e.negRisk,protocol:e.protocol,fee:e.fee,outcomes:e.outcomes.map((t,n)=>({label:t.label,tokenId:e.clobTokenIds[n],...t.shortLabel?{shortLabel:t.shortLabel}:{}}))}}function Pj(e,t,n){let r=e.markets.filter(c=>c.open&&Zd(c));if(r.length===0)return null;if(n?.open&&Zd(n)&&!t)return n;if(r.length===1)return r[0];if(!t)return null;let o=lt(t),s=r.find(c=>lt(c.label)===o||lt(c.question)===o);if(s)return s;let i=r.map(c=>({m:c,match:uL(t,c.label||c.question)})).sort((c,u)=>u.match.score-c.match.score),[a,l]=i;return a.match.recall>=.6&&(!l||a.match.score>l.match.score)?a.m:null}function Ej(e,t){if(!t)return-1;let n=lt(t),o={co:"yes",khong:"no"}[n]??n,s=e.outcomes.map(a=>lt(a.label)),i=s.indexOf(o);return i>=0?i:s.findIndex(a=>a.includes(o)||o.includes(a))}function PT(e){let t=typeof e=="string"?e.trim().replace(",","."):typeof e=="number"?String(e):"";return/^\d+(\.\d+)?$/.test(t)&&Number(t)>0?t:null}function ET(e){return typeof e=="string"&&/^(all|max|everything|het|tat ca|toan bo)$/.test(lt(e))}var whe=15,Rj=600,vhe=5,ep=class extends K{name="get-prediction-market-detail";kind="ui";category="prediction";description='Show ONE prediction market (Polymarket event) in full: every open option with its current market-implied odds and 24 h change, volume, liquidity, end date and how it resolves. Use when the user singles out one event \u2014 "tell me more about the Fed October decision market", "odds of each candidate in the Brazil election", "how does this market resolve", a pasted polymarket.com link, or a tapped "Details" button (its message names the title of an event card already shown). Do NOT use for browsing many events or a topic in general \u2192 get-prediction-markets. Do NOT use when the user wants to buy, sell or bet (mua / b\xE1n / \u0111\u1EB7t c\u01B0\u1EE3c) \u2014 even with a hint \u2192 open-prediction-trade.';parameters=[{name:"market",type:"string",description:'Which event. When the message names the title of an event card already shown (a "Details" tap), pass that title VERBATIM, untranslated. When it carries a "(prediction: <slug>)" hint, pass that hint VERBATIM (with the parentheses). When it carries a polymarket.com link, pass the link. Otherwise pass the event as the user named it, in ENGLISH keywords ("Fed decision October", "Brazil presidential election").',required:!0},...ha];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=typeof t.market=="string"?t.market.trim():"",o=await AT(this.service,r,n?.query??"");switch(o.kind){case"event":return this.detail(o.event);case"ambiguous":return this.ambiguous(o.query,o.candidates,t);case"not_found":return this.notFound(o.query);default:return{_instructions:"No event was named. Ask the user, in their language, which prediction market they want to see. Do NOT mention tool names."}}}detail(t){let n=t.markets.filter(i=>i.open),r=fL(t),o=r.markets,s={component:"PredictionMarketDetail",props:r};return n.length===0?{ui:s,title:t.title,open:!1,resolvedOutcomes:xhe(t),_instructions:"This prediction market is CLOSED \u2014 no longer open for trading. In the user's language, say so in one or two sentences; if `resolvedOutcomes` lists winners, state them as how the market resolved. "+ga}:{ui:s,title:t.title,open:!0,endDate:t.endDate,volumeUsd:r.volumeUsd,mutuallyExclusive:t.negRisk,leadingOptions:o.filter(i=>i.outcomes.length>0).slice(0,vhe).map(i=>({option:i.label,outcomes:i.outcomes.map(a=>`${a.label} ${a.chancePercent}%`).join(" / ")})),openMarketCount:n.length,rules:_j(t.description,Rj),_instructions:["The event is ALREADY RENDERED as a card below your reply, listing every open option with its odds,","volume, end date and rules. Write at most THREE short sentences: what the question is, the leading","option(s) from `leadingOptions` as market prices, and when it ends. Do NOT list every option and do NOT","repeat the rules unless the user asked how it resolves (then summarize `rules` in one sentence).",ga].join(" ")}}ambiguous(t,n,r){let o=n.map(i=>Xd(i,r)).filter(i=>i!==null);return o.length===0?this.notFound(t):{ui:{component:"PredictionMarketList",props:{sort:"relevance",category:null,query:t,events:o}},query:t,candidateCount:o.length,candidateTitles:o.map(i=>i.title),_instructions:[`"${t}" matches several prediction markets, so none was opened. They are ALREADY RENDERED as cards`,'below your reply, each with a "Details" button. Write your reply in TWO parts separated by a line',`containing exactly ${jr} (exactly once, on its own line): PART ONE \u2014 one short sentence`,"saying several markets match and asking which one they mean; PART TWO \u2014 leave it empty or one short","sentence. Do NOT list the markets in text.",ga].join(" ")}}notFound(t){return{query:t,found:!1,_instructions:`No open prediction market matching "${t}" was found. Say so briefly in the user's language and offer to search a related topic or show the trending markets. Do NOT invent a market or odds. Do NOT mention tool names.`}}};function fL(e){let t=e.markets.filter(s=>s.open),n=Xa(e),o=(n?n.open?[n]:[]:t.slice(0,whe)).map(khe(e));return{title:e.title,slug:e.slug,url:e.url,image:e.image,description:_j(e.description,Rj),resolutionSource:e.resolutionSource,endDate:e.endDate,volumeUsd:uc(e.volume),volume24hUsd:uc(e.volume24h),liquidityUsd:uc(e.liquidity),negRisk:e.negRisk,markets:o,hiddenMarketCount:Math.max(0,t.length-o.length)}}function khe(e){let t=e.markets.length===1;return n=>({label:t?e.title:n.label,outcomes:n.priced?mL(n.outcomes):[],volumeUsd:uc(n.volume),oneDayChangePoints:n.priced&&n.oneDayPriceChange!==null?Math.round(n.oneDayPriceChange*1e3)/10:null,trade:Zd(n)})}function xhe(e){return e.markets.filter(t=>!t.open).map(t=>({market:t.label,winner:t.outcomes.find(n=>n.chance>=.999)?.label??""})).filter(t=>t.winner).slice(0,5)}function _j(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=n.lastIndexOf(" ");return`${(r>t*.6?n.slice(0,r):n).trimEnd()}\u2026`}function bs(e,t){return{component:"PredictionSetupCard",props:{signer:e.owner,wallet:e.address,walletKind:e.kind==="safe"?"safe":"deposit-wallet",deployed:e.deployed,approved:e.deployed?t?.isFullyApproved??!1:null}}}var ya="This wallet has no Polymarket account yet, so there is nothing to show. A card to set one up is ALREADY RENDERED below your reply. In ONE short sentence in the user's language, say there is no Polymarket account yet and that they can create it with the card below. Do NOT invent positions, balances or steps, and do NOT mention tool names.";var RT={name:"address",type:"string",description:"EVM address (0x\u2026) to look up \u2014 the user's wallet or a Polymarket account wallet. Set it ONLY when the user wrote an address; otherwise OMIT it and the connected wallet is used.",required:!1};function Ij(e){return`${qi}/profile/${e}`}function _T(e){return e?`${qi}/event/${e}`:null}async function IT(e,t,n){let r=gt(t.address,n);if(!zr(r))return{ok:!1,result:{address:r,_instructions:`"${r}" is not a valid EVM address. Ask the user, in their language, for a valid 0x address. Do NOT mention tool names.`}};let o=await e.resolveAccount(r),s=!!n?.walletAddress&&n.walletAddress.toLowerCase()===r.toLowerCase();return!o.deployed&&s&&o.kind!=="profile"?{ok:!1,result:{ui:bs(o,null),hasPolymarketAccount:!1,_instructions:ya}}:o.deployed?{ok:!0,account:o}:{ok:!1,result:{address:r,hasPolymarketAccount:!1,_instructions:"This wallet has no Polymarket account yet \u2014 nothing has been deposited or traded on Polymarket from it. Tell the user so in one short sentence, in their language, and offer to show the trending prediction markets instead. Do NOT invent positions or balances. Do NOT mention tool names."}}}var Cj=10,Nj=30,Ahe=200,tp=class extends K{name="get-prediction-portfolio";kind="ui";category="prediction";description=`The user's Polymarket holdings: cash available to trade, the value and profit/loss of every open position, and winnings ready to claim. Use for "my Polymarket positions", "my bets", "how much have I won/lost on Polymarket", "v\u1ECB th\u1EBF d\u1EF1 \u0111o\xE1n c\u1EE7a t\xF4i", "Polymarket balance". Works for the connected wallet or an address the user gives. Do NOT use for past trades \u2192 get-prediction-activity; for markets to browse \u2192 get-prediction-markets.`;parameters=[RT,{name:"limit",type:"number",description:`How many positions to list, 1-${Nj}. Default ${Cj}.`,required:!1},...ha];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=await IT(this.service,t,n);if(!r.ok)return r.result;let o=r.account.address,s=Phe(t.limit),[i,a,l]=await Promise.all([this.service.getPositions(o,Ahe),this.service.getPositionsValue(o),this.service.getCash(o).catch(()=>null)]),c=i.filter(The),u=c.filter(y=>y.redeemable),d=fa(u.reduce((y,w)=>y+w.currentValue,0)),p=c.slice(0,s).map(y=>She(y,t)),m={wallet:o,profileUrl:Ij(o),cashUsd:l===null?null:ST(l),positionsValueUsd:fa(a),claimableUsd:d,positions:p,totalPositions:c.length},g={component:"PredictionPortfolio",props:m},f=fa(c.reduce((y,w)=>y+w.cashPnl,0));return{ui:g,wallet:o,cashUsd:m.cashUsd,positionsValueUsd:m.positionsValueUsd,claimableUsd:d,openPositionCount:c.length-u.length,claimablePositionCount:u.length,unrealizedPnlUsd:f,positionsShown:p.length,positions:p.map(y=>({market:y.title,outcome:y.outcome,valueUsd:y.valueUsd,pnlUsd:y.pnlUsd})),_instructions:["The portfolio is ALREADY RENDERED as a card below your reply: cash, positions value, claimable winnings","and each position with its value and profit/loss. Write at most TWO short sentences in the user's","language: the headline numbers (cash, positions value, and claimable winnings if above 0) in USD exactly","as given, and \u2014 only if there are no positions \u2014 that the account currently holds none. End with a period,","never a colon. Do NOT list the positions in text (`positions` is there only so you never state anything","that is not in it). Never state a figure that is not in this result.",c.length===0?"":"Do NOT judge the positions or suggest selling, holding or buying anything.","Do NOT mention tool names."].filter(Boolean).join(" ")}}};function The(e){return e.shares<=0?!1:!e.redeemable||e.currentValue>0}function She(e,t){return{title:e.title,outcome:e.outcome,url:_T(e.eventSlug),icon:e.icon,shares:fi(e.shares,2),avgPrice:fi(e.avgPrice,4),curPrice:fi(e.curPrice,4),valueUsd:fa(e.currentValue),pnlUsd:fa(e.cashPnl),pnlPercent:Math.round(e.percentPnl*10)/10,claimable:e.redeemable&&e.currentValue>0,endDate:e.endDate,detailPrompt:e.eventSlug?pL(e.title,e.eventSlug,t):"",detailLabel:dL(t),tokenId:e.asset,conditionId:e.conditionId,outcomeIndex:e.outcomeIndex,oppositeOutcome:e.oppositeOutcome,oppositeTokenId:e.oppositeAsset}}function Phe(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?Cj:Math.min(Math.floor(t),Nj)}var Oj=10,Lj=30,Ehe="https://polygonscan.com/tx/",np=class extends K{name="get-prediction-activity";kind="ui";category="prediction";description=`The user's recent Polymarket history: each buy and sell (outcome, shares, price, amount), claimed winnings and rewards, newest first. Use for "my Polymarket trades", "what did I bet on", "l\u1ECBch s\u1EED giao d\u1ECBch Polymarket", "my last prediction trades". Works for the connected wallet or an address the user gives. Do NOT use for current holdings \u2192 get-prediction-portfolio.`;parameters=[RT,{name:"limit",type:"number",description:`How many entries, 1-${Lj}. Default ${Oj}.`,required:!1}];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=await IT(this.service,t,n);if(!r.ok)return r.result;let o=r.account.address,s=Rhe(t.limit),i=(await this.service.getActivity(o,s)).map(c=>({type:c.type,side:c.side,title:c.title,outcome:c.outcome,url:_T(c.eventSlug),shares:fi(c.shares,2),usd:fa(c.usd),price:fi(c.price,4),timestamp:c.timestamp,txUrl:/^0x[0-9a-fA-F]{64}$/.test(c.transactionHash)?`${Ehe}${c.transactionHash}`:null}));return i.length===0?{wallet:o,entryCount:0,_instructions:"This Polymarket account has no trading history yet. Say so in one short sentence in the user's language. Do NOT invent trades. Do NOT mention tool names."}:{ui:{component:"PredictionActivity",props:{wallet:o,items:i},completeList:!0},wallet:o,entryCount:i.length,entries:i.map(c=>({type:c.type,side:c.side,market:c.title,outcome:c.outcome,usd:c.usd,date:c.timestamp>0?new Date(c.timestamp*1e3).toISOString().slice(0,10):null})),_instructions:["The history is ALREADY RENDERED as a list below your reply \u2014 every entry with its type, outcome, shares,",'price, amount and time \u2014 so a request to "show" or "list" the trades is ALREADY fully answered by it;',"writing the entries out again would show each one twice.",`Write your reply in TWO parts separated by a line containing exactly ${jr} (exactly once, on`,"its own line). PART ONE: ONE short sentence ending with a period (never a colon) saying this is their","recent Polymarket activity and how many entries are shown. PART TWO: EMPTY \u2014 write nothing at all after the","marker. No bullet or numbered list anywhere, no per-entry lines: `entries` is given ONLY so you never","state anything that is not in it. Do NOT judge the trades. Do NOT mention tool names."].join(" ")}}};function Rhe(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?Oj:Math.min(Math.floor(t),Lj)}var rp=class extends K{name="open-prediction-setup";kind="ui";category="prediction";description=`Open the card that SETS UP the user's Polymarket account so they can trade prediction markets: one button that enables trading, creates their Polymarket wallet and grants the trading approvals \u2014 gasless, signed once from their own wallet. Use for "create a Polymarket account", "set up Polymarket", "enable trading on Polymarket", "t\u1EA1o t\xE0i kho\u1EA3n Polymarket", "k\xEDch ho\u1EA1t giao d\u1ECBch d\u1EF1 \u0111o\xE1n", or when the user wants to start betting / trading and has no account. Needs the connected wallet. Do NOT use to deposit funds \u2192 open-prediction-deposit.`;parameters=[];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=n?.walletAddress?.trim();if(!r||!zr(r))return{error:"wallet_not_connected",_instructions:"Setting up a Polymarket account needs the user's own connected wallet, which signs for it. Ask them, in their language, to connect a wallet first. Do NOT mention tool names."};let{account:o,approvals:s}=await ys(r,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, not a wallet that can sign for one, so it cannot be set up here. Say so briefly in the user's language. Do NOT mention tool names."};let i=bs(o,s),a=o.deployed&&s?.isFullyApproved===!0;return{ui:i,walletDeployed:o.deployed,approvalsComplete:s?.isFullyApproved??!1,_instructions:["The Polymarket account-setup card is ALREADY RENDERED below your reply; it runs the setup itself when the","user taps its button. Write ONE or TWO short sentences in the user's language:",a?"the wallet is already created and approved on-chain, so the card only needs to confirm trading access \u2014":"what the button does \u2014 enables trading, creates their Polymarket wallet and grants the approvals in one go,","with no gas fees, signed from their own wallet (an NFC card is tapped once).","Do NOT claim the account is set up, do NOT list technical steps or contract names, and do NOT mention tool","names."].join(" ")}}};var op=class extends K{name="open-prediction-deposit";kind="ui";category="prediction";description='Open the card that DEPOSITS funds into the user\'s Polymarket account (to trade prediction markets): send a stablecoin they hold (USDC, USDT, DAI\u2026 on Ethereum, Base, Polygon, Arbitrum, BSC\u2026) straight from their wallet, or get the EVM deposit address + QR code for another EVM wallet or exchange (EVM chains only). Use for "deposit to Polymarket", "fund my Polymarket", "n\u1EA1p ti\u1EC1n v\xE0o Polymarket", "top up my prediction account", "n\u1EA1p 50 USDC v\xE0o Polymarket". Needs the connected wallet; if the account is not set up yet the setup card is shown instead. Pass `amount` ONLY when the user named one.';parameters=[{name:"amount",type:"string",description:`Amount to pre-fill, in the stablecoin's own units as a plain decimal ("50", "12.5"). ONLY when the user named an amount; never invent or convert one.`,required:!1}];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=n?.walletAddress?.trim();if(!r||!zr(r))return{error:"wallet_not_connected",_instructions:"Depositing into Polymarket needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let{account:o,approvals:s}=await ys(r,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, so deposits are made to it directly from another wallet. Say so briefly in the user's language. Do NOT mention tool names."};if(!o.deployed)return{ui:bs(o,s),hasPolymarketAccount:!1,_instructions:ya};let[i,a]=await Promise.all([this.service.getBridgeAssets(),this.service.getDepositAddresses(o.address)]),l=await gT(r,i),c=typeof t.amount=="string"&&/^\d+(\.\d+)?$/.test(t.amount.trim())?t.amount.trim():null,d={component:"PredictionDepositCard",props:{wallet:o.address,owner:r,depositAddress:a.evm,options:l,assets:yT(i),networks:_he(i,a),prefillAmount:c}},p=l.length>0?Math.min(...l.map(m=>m.minUsd)):null;return{ui:d,walletHasDepositableStablecoins:l.length>0,depositableFromWallet:l.slice(0,5).map(m=>`${m.symbol} on ${m.chainName}`),minimumDepositUsd:p,_instructions:["The deposit card is ALREADY RENDERED below your reply: it opens the deposit screen, which sends a stablecoin","from the user's wallet, or shows the EVM deposit address and QR code for another EVM wallet or exchange","(EVM chains only \u2014 Ethereum, Base, Polygon, Arbitrum, BNB Chain\u2026). Write ONE or TWO short sentences in the","user's language:",l.length>0?"they can deposit straight from their wallet with the card (pick a token and amount),":"their wallet holds no stablecoin the card can send, so they can deposit from another EVM wallet or exchange using the address and QR code,","funds arrive as cash in their Polymarket account after the bridge processes them (usually a few minutes),",p!==null?`and deposits below about $${p} may not be credited.`:"and very small deposits may not be credited.","Do NOT claim a deposit was made, do NOT repeat addresses, and do NOT mention tool names."].join(" ")}}};function _he(e,t){let n={evm:{chains:new Set,minUsd:1/0},svm:{chains:new Set,minUsd:1/0},btc:{chains:new Set,minUsd:1/0},tron:{chains:new Set,minUsd:1/0}};for(let r of e){let o=Ya[r.chainId];if(o===null)continue;let s=n[o??"evm"];s.chains.add(r.chainName),s.minUsd=Math.min(s.minUsd,r.minUsd)}return Object.keys(n).filter(r=>t[r]&&n[r].chains.size>0).map(r=>({family:r,address:t[r],chains:[...n[r].chains].sort(),minUsd:Number.isFinite(n[r].minUsd)?n[r].minUsd:0}))}var Ihe=100,sp=class extends K{name="open-prediction-trade";kind="ui";category="prediction";description='Prepare a BUY or SELL of shares in a prediction market (Polymarket) for the user to review and confirm in the order drawer, which shows the live price. Use for "bet $10 on Yes", "buy Yes on the Fed market", "mua 20$ c\u1EEDa Lula", "sell my Real Madrid shares", "b\xE1n h\u1EBFt c\u1ED5 ph\u1EA7n Trump". Market orders only. Needs the connected wallet with a Polymarket account (otherwise the setup card is shown). Do NOT use to browse or see odds \u2192 get-prediction-markets / get-prediction-market-detail.';parameters=[{name:"market",type:"string",description:'Which event. A "(prediction: <slug>)" hint, a polymarket.com link or the title of an event card already shown in the message \u2192 pass it VERBATIM. Otherwise the event as the user named it, in ENGLISH keywords ("Fed decision October").',required:!0},{name:"option",type:"string",description:'For an event with several options (candidates, price levels, dates): the one the user picked, as named ("Lula", "85,000", "No change"). Omit when the user did not name one.',required:!1},{name:"outcome",type:"string",description:'The side the user picked: "Yes", "No", or a team / name. Omit when not said.',required:!1},{name:"side",type:"string",description:'"buy" (bet on / mua) or "sell" (sell shares / b\xE1n).',required:!0},{name:"amount",type:"string",description:'ONLY when the user named it. BUY: USD to spend as a plain decimal ("10"). SELL: number of shares, or "all" to sell everything. Never invent or convert one.',required:!1},...ha];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=n?.walletAddress?.trim();if(!r||!zr(r))return{error:"wallet_not_connected",_instructions:"Trading prediction markets needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let o=["sell","ban"].includes(lt(String(t.side??"")))?"SELL":"BUY",{account:s,approvals:i}=await ys(r,this.service);if(s.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, which cannot sign orders here. Say so briefly in the user's language. Do NOT mention tool names."};if(!s.deployed||i?.isFullyApproved!==!0)return{ui:bs(s,i),hasPolymarketAccount:s.deployed,_instructions:s.deployed?"The Polymarket account is not fully set up for trading yet. A card that finishes the setup is ALREADY RENDERED below your reply. In ONE short sentence in the user's language, say the account needs to finish setup before trading. Do NOT mention tool names.":ya};let a=typeof t.market=="string"?t.market.trim():"",l=await AT(this.service,a,n?.query??"");if(l.kind==="unnamed"||l.kind==="not_found")return{found:!1,_instructions:l.kind==="unnamed"?"No market was named. Ask the user, in their language, which prediction market they want to trade.":`No open prediction market matching "${l.query}" was found. Say so briefly in the user's language and offer to search a related topic. Do NOT invent a market. Do NOT mention tool names.`};if(l.kind==="ambiguous"){let k=l.candidates.map(D=>Xd(D,t)).filter(D=>!!D);return{ui:{component:"PredictionMarketList",props:{sort:"relevance",category:null,query:l.query,events:k}},candidateCount:k.length,_instructions:[`"${l.query}" matches several prediction markets, so no order was prepared. They are ALREADY`,"RENDERED as cards below. Write your reply in TWO parts separated by a line containing exactly",`${jr} (once, on its own line): PART ONE \u2014 one short sentence asking which market they`,"mean; PART TWO \u2014 empty. Do NOT list the markets in text."].join(" ")}}let c=l.event,u=typeof t.option=="string"?t.option.trim():"",d=Pj(c,u,Xa(c)??null);if(!d){let k=fL(c),T=k.markets.some(D=>D.trade);return{ui:{component:"PredictionMarketDetail",props:k},title:c.title,open:T,_instructions:T?"This event has several options and the order needs ONE. The event is ALREADY RENDERED below with a buy button on every option. In ONE short sentence in the user's language, ask them to pick the option on the card. Do NOT claim an order was placed. Do NOT mention tool names.":"This prediction market is closed \u2014 it can no longer be traded. Say so in one sentence in the user's language. Do NOT mention tool names."}}let p=Zd(d),m=t.amount,g=o==="SELL"&&ET(m),f=Ej(d,typeof t.outcome=="string"?t.outcome:""),y=null;if(o==="SELL"){let k=(await this.service.getPositions(s.address,Ihe)).filter(D=>D.conditionId===d.conditionId&&D.shares>0&&!D.redeemable),T=(f>=0?k.find(D=>D.outcomeIndex===f):void 0)??(k.length===1?k[0]:void 0);if(!T)return{holdsShares:!1,market:d.question,_instructions:k.length>1?"The user holds several outcomes of this market. Ask, in their language, which one to sell. Do NOT mention tool names.":"The user holds no shares of this market's chosen outcome, so there is nothing to sell. Say so in one sentence in the user's language. Do NOT mention tool names."};f=T.outcomeIndex,y=Math.floor(T.shares*100)/100}let w={eventTitle:c.title,eventSlug:c.slug,url:c.url,image:c.image,marketLabel:c.markets.length===1?c.title:d.label,market:p,outcomeIndex:Math.max(0,f),side:o,amount:g?null:PT(m),sellAll:g,signer:r,wallet:s.address,endDate:d.endDate??c.endDate},v={component:"PredictionTradeCard",props:w},A=p.outcomes[w.outcomeIndex].label;return{ui:v,side:o,market:d.question,outcome:A,outcomeWasNamed:f>=0,amount:w.amount,sellAll:g,heldShares:y,_instructions:["The order is ALREADY RENDERED below your reply as a card; it opens the order screen with the LIVE price,","where the user reviews and confirms (one signature / NFC tap). In ONE or TWO short sentences in the",`user's language, say what is prepared (${o==="BUY"?"buying":"selling"} "${A}" in`,`"${d.question}"${w.amount?`, ${o==="BUY"?`$${w.amount}`:`${w.amount} shares`}`:""}),`,f>=0?"":"that they can switch the outcome on the card,","and that they confirm it there. Do NOT claim the order is placed or filled, do NOT state a price (it is","live on the card), do NOT give betting advice, and do NOT mention tool names.",ga].filter(Boolean).join(" ")}}};var ip=class extends K{name="open-prediction-withdraw";kind="ui";category="prediction";description='Open the card that WITHDRAWS cash from the user\'s Polymarket account back to their own wallet, as USDC or USDT on the chain they choose (Polygon, Base, Arbitrum, Ethereum, Optimism, BNB Chain\u2026). Use for "withdraw from Polymarket", "cash out my Polymarket", "r\xFAt ti\u1EC1n kh\u1ECFi Polymarket", "r\xFAt 20 USDC v\u1EC1 v\xED", "withdraw everything to Base". Needs the connected wallet; if the account is not set up yet the setup card is shown instead. Pass `amount` ONLY when the user named one ("all" for everything), and `chain` / `token` ONLY when named. Selling a position first is open-prediction-trade, not this.';parameters=[{name:"amount",type:"string",description:'USD amount to pre-fill as a plain decimal ("20", "12.5"), or "all" for the whole cash balance. ONLY when the user named one; never invent or convert one.',required:!1},{name:"chain",type:"string",description:'Destination chain the user named, in English ("Base", "Polygon", "Arbitrum", "Ethereum", "BNB Chain"). OMIT when not named \u2014 the card lets them pick.',required:!1},{name:"token",type:"string",description:'Destination stablecoin the user named ("USDC" or "USDT"). OMIT when not named.',required:!1}];service;constructor(t){super(),this.service=new Ye(t)}async run(t,n){let r=n?.walletAddress?.trim();if(!r||!zr(r))return{error:"wallet_not_connected",_instructions:"Withdrawing from Polymarket needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let{account:o,approvals:s}=await ys(r,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, which cannot sign a withdrawal here; withdrawals are made from the wallet that owns it. Say so briefly in the user's language. Do NOT mention tool names."};if(!o.deployed)return{ui:bs(o,s),hasPolymarketAccount:!1,_instructions:ya};let[i,a]=await Promise.all([this.service.getBridgeAssets(),cd(o.address).catch(()=>null)]),l=vT(i);if(l.length===0)return{error:"withdraw_unavailable",_instructions:"Withdrawals are not available right now (the bridge lists no destination). Say so briefly in the user's language and suggest trying again later. Do NOT mention tool names."};let c=a===null?null:ST(a);return{ui:{component:"PredictionWithdrawCard",props:{signer:r,wallet:o.address,recipient:r,cashUsd:c,destinations:l,defaultDestination:Che(l,t.chain,t.token),prefillAmount:ET(t.amount)?"all":PT(t.amount)}},cashUsd:c,_instructions:["The withdraw card is ALREADY RENDERED below your reply: the user picks the chain and stablecoin, sees the","live quote (what arrives and the route cost) and confirms there; funds go to their own connected wallet.","Write ONE or TWO short sentences in the user's language:",c===null?"that they can withdraw their Polymarket cash with the card below.":c>0?`that they have $${c} cash available to withdraw with the card below.`:"that the account has no cash to withdraw right now \u2014 positions must be sold (or winnings claimed) first.","Do NOT claim a withdrawal was made or funds arrived, do NOT repeat addresses, and do NOT mention tool names."].join(" ")}}};function Che(e,t,n){let r=typeof t=="string"?lt(t).replace(/\bchain\b|\bmainnet\b/g,"").trim():"",o=typeof n=="string"?lt(n):"";if(!r&&!o)return null;let s=c=>{if(!r)return!0;let u=lt(c.chainName);return u===r||u.startsWith(r)||r.startsWith(u.split(" ")[0])},i=c=>!o||lt(c.symbol).startsWith(o),a=e.findIndex(c=>s(c)&&i(c));if(a>=0)return a;let l=e.findIndex(s);return l>=0?l:null}var CT="https://ipfs.pantograph.app/ipfs/",Dj=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function dc(e){let t=e?.trim();if(!t)return null;if(/^(https?:\/\/|data:image\/)/i.test(t))return t;let n=t.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return n?`${CT}${n[1]}`:Dj.test(t)?`${CT}${t}`:null}function Uj(e){let t=e?.trim();if(!t)return null;if(/^https?:\/\//i.test(t))return t;let n=t.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return n?`${CT}${n[1]}`:Dj.test(t)?`${CT}${t}`:null}function Bj(e){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(e)}function gL(e){if(!e||typeof e!="object")return;let t=e,n=t.image??t.image_url??t.imageUrl;return typeof n=="string"&&n.trim()?n.trim():void 0}function Nhe(e){if(typeof atob=="function"){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return new TextDecoder().decode(n)}if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Ohe(e){let t=e.match(/^data:application\/json([^,]*),(.*)$/is);if(!t)return null;let n=t[1]??"",r=t[2]??"";try{let o=/;base64/i.test(n)?Nhe(r):decodeURIComponent(r);return JSON.parse(o)}catch{try{return JSON.parse(r)}catch{return null}}}function Mj(e){let t=e?.trim();if(!t||!/^data:/i.test(t))return null;if(/^data:image\//i.test(t))return t;let n=Ohe(t);return n?dc(gL(n)):null}var Lhe=12,Dhe=6e3;async function Uhe(e,t,n){let r=new Array(e.length),o=0,s=new Array(Math.max(1,Math.min(t,e.length))).fill(0).map(async()=>{for(;o<e.length;){let i=o++;r[i]=await n(e[i],i)}});return await Promise.all(s),r}async function Bhe(e,t){try{let n=await se.get(e,{timeout:t});if(!n.ok)return null;let r=n.data;if(r&&typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return null}return null}catch{return null}}async function Mhe(e,t){let n=e?.trim();if(!n)return null;if(/^data:/i.test(n))return Mj(n);let r=Uj(n);if(!r)return null;if(Bj(r))return r;let o=await Bhe(r,t);if(o){let s=dc(gL(o));if(s)return s}return null}async function NT(e,t,n){if(t.length===0)return[];let r=n?.concurrency??Lhe,o=n?.timeoutMs??Dhe,s=await B1(e,t,n?.rpcUrl);return Uhe(s,r,i=>Mhe(i,o))}var Fj=100,Fhe=100,ap="{name}",qj="{chain}",lp=class extends K{name="get-wallet-nfts";description=`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`;category="nft";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}];service;constructor(t){super(),this.service=new De(t)}async run(t,n){let r=gt(t.address,n),o=at(t.chain,n),s=o?[o]:nr(),i=Whe(t.contract_address),a=Vj(t.collection_name);return i||a?this.listNfts({address:r,chains:s,singleChain:!!o,contract:i,collectionName:a}):this.listCollections({address:r,chains:s,singleChain:!!o,args:t})}async listCollections(t){let{address:n,chains:r,singleChain:o,args:s}=t,i=await Promise.all(r.map(async c=>{let u=await this.service.getWalletNftCollections({address:n,chain:c,limit:Fj});return{chain:c,rows:u.success?Hj(u.data?.result??[]):[],ok:u.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFT collections"};let a=i.flatMap(c=>c.rows.map(u=>({name:Hhe(u),contractAddress:u.token_address,chain:j(c.chain),nftCount:u.count??null})));if(a.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:n,collectionCount:0,collections:[]};let l=Vhe(a,s);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:n,collectionCount:a.length,collections:a,...l.length>0?{actionButtons:l}:{}}}async listNfts(t){let{address:n,chains:r,singleChain:o,contract:s,collectionName:i}=t,a=await Promise.all(r.map(async m=>{let g=await this.service.getWalletNFTs({address:n,chain:m,limit:Fj,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:g.success?Hj(g.data?.result??[]):[],ok:g.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=a.flatMap(m=>m.rows.filter(g=>qhe(g,{contract:s,collectionName:i})).map(g=>({chain:m.chain,row:g})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${i??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||i||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:m,row:g},f)=>{let y=$he(g);return{name:y.name,tokenId:y.tokenId,contractAddress:y.contractAddress,image:u[f]??y.image,chain:j(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:n,collectionName:c,nfts:d}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:n,collectionName:c,nftCount:l.length}}async resolveOnchainImages(t){let n=new Array(t.length).fill(null),r=new Map;t.forEach((o,s)=>{let i=r.get(o.chain)??[];i.push(s),r.set(o.chain,i)});try{await Promise.all([...r.entries()].map(async([o,s])=>{let i=s.map(l=>({contract:t[l].row.token_address,tokenId:t[l].row.token_id})),a=await NT(o,i);s.forEach((l,c)=>{n[l]=a[c]??null})}))}catch{}return n}};function Hj(e){return e.filter(t=>(t.contract_type||"").toUpperCase()==="ERC721")}function qhe(e,t){if(t.contract)return e.token_address.toLowerCase()===t.contract.toLowerCase();if(t.collectionName){let n=t.collectionName.toLowerCase();return(e.name??"").toLowerCase().includes(n)}return!1}function Hhe(e){let t=e.name?.trim();if(t)return t;let n=e.token_address??"";return n.length>10?`${n.slice(0,6)}\u2026${n.slice(-4)}`:n}function $he(e){return{name:e.normalized_metadata?.name||e.name||`#${e.token_id}`,tokenId:e.token_id,contractAddress:e.token_address,image:dc(e.normalized_metadata?.image||e.media?.original_media_url)}}function Vhe(e,t){let n=typeof t.pick_button_label=="string"?t.pick_button_label:"",r=typeof t.pick_prompt_template=="string"?t.pick_prompt_template:"",o=[];for(let s of e){if(o.length>=Fhe)break;if(!s.contractAddress)continue;let i=typeof s.chain=="string"?s.chain.trim():"",a=i?`show my ${ap} NFTs on ${qj}`:`show my ${ap} NFTs`,l=$j(r,{[ap]:s.name,[qj]:i},a);i&&!l.includes(i)&&(l=`${l} (${i})`),o.push({label:jhe(n,s.name,ap),prompt:`${l} (${s.contractAddress})`})}return o}function $j(e,t,n){let r=e&&e.includes(ap)?e:n;for(let[o,s]of Object.entries(t))r=r.split(o).join(s);return r.replace(/\s+/g," ").trim()}function jhe(e,t,n){return $j(e,{[ap]:t},n)}function Vj(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}function Whe(e){let t=Vj(e);return t&&/^0x[a-fA-F0-9]{40}$/.test(t)?t:void 0}var zhe="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",ws=class extends K{kind="data";category="nft";llm;constructor(t){super(),this.llm=new jt(t??{})}static promptParams(t){return[{name:"prompt",type:"string",description:t,required:!0}]}async run(t){let n=typeof t.prompt=="string"?t.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=await this.askGeminiWithSearch(n);return r?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:r}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(t){let n=Date.now();try{return(await this.llm.chat([{role:"system",content:zhe,timestamp:n},{role:"user",content:t,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var cp=class extends ws{name="get-nft-contract-info";description='Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.';parameters=ws.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`);presentInstructions="Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks."};var up=class extends ws{name="get-nft-metadata";description='Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.';parameters=ws.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`);presentInstructions="Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points."};var yL={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},bL="amazon.com";function Ghe(e){return e?e.trim().toLowerCase().split(/[-_]/)[0]:""}function wL(e){let t=Ghe(e);return yL[t]??bL}function OT(e){return`https://${wL(e)}/s?k=NFC%20Tag`}function LT(e){if(!e)return"";let t=e.trim().toUpperCase().split(/[-_]/),n=t.length>1?t[t.length-1]:t[0];return/^[A-Z]{2}$/.test(n)?n:""}var Khe=720*60*1e3,jj=new Map,Wj=3;function Yhe(e){return[`A user in country "${e}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Wj} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function Qhe(e){if(!e)return[];let t=e.indexOf("["),n=e.lastIndexOf("]");if(t===-1||n===-1||n<=t)return[];let r;try{r=JSON.parse(e.slice(t,n+1))}catch{return[]}if(!Array.isArray(r))return[];let o=[],s=new Set;for(let i of r){if(!i||typeof i!="object")continue;let a=i.label,l=i.url;if(typeof a!="string"||!a.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!s.has(c)&&(s.add(c),o.push({label:a.trim(),url:l.trim()}),o.length>=Wj))break}return o}async function vL(e,t){let n=LT(e);if(!n||!t)return null;let r=jj.get(n);if(r&&r.expires>Date.now())return r.links;let o=Date.now(),s=[{role:"user",content:Yhe(n),timestamp:o}];try{let i=await t.chat(s,void 0,{googleSearch:!0,maxRetries:1}),a=Qhe(i.text);if(a.length)return jj.set(n,{links:a,expires:Date.now()+Khe}),a}catch{}return null}async function dp(e){let t=await vL(e.country,e.llm);return t&&t.length?t:[{label:"Amazon",url:OT(e.language)}]}function Xhe(e){return e.length<=1?e.length===1?`[${e[0].label}](${e[0].url})`:"":e.map((t,n)=>`${n+1}. [${t.label}](${t.url})`).join(`
|
|
50
50
|
`)}var zj=["WHAT IT IS: NFC (Near-Field Communication) is a short-range wireless standard operating at 13.56 MHz, a",'subset of the older RFID family. An "NFC tag" is a tiny passive chip + antenna (often embedded in a','sticker, card, keyfob, wristband, or ring). "Passive" means it has no battery \u2014 it draws all its power from',"the electromagnetic field of the reader (a smartphone or dedicated reader) when held within ~2\u20134 cm. The","tag does nothing on its own; it simply waits to be tapped, then hands over the small piece of data it holds.","","HOW IT WORKS: When an NFC-enabled phone comes close, the reader emits a 13.56 MHz radio field. Through","inductive (magnetic) coupling that field powers the tag, which then transmits its stored data back to the","reader \u2014 no pairing, no app launch, no internet required for the handshake. The exchange is bidirectional","and near-instant (well under a second). Tags can be READ many times and, unless locked, also re-WRITTEN.","Data is stored in the standardised NDEF format (NFC Data Exchange Format) so any NFC phone can parse it the","same way. NFC works in three modes: reader/writer (phone reads or writes a tag), peer-to-peer (two devices","exchange data), and card-emulation (the phone itself acts like a tag, e.g. for tap-to-pay).","","WHAT'S INSIDE AN NFC TAG: just two parts \u2014 (1) a microchip (the integrated circuit) that holds a small","block of memory plus simple logic, and (2) a thin coiled antenna (usually etched copper or aluminium) that","both harvests power from the reader's field and carries the data signal. There is no battery and no moving","parts, which is why tags are paper-thin, cheap, and last for years (often rated for ~10 years of storage","and 100,000+ rewrites). Common chips differ mainly by memory size: NTAG213 (~144 bytes), NTAG215","(~504 bytes), NTAG216 (~888 bytes); larger/industrial families (e.g. ICODE, MIFARE) add more memory or","security features.","","WHAT IT CAN STORE: capacity is small \u2014 tens to a few hundred bytes of usable memory \u2014 so a tag holds a","compact payload, not files. Typical contents: a website URL, plain text, a contact card (vCard), Wi-Fi","credentials (SSID + password for one-tap join), an app-launch or deep link, a phone number / email,","geo-coordinates, a Bluetooth pairing handoff, or a small identifier/token. It is NOT mass storage \u2014 large","content lives elsewhere and the tag holds a pointer (a link or ID) to it.","","COMMON REAL-WORLD USES: contactless payments (Apple Pay / Google Pay via card emulation); transit and","access cards (metro, office door badges, hotel keys); product tags and anti-counterfeit / authenticity","checks; smart posters and marketing (tap to open a page, menu, or promo); pairing speakers/headphones with",'one tap; digital business cards and "tap to share contact"; smart-home automations (tap a tag by the door',"to run a routine); inventory, asset tracking, and ticketing; and tap-to-act crypto flows (e.g. open a","wallet address or a dapp link).","","HOW TO USE ONE: (1) Get an NFC tag (sticker/card/keyfob). (2) Make sure the phone has NFC enabled","(Settings \u2192 Connections/NFC; most modern Android phones and iPhone XS and later support it). (3) To WRITE,",'install an NFC writer app (e.g. "NFC Tools"), choose the record type (URL, text, Wi-Fi\u2026), enter the data,',"and tap the phone to the tag to program it. (4) To READ, just tap the phone to the tag \u2014 the action fires","automatically. (5) Optionally LOCK the tag to make it read-only so the data cannot be overwritten. Keep the","tag away from metal surfaces, which can detune the antenna and block reads.","","WHY THEY ARE POPULAR: they are extremely cheap (cents each), battery-free and maintenance-free, work with","the phone almost everyone already carries, and need just a tap \u2014 no app pairing, codes, or setup. The very","short range is a feature, not a bug: you must deliberately bring the devices together, which makes NFC","trusted for payments and access where accidental or remote reads would be a security risk.","","CRYPTO / WALLET CONTEXT: because a tag can hold a short identifier or address, NFC is handy for tap-to-act","flows \u2014 e.g. encoding a public wallet address or a deep link. Private keys/seed phrases should never be","written to an open, re-writable tag; treat tags as public, tamper-readable pointers, not secure key vaults.","","PRACTICAL TIPS: re-writable blank tags are inexpensive; pick a chip with enough memory for the payload",'(NTAG215+ for longer URLs or vCards). Use a metal-shielded ("on-metal") tag if you must stick it to a',"metal surface. Range is intentionally tiny (a few cm) for security \u2014 you must deliberately tap."].join(`
|
|
51
51
|
`),pp=class extends K{kind="data";name="nfc-info";category="nfc";description='Use when the user asks a conceptual / how-to question about NFC tags \u2014 what an NFC tag is, how NFC works, what data a tag can store, tag types/capacity, or how to read/write/use one ("what is an NFC tag", "how does NFC work", "what can I store on an NFC tag", "how do I use an NFC tag"). Returns an expert reference to answer from, plus a country-appropriate Amazon buy link to close with. Pass the current turn\'s BCP-47 `language` so the right storefront is picked. For a pure "where to buy" question with no explanation needed, prefer nfc-buy-link.';parameters=[{name:"language",type:"string",description:`The BCP-47 language tag of the user's current message (e.g. "en", "vi", "ja", "zh", "de"). Used only to pick the local Amazon storefront for the closing buy link. Optional (defaults to amazon.com).`,required:!1}];llm;constructor(t){super(),t&&(this.llm=new jt(t))}async run(t,n){let r=typeof t.language=="string"&&t.language.trim()?t.language.trim():void 0,o=await dp({country:n?.country,language:r,llm:this.llm}),s=Xhe(o),i=o.length>1;return{reference:zj,marketplaceLinks:o,_instructions:`Answer the user's NFC question as a knowledgeable, friendly expert, writing in the USER'S language (translate naturally \u2014 never leave it in English when they wrote another language). Draw on the reference below for the facts (do NOT invent anything beyond it), but write a polished, well-organized answer \u2014 not a terse one-liner. FORMAT: Use short Markdown section headings (bold or "##") and bullet points so it is easy to scan, similar to a great encyclopedia entry. For a broad question like "what is an NFC tag", give a thorough multi-section answer: open with a 1\u20132 sentence plain-language definition, then cover sections such as "How it works", "What's inside", "What it can store", "Common uses", "How to use one", and "Why they're popular" \u2014 include concrete specifics (the 13.56 MHz frequency, chip names + byte capacities, example payloads, numbered steps). Aim for genuinely useful depth, several short paragraphs/lists, not a wall of dense text. For a NARROW question (e.g. only "what can it store" or "how do I write one"), answer just that part in focused detail and skip the unrelated sections. Do not mention tools, this reference, or that anything is canned. AT THE END, add a short closing line telling them where they can buy NFC tags, then include EACH of these exact CLICKABLE Markdown links `+(i?"as a NUMBERED Markdown list (1., 2., 3.), ONE store per line, in this exact order and numbering":"inline")+` (keep every URL byte-for-byte; localize only the visible text; keep the form [text](url)):
|
|
52
52
|
${s}
|
|
@@ -270,12 +270,11 @@ Schema:
|
|
|
270
270
|
|
|
271
271
|
DECISION RULES (top-down, stop at first match):
|
|
272
272
|
0. Query is about the assistant itself \u2014 who/what it is, what it can do, its limits (any language, e.g. "what can you help me with?", "b\u1EA1n c\xF3 th\u1EC3 gi\xFAp g\xEC", "who are you", "\u4F60\u80FD\u505A\u4EC0\u4E48") -> "assignments": []. NEVER route these anywhere.
|
|
273
|
-
1. Query
|
|
274
|
-
|
|
275
|
-
2. Query
|
|
276
|
-
3.
|
|
277
|
-
4.
|
|
278
|
-
5. Pure general knowledge, small-talk, or clearly non-crypto -> "assignments": [].
|
|
273
|
+
1. Query matches one subagent's described scope -> one assignment.
|
|
274
|
+
A "who will win / will X happen" question asked while the conversation is ALREADY about prediction markets \u2014 "Previous turn handled by" names the prediction subagent, or the recent turns showed markets or odds \u2014 asks for the market's odds: it matches the prediction subagent's scope.
|
|
275
|
+
2. Query spans several scopes -> one assignment per scope (they run in PARALLEL).
|
|
276
|
+
3. No specific match, but query is about crypto / blockchain / token / NFT / wallet / DeFi / on-chain / smart contracts / a supported chain -> assign "ai-agent" with the user's original query.
|
|
277
|
+
4. Pure general knowledge, small-talk, or clearly non-crypto -> "assignments": [].
|
|
279
278
|
|
|
280
279
|
Route by MEANING, not keywords: a wallet / token / NFT / pool / swap / buy intent is the same whatever the language or script (English, Vietnamese, \u4E2D\u6587, \u65E5\u672C\u8A9E, \uD55C\uAD6D\uC5B4, \u2026). Symbols, addresses and numbers are language-neutral. wallet-agent / token-agent / nft-agent each have an internal AI Cortex fallback, so a domain-shaped query is safe to route to its matching agent even when no exact tool is obvious.
|
|
281
280
|
|
|
@@ -1417,9 +1416,7 @@ ${t}${c}
|
|
|
1417
1416
|
Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:Jge,timestamp:0},{role:"user",content:t,timestamp:Date.now()}],[m,g]=await Promise.allSettled([this.llm.chat(d,void 0,{maxOutputTokens:512}),this.llm.chat(p,void 0,{maxOutputTokens:32})]),f={};if(m.status==="fulfilled")try{f=this.parseJSON(m.value.text)}catch(A){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${A}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${m.reason}`);let y="";if(g.status==="fulfilled")try{let A=this.parseJSON(g.value.text);typeof A.language=="string"&&(y=A.language.trim().toLowerCase())}catch(A){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${A}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${g.reason}`);let w=typeof f.selfContained=="boolean"?f.selfContained:typeof f.isFollowUp=="boolean"?!f.isFollowUp:!0,v={selfContained:w,isFollowUp:o&&!w,rewrittenQuery:typeof f.rewrittenQuery=="string"&&f.rewrittenQuery.trim()?f.rewrittenQuery.trim():t,topicChanged:o&&typeof f.topicChanged=="boolean"?f.topicChanged:!1,reasoning:typeof f.reasoning=="string"?f.reasoning:"",language:y,mentionedChain:typeof f.mentionedChain=="string"?f.mentionedChain.trim():"",needsWebSearch:f.needsWebSearch===!0,aboutAssistant:f.aboutAssistant===!0};if(v.isFollowUp||(v.rewrittenQuery=t),this.debug){let A=Date.now()-u,k=v.rewrittenQuery!==t,T=f.isFollowUp===!0&&!v.isFollowUp;console.log(`
|
|
1418
1417
|
[QueryRewriter] (${A}ms)`),console.log(` original : "${t}"`),console.log(` rewritten : "${v.rewrittenQuery}"${k?"":" (unchanged)"}`),console.log(` followUp : ${v.isFollowUp}${T?" (clamped: message states its own action + object)":""} topicChanged: ${v.topicChanged} selfContained: ${v.selfContained}`),v.reasoning&&console.log(` reasoning : ${v.reasoning}`),console.log(` language : ${v.language}`),console.log(` webSearch : ${v.needsWebSearch}`),console.log(` aboutSelf : ${v.aboutAssistant}`)}return v}parseJSON(t){let n=t.trim();n.startsWith("```")&&(n=n.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let r=n.match(/\{[\s\S]*\}/);return r&&(n=r[0]),JSON.parse(n)}};var nt=require("@langchain/langgraph");function cS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var jW="\\s*/\\s*";function FL(e){return[e.symA.toLowerCase(),e.symB.toLowerCase()].sort().join("|")}function WW(e){return`(${e.symA}${jW}${e.symB}|${e.symB}${jW}${e.symA})`}function Zge(e){let t=cS(String(e));return`(?<![\\d.])${Number.isInteger(e)?`${t}(?:\\.0+)?`:`${t}0*`}`}function qL(e,t,n,r){return`${e.slice(0,t)}[${n}](${r})${e.slice(t+n.length)}`}function eye(e,t){let r=new RegExp(`(?<!\\[)\\b${WW(t)}\\b`,"i").exec(e);return r?qL(e,r.index,r[1]??r[0],t.url):null}function tye(e,t){if(t.feePercent==null)return null;let r=new RegExp(`(?<!\\[)\\b${WW(t)}\\b[^\\n\\]]{0,16}?${Zge(t.feePercent)}\\s*%`,"i").exec(e);return r?qL(e,r.index,r[1]??"",t.url):null}var nye=e=>{let t=[],n=r=>{if(!r||typeof r!="object")return;let o=r,s=typeof o.uniswapUrl=="string"?o.uniswapUrl:void 0,i=o.token0?.symbol,a=o.token1?.symbol;if(s&&typeof i=="string"&&i&&typeof a=="string"&&a){let l=o.feeTierPercent;t.push({url:s,symA:cS(i),symB:cS(a),feePercent:typeof l=="number"&&Number.isFinite(l)?l:void 0})}};n(e),n(e.pool);for(let r of["pools","candidates"]){let o=e[r];Array.isArray(o)&&o.forEach(n)}return t},rye=[nye],oye=e=>{let t=[],n=e.marketplaceLinks;if(Array.isArray(n))for(let o of n){if(!o||typeof o!="object")continue;let{label:s,url:i}=o;typeof s=="string"&&s&&typeof i=="string"&&i&&t.push({url:i,label:s})}let r=typeof e.amazonBuyUrl=="string"?e.amazonBuyUrl:void 0;return r&&t.push({url:r,label:"Amazon"}),t},sye=[oye];function iye(e,t){let r=new RegExp(`(?<!\\[)\\b${cS(t.label)}\\b`,"i").exec(e);return r?qL(e,r.index,r[0],t.url):null}function uS(e,t){if(!e)return e;let n=[],r=[];for(let a of t)for(let l of a.toolResults){if(!l.success||!l.data||typeof l.data!="object")continue;let c=l.data;for(let u of rye)n.push(...u(c));for(let u of sye)r.push(...u(c))}if(n.length===0&&r.length===0)return e;let o=new Map;for(let a of n)o.set(FL(a),(o.get(FL(a))??0)+1);let s=e,i=new Set;for(let a of n){if(i.has(a.url))continue;if(s.includes(a.url)){i.add(a.url);continue}let c=(o.get(FL(a))??0)>1?tye(s,a):eye(s,a);c&&(s=c,i.add(a.url))}for(let a of r){if(i.has(a.url))continue;if(s.includes(a.url)){i.add(a.url);continue}let l=iye(s,a);l&&(s=l,i.add(a.url))}return s}var Br=e=>({reducer:(t,n)=>n,default:e}),aye=nt.Annotation.Root({userMessage:(0,nt.Annotation)(),overrideLang:(0,nt.Annotation)(Br(()=>"")),conversationMessages:(0,nt.Annotation)(Br(()=>[])),lastSubagents:(0,nt.Annotation)(Br(()=>[])),messageId:(0,nt.Annotation)(Br(()=>"")),rewrite:(0,nt.Annotation)(Br(()=>null)),effectiveQuery:(0,nt.Annotation)(Br(()=>"")),turnLanguage:(0,nt.Annotation)(Br(()=>"")),kbContext:(0,nt.Annotation)(Br(()=>"")),speculativeDecision:(0,nt.Annotation)(Br(()=>null)),decision:(0,nt.Annotation)(Br(()=>null)),assignment:(0,nt.Annotation)(Br(()=>null)),assignmentIndex:(0,nt.Annotation)(Br(()=>0)),subResults:(0,nt.Annotation)({reducer:(e,t)=>e.concat(t),default:()=>[]}),response:(0,nt.Annotation)(Br(()=>null))});function zW(e){let t=async d=>{e.addUserMessage(d.userMessage),e.needsSummary()&&await e.compactHistory();let p=e.conversationForTurn(),m=e.lastAssistantSubagents(p);return e.debug&&m.length>0&&console.log(`[AgentCore] previous turn handled by: ${m.join(", ")}`),{conversationMessages:p,lastSubagents:m,messageId:e.generateMessageId()}},n=async d=>{let p=e.route(d.userMessage,d.conversationMessages,e.subagentCards(),d.lastSubagents).catch(()=>null),m=await e.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),g=d.overrideLang||m.language||"";return{rewrite:m,effectiveQuery:m.rewrittenQuery,turnLanguage:g,speculativeDecision:await p}},r=async d=>{let p=d.rewrite,m=p.isFollowUp?d.effectiveQuery:d.userMessage,g=await e.searchKB(m),f=e.formatKBContext(g),y=await e.tryAnswerFromKB(d.userMessage,g,f,d.messageId);return y?{kbContext:f,response:{...y,messageId:d.messageId,rewrite:p}}:{kbContext:f}},o=async d=>d.speculativeDecision&&d.effectiveQuery===d.userMessage?(e.debug&&console.log("[AgentCore] route: reusing the speculative decision (query unchanged by rewrite)"),{decision:d.speculativeDecision}):{decision:await e.route(d.effectiveQuery,d.conversationMessages,e.subagentCards(),d.lastSubagents)},s=async d=>{let p=await e.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.messageId,d.rewrite?.needsWebSearch??!1),m=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...p,messageId:d.messageId,routerDecision:m,rewrite:d.rewrite}}},i=async d=>{let p=await e.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage,(d.rewrite?.mentionedChain??"").trim());return{subResults:[{i:d.assignmentIndex,result:p}]}},a=async d=>{let p=d.subResults.slice().sort((T,D)=>T.i-D.i).map(T=>T.result);e.persistToolMessages(p);let m=e.mergeTrace(p),f=(p.length===1?p[0].finalAnswer.trim():"")||await e.synthesise(d.userMessage,m,e.synthesiserHistory(),d.turnLanguage||void 0),y=uS(f,p),w=p.map(T=>T.subagentName),v=e.collectUiActions(p,d.turnLanguage||null),A=e.collectActionButtons(p,d.turnLanguage||null);return{response:{...await e.finaliseAnswer({userMessage:d.userMessage,answer:y,subagents:w,uiActions:v,actionButtons:A,messageId:d.messageId}),messageId:d.messageId,trace:m,routerDecision:d.decision,subagentResults:p,rewrite:d.rewrite,...v.length>0?{uiActions:v}:{},...A.length>0?{actionButtons:A}:{}}}},l=async d=>{let p=(d.rewrite?.mentionedChain||String(e.connectedChain()??"")).trim(),m=new Map(e.subagentCards().map(v=>[v.name,v.domain])),g=(d.decision?.assignments??[]).filter(v=>v.subagent!=="ai-agent"),y=g.length>0&&g.every(v=>m.get(v.subagent)==="pool")?Xn():void 0;return{response:{...await e.answerUnsupportedChain(p,d.turnLanguage,d.messageId,y),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},c=d=>d.response?nt.END:d.rewrite?.aboutAssistant?"direct":"route",u=d=>{let p=d.decision?.assignments??[];if(p.length===0)return"direct";let m=p.some(f=>f.subagent!=="ai-agent"),g=(d.rewrite?.mentionedChain||e.connectedChain()||"").trim();return m&&g!==""&&!tr(g)?"unsupportedChain":p.map((f,y)=>new nt.Send("subagent",{...d,assignment:f,assignmentIndex:y}))};return new nt.StateGraph(aye).addNode("setup",t).addNode("contextualize",n).addNode("kb",r).addNode("route",o).addNode("direct",s).addNode("subagent",i).addNode("synthesize",a).addNode("unsupportedChain",l).addEdge(nt.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",nt.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",nt.END).addEdge("direct",nt.END).addEdge("subagent","synthesize").addEdge("synthesize",nt.END).compile()}var GW=require("js-sha3");function rm(){let e=Date.now().toString(16),t=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(e+t).slice(-8)}var lye="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",cye=`
|
|
1419
1418
|
|
|
1420
|
-
IDENTITY:
|
|
1421
|
-
|
|
1422
|
-
RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,dS=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;ownGeminiKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;x402Signer=null;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;currentAbortController=null;historyReady;constructor(t){if(this.secretKey=t.secretKey??"",this.ownGeminiKey=!!t.llm?.apiKey?.trim(),Ma(t.rpcUrls),t.swapProviders)for(let[p,m]of Object.entries(t.swapProviders))m&&qT(p,m);CP(t.polymarketBuilderCode),Wg({debug:t.debug??!1}),ny(t.excludeChains),this.llm=new jt(t.llm),this.registry=new Zc,this.history=new Jp(t.maxHistoryMessages??50),this.summarizer=new Zp(this.llm),this.synthesizer=new nm(this.llm),this.systemPrompt=(t.systemPrompt??lye)+cye+uye,this.debug=t.debug??!1,this.storage=t.storage??null,this.storageKey=t.storageKey??"keyring-agent-history",this.persistHistoryEnabled=t.persistHistory??!1,this.kbEntries=new em(t.knowledgeBase),this.kbEntries.setLLM(this.llm);let n=t.vectorKB;n?.enabled?(n.provider?this.kb=n.provider:(this.vectorKB=new Ra({url:n.url,token:n.token,namespace:n.namespace,minScore:n.minScore,defaultTopK:n.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=n.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${n.provider?"custom provider":"Upstash"}`+(n.namespace?`, ns=${n.namespace}`:"")+")")):this.kb=this.kbEntries;let r=t.kbAnswerThreshold;if(typeof r=="number"?this.kbAnswerThreshold=r:n?.enabled&&!n.provider?this.kbAnswerThreshold=n.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),t.moralis!==!1){let p=typeof t.moralis=="object"?t.moralis:void 0;this.registry.register(new yu(p)),this.registry.register(new cu({...p,llm:t.llm})),this.registry.register(new bu(p)),this.registry.register(new wu(p)),this.registry.register(new vu(p)),this.registry.register(new uu(p)),this.registry.register(new ku(p)),this.registry.register(new xu(p)),this.registry.register(new Pu(p)),this.registry.register(new Tu(p)),this.registry.register(new Su(p)),this.registry.register(new Au(p)),this.registry.register(new mu(p)),this.registry.register(new hu(p)),this.registry.register(new du(p)),this.registry.register(new pu(p)),this.registry.register(new lp(p))}if(t.lending!==!1){let p=typeof t.lending=="object"?t.lending:void 0;this.registry.register(new _u(p)),this.registry.register(new Iu(p)),this.registry.register(new Cu(p)),this.registry.register(new Nu({...p,moralis:typeof t.moralis=="object"?t.moralis:void 0}))}if(t.subagents?.prediction===!0&&t.prediction!==!1){let p=typeof t.prediction=="object"?t.prediction:void 0;this.registry.register(new Jd(p)),this.registry.register(new ep(p)),this.registry.register(new tp(p)),this.registry.register(new np(p)),this.registry.register(new rp(p)),this.registry.register(new op(p)),this.registry.register(new sp(p)),this.registry.register(new ip(p))}this.registry.register(new cp(t.llm)),this.registry.register(new up(t.llm)),t.subagents?.nfc===!0&&(this.registry.register(new pp(t.llm)),this.registry.register(new mp(t.llm))),this.registry.register(new hp(t.llm));let o=t.subagents?.["pool-subgraph"]===!0,s=t.subagents?.["pool-defillama"]===!0,i=t.subagents?.["pool-uniswap"],a=o||s?i===!0:i!==!1;if(a&&t.uniswap!==!1){let p=typeof t.uniswap=="object"?t.uniswap:void 0,m=typeof t.subgraph=="object"?t.subgraph:void 0;this.registry.register(new Pp(p,m)),this.registry.register(new Ep(p)),this.registry.register(new Rp(p)),this.registry.register(new _p(p)),this.registry.register(new Ip(p)),this.registry.register(new fc({baseUrl:p?.baseUrl,minProvideUsd:p?.minProvideUsd})),this.registry.register(new gc),this.registry.register(new yc),this.registry.register(new bc)}if((a||o||s)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new fp(t.llm)),o&&t.subgraph!==!1){let p=typeof t.subgraph=="object"?t.subgraph:void 0;this.registry.register(new Cp(p)),this.registry.register(new Np(p)),this.registry.register(new Op(p)),this.registry.register(new Lp(p)),this.registry.register(new Dp(p)),this.registry.register(new Up(p)),this.registry.register(new Bp(p))}if(s&&t.defiLlama!==!1){let p=typeof t.defiLlama=="object"?t.defiLlama:void 0,m={baseUrl:p?.baseUrl,cacheTtlMs:p?.cacheTtlMs};this.registry.register(new qp(m)),this.registry.register(new $p(m)),this.registry.register(new Hp(m)),this.registry.register(new Vp(m)),this.registry.register(new jp(m)),this.registry.register(new fc({minProvideUsd:p?.minProvideUsd,resolver:new Wp(m)})),this.registry.register(new gc),this.registry.register(new yc({scope:pr(),supportsLabel:mr(),chainParamDescription:hr})),this.registry.register(new bc)}if(t.subagents?.["wallet-action"]!==!1){let p=t.moralis===!1?void 0:typeof t.moralis=="object"?t.moralis:{},m=t.noFormTools,g=f=>XT(this.registry,f,m);g(new zp(p)),g(new Gp(p)),g(new Xp(p)),g(new Kp(p)),g(new Yp(p,{debug:this.debug})),g(new Qp(p,{debug:this.debug}))}this.router=new tm(this.llm,{debug:this.debug}),this.rewriter=new lS(this.llm,{debug:this.debug});let c=typeof t.subgraph=="object"?t.subgraph:void 0,u={...t.subagents,...t.lending===!1&&t.subagents?.lending!==!0?{lending:!1}:{},...t.prediction===!1?{prediction:!1}:{}},d=aS(this.llm,this.registry,{maxToolCalls:t.maxIterations??5,debug:this.debug,linkAddLiquidity:c?.linkAddLiquidity},u);this.subagents=new Map(d.map(p=>[p.name,p])),this.chatGraph=zW(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(t){this.registry.register(t)}registerTools(t){for(let n of t)this.registry.register(n)}unregisterTool(t){return this.registry.unregister(t)}listTools(){return this.registry.listNames()}async invokeTool(t,n,r){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(t))return{answer:`Unknown tool: "${t}".`,messageId:rm()};this.debug&&console.log(`[AgentCore] invokeTool ${t} ${JSON.stringify(n)}`);let s=r?.userMessage??`[invoke ${t}]`;this.history.add({role:"user",content:s,timestamp:Date.now()});let i=await this.registry.execute(t,n,this.userContext),a=i.data,l=i.success?a?.summary??"Done.":`Action failed: ${i.error??"unknown error"}`,c=rm(),u=i.success&&i.ui?[this.stampLanguage(i.ui,null)]:[],d={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:l,messageId:c,...u.length>0?{uiActions:u}:{}}}async runTool(t,n,r){this.assertLicense(),await this.loadHistory();let o=rm();if(!this.registry.has(t))return{answer:`Unknown tool: "${t}".`,messageId:o};this.debug&&console.log(`[AgentCore] runTool ${t} ${JSON.stringify(n)}`);let s=r?.userMessage?.trim()||`[run ${t}]`,i=typeof r?.language=="string"&&r.language.trim()?r.language.trim():null,a=Array.from(this.subagents.values()).filter(m=>m.ownsTool(t)).map(m=>m.name),l=a.length>0?a:["direct"],c=new AbortController;this.currentAbortController=c;let{signal:u,cleanup:d}=sP(c,r?.signal);this.llm.setRequestSignal?.(u),om(u);let p=this.history.serialise();try{this.history.add({role:"user",content:s,timestamp:Date.now()});let m=await this.registry.execute(t,n,{...this.userContext,query:s});km(u);let g=m.success?JSON.stringify(m.data):`Error: ${m.error}`,f=Date.now(),y=[{subagentName:l[0],steps:[{phase:"act",content:`Calling tool: ${t}`,toolCall:{toolName:t,args:n},timestamp:f},{phase:"observe",content:g,toolResult:m,timestamp:f}],finalAnswer:"",toolResults:[m],toolMessages:[]}],w=this.mergeTrace(y),v=await this.synthesizer.synthesise(s,w,this.synthesiserHistory(),i??void 0),A=uS(v,y),k=this.collectUiActions(y,i),T=this.collectActionButtons(y,i);return{...await this.finaliseAnswer({userMessage:s,answer:A,subagents:l,uiActions:k,actionButtons:T,messageId:o}),messageId:o,trace:w,subagentResults:y,...k.length>0?{uiActions:k}:{},...T.length>0?{actionButtons:T}:{}}}catch(m){throw Va(m)||u.aborted?(this.history.restore(p),new Ni):(this.history.restore(p),m)}finally{d(),this.llm.setRequestSignal?.(void 0),om(void 0),this.currentAbortController===c&&(this.currentAbortController=null)}}setX402Signer(t){this.x402Signer=t,GL(t?oP({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(t,n,r){this.assertLicense(),await this.loadHistory();let o=rm(),s=t,i=r?.userQuery||s?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let a;try{a=await nP(se,s,n)}catch(c){let d=`The payment couldn't be completed: ${c instanceof Error?c.message:String(c)}. Please try again.`;return this.history.add({role:"assistant",content:d,timestamp:Date.now(),messageId:o}),await this.persistHistory(),{answer:d,messageId:o}}return{...await this.synthesizeFromPaidData(i,a,o),messageId:o}}async synthesizeFromPaidData(t,n,r){let o=typeof n=="string"?n:JSON.stringify(n),s=this.systemPrompt+this.capabilitiesSummary(),i=`The user's question was: "${t}".
|
|
1419
|
+
IDENTITY: If the user asks who or what you are, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline and steer back to how you can help.`,dS=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;ownGeminiKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;x402Signer=null;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;currentAbortController=null;historyReady;constructor(t){if(this.secretKey=t.secretKey??"",this.ownGeminiKey=!!t.llm?.apiKey?.trim(),Ma(t.rpcUrls),t.swapProviders)for(let[p,m]of Object.entries(t.swapProviders))m&&qT(p,m);CP(t.polymarketBuilderCode),Wg({debug:t.debug??!1}),ny(t.excludeChains),this.llm=new jt(t.llm),this.registry=new Zc,this.history=new Jp(t.maxHistoryMessages??50),this.summarizer=new Zp(this.llm),this.synthesizer=new nm(this.llm),this.systemPrompt=(t.systemPrompt??lye)+cye,this.debug=t.debug??!1,this.storage=t.storage??null,this.storageKey=t.storageKey??"keyring-agent-history",this.persistHistoryEnabled=t.persistHistory??!1,this.kbEntries=new em(t.knowledgeBase),this.kbEntries.setLLM(this.llm);let n=t.vectorKB;n?.enabled?(n.provider?this.kb=n.provider:(this.vectorKB=new Ra({url:n.url,token:n.token,namespace:n.namespace,minScore:n.minScore,defaultTopK:n.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=n.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${n.provider?"custom provider":"Upstash"}`+(n.namespace?`, ns=${n.namespace}`:"")+")")):this.kb=this.kbEntries;let r=t.kbAnswerThreshold;if(typeof r=="number"?this.kbAnswerThreshold=r:n?.enabled&&!n.provider?this.kbAnswerThreshold=n.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),t.moralis!==!1){let p=typeof t.moralis=="object"?t.moralis:void 0;this.registry.register(new yu(p)),this.registry.register(new cu({...p,llm:t.llm})),this.registry.register(new bu(p)),this.registry.register(new wu(p)),this.registry.register(new vu(p)),this.registry.register(new uu(p)),this.registry.register(new ku(p)),this.registry.register(new xu(p)),this.registry.register(new Pu(p)),this.registry.register(new Tu(p)),this.registry.register(new Su(p)),this.registry.register(new Au(p)),this.registry.register(new mu(p)),this.registry.register(new hu(p)),this.registry.register(new du(p)),this.registry.register(new pu(p)),this.registry.register(new lp(p))}if(t.lending!==!1){let p=typeof t.lending=="object"?t.lending:void 0;this.registry.register(new _u(p)),this.registry.register(new Iu(p)),this.registry.register(new Cu(p)),this.registry.register(new Nu({...p,moralis:typeof t.moralis=="object"?t.moralis:void 0}))}if(t.subagents?.prediction===!0&&t.prediction!==!1){let p=typeof t.prediction=="object"?t.prediction:void 0;this.registry.register(new Jd(p)),this.registry.register(new ep(p)),this.registry.register(new tp(p)),this.registry.register(new np(p)),this.registry.register(new rp(p)),this.registry.register(new op(p)),this.registry.register(new sp(p)),this.registry.register(new ip(p))}this.registry.register(new cp(t.llm)),this.registry.register(new up(t.llm)),t.subagents?.nfc===!0&&(this.registry.register(new pp(t.llm)),this.registry.register(new mp(t.llm))),this.registry.register(new hp(t.llm));let o=t.subagents?.["pool-subgraph"]===!0,s=t.subagents?.["pool-defillama"]===!0,i=t.subagents?.["pool-uniswap"],a=o||s?i===!0:i!==!1;if(a&&t.uniswap!==!1){let p=typeof t.uniswap=="object"?t.uniswap:void 0,m=typeof t.subgraph=="object"?t.subgraph:void 0;this.registry.register(new Pp(p,m)),this.registry.register(new Ep(p)),this.registry.register(new Rp(p)),this.registry.register(new _p(p)),this.registry.register(new Ip(p)),this.registry.register(new fc({baseUrl:p?.baseUrl,minProvideUsd:p?.minProvideUsd})),this.registry.register(new gc),this.registry.register(new yc),this.registry.register(new bc)}if((a||o||s)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new fp(t.llm)),o&&t.subgraph!==!1){let p=typeof t.subgraph=="object"?t.subgraph:void 0;this.registry.register(new Cp(p)),this.registry.register(new Np(p)),this.registry.register(new Op(p)),this.registry.register(new Lp(p)),this.registry.register(new Dp(p)),this.registry.register(new Up(p)),this.registry.register(new Bp(p))}if(s&&t.defiLlama!==!1){let p=typeof t.defiLlama=="object"?t.defiLlama:void 0,m={baseUrl:p?.baseUrl,cacheTtlMs:p?.cacheTtlMs};this.registry.register(new qp(m)),this.registry.register(new $p(m)),this.registry.register(new Hp(m)),this.registry.register(new Vp(m)),this.registry.register(new jp(m)),this.registry.register(new fc({minProvideUsd:p?.minProvideUsd,resolver:new Wp(m)})),this.registry.register(new gc),this.registry.register(new yc({scope:pr(),supportsLabel:mr(),chainParamDescription:hr})),this.registry.register(new bc)}if(t.subagents?.["wallet-action"]!==!1){let p=t.moralis===!1?void 0:typeof t.moralis=="object"?t.moralis:{},m=t.noFormTools,g=f=>XT(this.registry,f,m);g(new zp(p)),g(new Gp(p)),g(new Xp(p)),g(new Kp(p)),g(new Yp(p,{debug:this.debug})),g(new Qp(p,{debug:this.debug}))}this.router=new tm(this.llm,{debug:this.debug}),this.rewriter=new lS(this.llm,{debug:this.debug});let c=typeof t.subgraph=="object"?t.subgraph:void 0,u={...t.subagents,...t.lending===!1&&t.subagents?.lending!==!0?{lending:!1}:{},...t.prediction===!1?{prediction:!1}:{}},d=aS(this.llm,this.registry,{maxToolCalls:t.maxIterations??5,debug:this.debug,linkAddLiquidity:c?.linkAddLiquidity},u);this.subagents=new Map(d.map(p=>[p.name,p])),this.chatGraph=zW(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(t){this.registry.register(t)}registerTools(t){for(let n of t)this.registry.register(n)}unregisterTool(t){return this.registry.unregister(t)}listTools(){return this.registry.listNames()}async invokeTool(t,n,r){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(t))return{answer:`Unknown tool: "${t}".`,messageId:rm()};this.debug&&console.log(`[AgentCore] invokeTool ${t} ${JSON.stringify(n)}`);let s=r?.userMessage??`[invoke ${t}]`;this.history.add({role:"user",content:s,timestamp:Date.now()});let i=await this.registry.execute(t,n,this.userContext),a=i.data,l=i.success?a?.summary??"Done.":`Action failed: ${i.error??"unknown error"}`,c=rm(),u=i.success&&i.ui?[this.stampLanguage(i.ui,null)]:[],d={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:l,messageId:c,...u.length>0?{uiActions:u}:{}}}async runTool(t,n,r){this.assertLicense(),await this.loadHistory();let o=rm();if(!this.registry.has(t))return{answer:`Unknown tool: "${t}".`,messageId:o};this.debug&&console.log(`[AgentCore] runTool ${t} ${JSON.stringify(n)}`);let s=r?.userMessage?.trim()||`[run ${t}]`,i=typeof r?.language=="string"&&r.language.trim()?r.language.trim():null,a=Array.from(this.subagents.values()).filter(m=>m.ownsTool(t)).map(m=>m.name),l=a.length>0?a:["direct"],c=new AbortController;this.currentAbortController=c;let{signal:u,cleanup:d}=sP(c,r?.signal);this.llm.setRequestSignal?.(u),om(u);let p=this.history.serialise();try{this.history.add({role:"user",content:s,timestamp:Date.now()});let m=await this.registry.execute(t,n,{...this.userContext,query:s});km(u);let g=m.success?JSON.stringify(m.data):`Error: ${m.error}`,f=Date.now(),y=[{subagentName:l[0],steps:[{phase:"act",content:`Calling tool: ${t}`,toolCall:{toolName:t,args:n},timestamp:f},{phase:"observe",content:g,toolResult:m,timestamp:f}],finalAnswer:"",toolResults:[m],toolMessages:[]}],w=this.mergeTrace(y),v=await this.synthesizer.synthesise(s,w,this.synthesiserHistory(),i??void 0),A=uS(v,y),k=this.collectUiActions(y,i),T=this.collectActionButtons(y,i);return{...await this.finaliseAnswer({userMessage:s,answer:A,subagents:l,uiActions:k,actionButtons:T,messageId:o}),messageId:o,trace:w,subagentResults:y,...k.length>0?{uiActions:k}:{},...T.length>0?{actionButtons:T}:{}}}catch(m){throw Va(m)||u.aborted?(this.history.restore(p),new Ni):(this.history.restore(p),m)}finally{d(),this.llm.setRequestSignal?.(void 0),om(void 0),this.currentAbortController===c&&(this.currentAbortController=null)}}setX402Signer(t){this.x402Signer=t,GL(t?oP({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(t,n,r){this.assertLicense(),await this.loadHistory();let o=rm(),s=t,i=r?.userQuery||s?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let a;try{a=await nP(se,s,n)}catch(c){let d=`The payment couldn't be completed: ${c instanceof Error?c.message:String(c)}. Please try again.`;return this.history.add({role:"assistant",content:d,timestamp:Date.now(),messageId:o}),await this.persistHistory(),{answer:d,messageId:o}}return{...await this.synthesizeFromPaidData(i,a,o),messageId:o}}async synthesizeFromPaidData(t,n,r){let o=typeof n=="string"?n:JSON.stringify(n),s=this.systemPrompt+this.capabilitiesSummary(),i=`The user's question was: "${t}".
|
|
1423
1420
|
|
|
1424
1421
|
A paid API returned this data:
|
|
1425
1422
|
${o}
|
|
@@ -1472,9 +1469,9 @@ REFERENCE MATERIAL:
|
|
|
1472
1469
|
`+r+`
|
|
1473
1470
|
---`:this.systemPrompt)+this.capabilitiesSummary()+i+`
|
|
1474
1471
|
|
|
1475
|
-
REMINDER:
|
|
1472
|
+
REMINDER: NEVER quote prediction-market odds or probabilities (Polymarket or any other) from web search or memory \u2014 even if earlier turns discussed prediction markets; only the prediction tools may supply them.`,c=Ts(n),u=[{role:"system",content:l,timestamp:0},...c,{role:"user",content:t,timestamp:Date.now()}],d=await this.llm.chat(u,void 0,{googleSearch:s});return await this.finaliseAnswer({userMessage:t,answer:d.text,messageId:o})}async answerUnsupportedChain(t,n,r,o){this.debug&&console.log(`[AgentCore] connected chain "${t}" is not supported \u2192 short-circuit with notice`);let s=(n||"").trim(),i=o&&o.trim()||nu,a=[{role:"system",content:`Write ONE short, polite message telling the user that the blockchain network they want to use is NOT supported by this assistant, and inviting them to use one of the supported networks. List the supported networks: ${i}. Use ONLY the network NAMES \u2014 NEVER show any hex chain id (e.g. never write "0x1" or "(0xa)"). Do NOT mention or guess the name or chain id of the unsupported network. `+(s?`Reply in BCP-47 language "${s}".`:"Reply in the same language the user has been using.")+" Do NOT mention tools or internal implementation details.",timestamp:0},{role:"user",content:"Is my currently connected network supported?",timestamp:Date.now()}],c=(await this.llm.chat(a)).text?.trim()||`Your currently connected network is not supported yet. Supported networks: ${i}.`;return await this.finaliseAnswer({userMessage:`[unsupported chain: ${t}]`,answer:c,messageId:r})}synthesiserHistory(){let t=this.history.getConversation(),n=t.length>0&&t[t.length-1].role==="user"?t.slice(0,-1):t;return Ts(n)}mergeTrace(t){let n=[];for(let o of t)n.push({phase:"think",content:`[${o.subagentName}] begin`,timestamp:Date.now()}),n.push(...o.steps),n.push({phase:"observe",content:`[${o.subagentName}] answer: ${o.finalAnswer}`,timestamp:Date.now()});let r=t.map(o=>`[${o.subagentName}] ${o.finalAnswer}`).join(`
|
|
1476
1473
|
|
|
1477
|
-
`);return{steps:n,finalAnswer:r}}async finaliseAnswer(t){let{subagents:n,uiActions:r,actionButtons:o,messageId:s}=t??{},i=typeof t?.answer=="string"?
|
|
1474
|
+
`);return{steps:n,finalAnswer:r}}async finaliseAnswer(t){let{subagents:n,uiActions:r,actionButtons:o,messageId:s}=t??{},i=typeof t?.answer=="string"?uye(t.answer,r):t?.answer,a={role:"assistant",content:i,timestamp:Date.now()};return n&&n.length>0&&(a.subagents=n),r&&r.length>0&&(a.uiActions=r),o&&o.length>0&&(a.actionButtons=o),s&&(a.messageId=s),this.history.add(a),await this.persistHistory(),{answer:i,...o&&o.length>0?{actionButtons:o}:{}}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(t=>!(t.role!=="user"&&t.role!=="assistant"||t._intermediate||t.role==="assistant"&&!t.content?.trim()))}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(t){this.history.restore(t)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let t=this.history.getAll(),n=6,r=0,o=t.length;for(let p=t.length-1;p>=0;p--)if(t[p].role==="user"&&(r++,r>=n)){o=p;break}let s=t.slice(o),i=UW(s,s.length),a=t.length-i.length,l=Ts(t.slice(0,a)),c=this.history.getSummary(),u=[];c&&u.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),u.push(...l);let d=await this.summarizer.summarize(u);this.history.compactWith(d,i)}persistToolMessages(t){for(let n of t)n.toolMessages.length>0&&(this.history.addMany(n.toolMessages),this.history.add({role:"assistant",content:n.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${n.toolMessages.length} tool message(s) + finalAnswer from ${n.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};function uye(e,t){if(!t?.some(r=>r.completeList===!0))return e;let n=e.indexOf(jr);return n===-1?e:e.slice(0,n).trimEnd()}var XW=require("js-sha3");var HL="keyring-website-trust-cache";var KW=new Map,YW=new Map,pS=class{constructor(t,n,r=HL){this.isValue=t;this.storage=n;this.storageKey=r;let o=KW.get(r);o||(o=new Map,KW.set(r,o)),this.memory=o}isValue;storage;storageKey;memory;async get(t,n){await this.hydrate();let r=this.memory.get(t);if(!r)return;let o=Date.now();if(!this.isFresh(r,o)||o-r.storedAt>=n){this.memory.delete(t);return}return r.value}async set(t,n,r){await this.hydrate();let o=Date.now();this.memory.set(t,{storedAt:o,expiresAt:o+r,value:n}),this.prune(),await this.persist()}async clear(){if(this.memory.clear(),!!this.storage)try{await this.storage.removeItem(this.storageKey)}catch{}}hydrate(){if(!this.storage)return Promise.resolve();let t=YW.get(this.storageKey);return t||(t=this.readStorage(),YW.set(this.storageKey,t)),t}async readStorage(){try{let t=await this.storage.getItem(this.storageKey);if(!t)return;let n=JSON.parse(t);if(!n||typeof n!="object")return;let r=Date.now();for(let[o,s]of Object.entries(n))!this.memory.has(o)&&typeof s?.storedAt=="number"&&typeof s.expiresAt=="number"&&this.isFresh(s,r)&&this.isValue(s.value)&&this.memory.set(o,s)}catch{}}prune(){let t=Date.now();for(let[r,o]of this.memory)this.isFresh(o,t)||this.memory.delete(r);if(this.memory.size<=200)return;let n=[...this.memory.entries()].sort((r,o)=>r[1].expiresAt-o[1].expiresAt);for(let[r]of n.slice(0,this.memory.size-200))this.memory.delete(r)}isFresh(t,n){return t.storedAt<=n&&n<t.expiresAt}async persist(){if(this.storage)try{await this.storage.setItem(this.storageKey,JSON.stringify(Object.fromEntries(this.memory)))}catch{}}};var mye="Every domain you analyze is the website of a service that integrates WalletConnect \u2014 i.e. a blockchain / Web3 application (DeFi, DEX, NFT marketplace, bridge, wallet, staking, launchpad, GameFi, etc.). Investigate it WITHIN that crypto/Web3 ecosystem FIRST: assume any brand it resembles is most likely a crypto/blockchain project, look up that brand's official domains within that ecosystem, and prioritize crypto-focused phishing/scam intelligence. This is a strong prior, NOT a guarantee \u2014 if the evidence shows it actually imitates a major NON-crypto brand or is a plain scam, still flag it. NEVER assume a domain is legitimate merely because it sits in the crypto space.",QW='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.';function hye(e){let t=e,n=r=>r===void 0||Array.isArray(r)&&r.every(o=>typeof o=="string");return typeof t?.answer=="string"&&typeof t.extraData=="object"&&t.extraData!==null&&typeof t.extraData.isPhishing=="boolean"&&(t.extraData.copiedSite===void 0||typeof t.extraData.copiedSite=="string")&&n(t.extraData.reasons)&&n(t.extraData.keyFeatures)}var mS=class{llm;debug;ecosystem;secretKey;ownGeminiKey;licenseChecked=!1;cache;officialCacheTtlMs;assessCacheTtlMs;constructor(t={}){this.llm=t.provider??new jt({temperature:.5,...t.llm}),this.debug=t.debug??!1,this.ecosystem=t.ecosystemContext?.trim()||mye,this.secretKey=t.secretKey??"",this.ownGeminiKey=!!t.llm?.apiKey?.trim(),this.officialCacheTtlMs=t.officialCacheTtlMs??6048e5,this.assessCacheTtlMs=t.assessCacheTtlMs??864e5,this.cache=new pS(hye,t.cacheStorage,t.cacheStorageKey??HL)}async clearCache(){await this.cache.clear()}assertLicense(){if(this.licenseChecked)return;if(this.ownGeminiKey){this.licenseChecked=!0;return}let t="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(t&&(!this.secretKey||(0,XW.sha3_256)(this.secretKey)!==t))throw new Error("WebsiteTrustKeyringAgent: invalid or missing secretKey. Pass a valid secretKey to use the Keyring Gemini proxy, or supply your own Gemini key via llm.apiKey to call the Gemini API directly.");this.licenseChecked=!0}async chat(t){this.assertLicense();let n=(t?.url??"").trim();if(!n)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let r=t.language?.trim()||"English",o=[t.isMarkOfficial?"official":"assess",this.languageLabel(r).toLowerCase(),this.toHost(n)].join("|"),s=t.isMarkOfficial?this.officialCacheTtlMs:this.assessCacheTtlMs,i=s>0?await this.cache.get(o,s):void 0;if(i){this.debug&&console.log("[WebsiteTrustKeyringAgent] cache hit:",o);let a=JSON.parse(JSON.stringify(i));return a.extraData.currentSite=n,a}try{let{result:a,cacheable:l}=await this.analyze(n,t.isMarkOfficial,r,t.signal);return l&&s>0&&await this.cache.set(o,a,s),a}catch(a){throw new Error(`WebsiteTrustKeyringAgent.chat failed: ${a instanceof Error?a.message:String(a)}`,{cause:a})}}async analyze(t,n,r,o){let s=this.normalizeSite(t);if(n){let{description:g,keyFeatures:f}=await this.describeOfficial(t,o),{answer:y,keyFeatures:w,localized:v}=await this.present(s,{isPhishing:!1,trusted:!0,description:g,reasons:[],keyFeatures:f},r,o),A={currentSite:t,isPhishing:!1};return w.length>0&&(A.keyFeatures=w),{result:{answer:y,extraData:A},cacheable:!!g&&v&&w.length>0}}let i=await this.investigate(t,s,o),a=this.buildVerdict(s,i),l=i.keyFeatures;!a.isPhishing&&l.length===0&&(l=await this.gatherKeyFeatures(t,o)),this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",s),console.log("[WebsiteTrustKeyringAgent] investigation:",i),console.log("[WebsiteTrustKeyringAgent] verdict:",a),console.log("[WebsiteTrustKeyringAgent] keyFeaturesEvidence:",l));let{answer:c,reasons:u,keyFeatures:d,localized:p}=await this.present(s,{isPhishing:a.isPhishing,description:i.description,copiedSite:a.copiedSite,reasons:a.reasons,keyFeatures:l},r,o),m={currentSite:t,isPhishing:a.isPhishing};return a.copiedSite&&(m.copiedSite=a.copiedSite),a.isPhishing&&u.length>0&&(m.reasons=u),!a.isPhishing&&d.length>0&&(m.keyFeatures=d),{result:{answer:c,extraData:m},cacheable:i.answered&&p&&(a.isPhishing||d.length>0)}}buildVerdict(t,n){let r=n.officialDomain,o=r?n.affiliatedDomains.filter(g=>!this.looksLikeSquatOf(g,r)):n.affiliatedDomains,s=[n.officialDomain,...o].filter(g=>!!g),i=s.length>0?s.some(g=>this.isSameRegistrableDomain(t,g)):n.exactMatchOfficial,l=(n.resemblesBrand||this.carriesBrandName(t,n.officialDomain,n.brand))&&!i&&n.brandIsWellKnown&&(s.length>0||!n.hasOwnLegitPresence),u=!(i||n.hasOwnLegitPresence&&!l)&&n.scamReports.length>0,d=l||u;if(!d)return{isPhishing:!1,reasons:[]};let p=[];if(l){let g=n.officialDomain?this.describeLookAlike(t,n.officialDomain):void 0;g&&p.push(g),n.impersonationEvidence.length>0?p.push(...n.impersonationEvidence):g||p.push(n.officialDomain?`This address (${t}) is not the official ${n.brand??"brand"} domain \u2014 the real one is ${n.officialDomain}; the look-alike is easy to miss at a glance.`:`This domain (${t}) imitates ${n.brand??"a known brand"} but is not its official site and has no legitimate presence of its own.`)}u&&p.push(...n.scamReports);let m=l?n.officialUrl??n.officialDomain??n.brand:void 0;return{isPhishing:d,copiedSite:m,reasons:this.dedupe(p)}}async investigate(t,n,r){let o=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${n}
|
|
1478
1475
|
URL: ${t}
|
|
1479
1476
|
|
|
1480
1477
|
Investigate, using web search, whether this EXACT domain is a legitimate official site or a phishing / look-alike / scam site. Work through:
|
|
@@ -1540,7 +1537,7 @@ LANGUAGE (MANDATORY): write "answer", every "reasons" item AND every "keyFeature
|
|
|
1540
1537
|
|
|
1541
1538
|
Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:o,googleSearch:!1,system:this.presentationSystem(s),maxRetries:2,maxOutputTokens:1536}),u=this.cleanStr(c?.answer),d=u??(n.description||t),p=this.cleanStrArray(c?.reasons),m=this.cleanStrArray(c?.keyFeatures);return{answer:d,localized:u!==void 0&&(n.reasons.length===0||p.length>0)&&(!i||m.length>0),reasons:p.length>0?p.slice(0,5):n.reasons.slice(0,5),keyFeatures:i?(m.length>0?m:n.keyFeatures).slice(0,5):[]}}languageLabel(t){let n={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},r=t.trim().toLowerCase();return n[r]??n[r.split("-")[0]]??t}presentationSystem(t){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${t} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${t}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
|
|
1542
1539
|
|
|
1543
|
-
${QW}`}async askJson(t,n={}){let{signal:r,googleSearch:o=!0,system:s=QW,maxRetries:i=2,maxOutputTokens:a,thinkingBudget:l}=n,c=Date.now(),u=[{role:"system",content:s,timestamp:c},{role:"user",content:t,timestamp:c}],d=await this.llm.chat(u,void 0,{googleSearch:o,maxRetries:i,maxOutputTokens:a,thinkingBudget:l,signal:r}),p=this.parseJson(d.text?.trim()??"");return this.debug&&!p&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(d.text??"").slice(0,200)),p}normalizeSite(t){try{let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`,r=new URL(n).hostname||t;return this.decodeIdn(r)}catch{return t}}toHost(t){return this.normalizeSite(t.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(t){return t.includes("xn--")?t.split(".").map(n=>n.startsWith("xn--")?this.punycodeDecodeLabel(n.slice(4)):n).join("."):t}punycodeDecodeLabel(t){let c=(d,p,m)=>{d=m?Math.floor(d/700):d>>1,d+=Math.floor(d/p);let g=0;for(;d>455;)d=Math.floor(d/35),g+=36;return g+Math.floor(36*d/(d+38))},u=d=>d-48<10?d-22:d-65<26?d-65:d-97<26?d-97:36;try{let d=[],p=t.lastIndexOf("-");for(let w=0;w<Math.max(0,p);w++){let v=t.charCodeAt(w);if(v>=128)return t;d.push(v)}let m=0,g=128,f=72,y=p<0?0:p+1;for(;y<t.length;){let w=m,v=1;for(let k=36;;k+=36){if(y>=t.length)return t;let T=u(t.charCodeAt(y++));if(T>=36)return t;m+=T*v;let D=k<=f?1:k>=f+26?26:k-f;if(T<D)break;v*=36-D}let A=d.length+1;f=c(m-w,A,w===0),g+=Math.floor(m/A),m%=A,d.splice(m,0,g),m++}return String.fromCodePoint(...d)}catch{return t}}isSameRegistrableDomain(t,n){let r=this.toHost(t),o=this.toHost(n);return!r||!o?!1:r===o||r.endsWith(`.${o}`)}alnum(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(t){return this.toHost(t).split(".").map(n=>this.alnum(n)).filter(Boolean)}brandCore(t){return this.hostLabels(t)[0]??""}editDistance(t,n){let r=t.length,o=n.length;if(!r)return o;if(!o)return r;let s=Array.from({length:o+1},(i,a)=>a);for(let i=1;i<=r;i++){let a=[i];for(let l=1;l<=o;l++){let c=t[i-1]===n[l-1]?0:1;a[l]=Math.min(s[l]+1,a[l-1]+1,s[l-1]+c)}s=a}return s[o]}isNearMiss(t,n){if(!t||!n||t===n)return!1;let r=Math.max(t.length,n.length);if(r<4||Math.abs(t.length-n.length)>2)return!1;let o=this.editDistance(t,n);return o>=1&&o<=(r>=8?2:1)}carriesBrandName(t,n,r){let o=this.alnum(this.toHost(t));if(!o)return!1;let s=this.hostLabels(t);return[n?this.brandCore(n):"",this.alnum(r??"")].filter(a=>a.length>=4).some(a=>o.includes(a)||s.some(l=>this.isNearMiss(l,a)))}looksLikeSquatOf(t,n){if(this.isSameRegistrableDomain(t,n))return!1;let r=this.brandCore(n);if(r.length<4)return!1;let o=this.hostLabels(t);return o.includes(r)?!1:o.some(s=>this.isNearMiss(s,r)||s.length>r.length&&s.includes(r))}describeLookAlike(t,n){let r=this.toHost(t),o=this.toHost(n);if(!r||!o||r===o)return;if(/[^\u0020-\u007E]/.test(r))return`The address "${r}" uses look-alike (non-standard) characters to imitate the official ${o}; to the eye it reads the same, but it is a different address.`;let s=r.lastIndexOf("."),i=o.lastIndexOf(".");if(s>0&&i>0){let c=r.slice(0,s),u=o.slice(0,i),d=r.slice(s+1),p=o.slice(i+1);if(c===u&&d!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${d}" (${r} vs ${o}) \u2014 a look-alike that is easy to miss at a glance.`}let a=this.brandCore(o),l=this.hostLabels(r).find(c=>this.isNearMiss(c,a));if(l){let c=this.editDistance(l,a);return`The address "${r}" is a near-copy of the official ${o} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${a}"), a typo that is easy to overlook.`}if(a.length>=4&&this.alnum(r).includes(a))return`The address "${r}" reuses the "${a}" name with extra text added to look affiliated with the official ${o}, but it is a different, unofficial domain.`}parseJson(t){if(!t)return null;let n=t.replace(/```(?:json)?/gi,"").trim(),r=n.indexOf("{"),o=n.lastIndexOf("}");if(r===-1||o===-1||o<=r)return null;try{return JSON.parse(n.slice(r,o+1))}catch{return null}}cleanStr(t){if(typeof t!="string")return;let n=t.trim();if(!n)return;let r=n.toLowerCase();if(!(r==="null"||r==="none"||r==="n/a"||r==="undefined"))return n}cleanStrArray(t){let n=Array.isArray(t)?t:typeof t=="string"?t.split(/\r?\n|(?:^|\s)[-•]\s+/):[],r=[];for(let o of n){let s=this.coerceToStr(o);s&&r.push(s)}return r}coerceToStr(t){if(typeof t=="string")return this.cleanStr(t);if(!t||typeof t!="object")return;let n=t,r=this.cleanStr(n.feature)??this.cleanStr(n.name)??this.cleanStr(n.title),o=this.cleanStr(n.description)??this.cleanStr(n.detail)??this.cleanStr(n.text)??this.cleanStr(n.value);return r&&o?r===o?r:`${r} \u2014 ${o}`:r||o?r??o:Object.values(n).map(i=>this.cleanStr(i)).filter(i=>!!i).join(" \u2014 ")||void 0}dedupe(t){let n=new Set,r=[];for(let o of t){let s=o.toLowerCase();n.has(s)||(n.add(s),r.push(o))}return r}};var gye=e=>{let t=JSON.parse(e),n=Array.isArray(t)?t:t?.entries;if(!Array.isArray(n))throw new Error("JSON must be an array or { entries: [...] }");return n.map((r,o)=>{if(!r||typeof r.question!="string"||typeof r.answer!="string")throw new Error(`Entry #${o} is missing "question" or "answer"`);return r})};async function JW(e,t){let n=e.entries??(e.json?gye(e.json):[]);return n.length===0?{count:0}:new Ra(t).upsert(n)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BRIDGE_NON_EVM_CHAIN_FAMILY,BRIDGE_STATUS_POLL_MS,BRIDGE_SUPPORT_URL,BUILDER_CODE,BaseNftAiTool,BaseSwapProvider,BaseTool,BaseWalletActionTool,BuyTokenTool,CachedResource,ChatHistory,CoinpoolConfigApi,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DEFILLAMA_EXTRA_SIGNALS,DEFILLAMA_POOL_CHAIN_HEXES,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION,DELAYED_ORDER,DEPOSIT_REFERENCE_USD,DEPOSIT_STABLE_SYMBOLS,DebridgeProvider,DefiLlamaEstimatePoolYieldTool,DefiLlamaPoolByAddressTool,DefiLlamaPoolCandidateResolver,DefiLlamaPoolDetailTool,DefiLlamaPoolSearchTool,DefiLlamaPoolService,DefiLlamaTopPoolsTool,ERC1967_INIT_CODE,EstimatePoolYieldTool,GAMES_TAG_ID,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,HIDE_FROM_NEW_TAG_ID,KeyringSettingApi,KnowledgeBase,LendingMarketDetailTool,LendingMarketsTool,LendingReadService,LendingService,LendingSupplyService,MARKET_ORDER,MARKET_STREAM,MULTICALL3_ADDRESS,ManageLiquidityRedirectTool,MoralisService,NATIVE_GAS_LIMIT,NATIVE_TOKEN_PLACEHOLDER,NFC_AGENT_TOOL_NAMES,NFC_AMAZON_DEFAULT_DOMAIN,NFC_AMAZON_DOMAINS,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,NfcBuyTool,NfcInfoTool,NoFormTool,ONBOARDING_STEP,ONBOARDING_TRACKING,ORDER_INPUT_ERROR,OpenAddLiquidityFormTool,OpenSupplyFormTool,PERPS_DEPOSIT_CONTRACT,POLYGON_CHAIN_ID,POLYGON_HEX_CHAIN_ID,POLYMARKET_API,POLYMARKET_LIVE_DATA_WS,POLYMARKET_WEB_URL,POOL_UNISWAP_AGENT_TOOL_NAMES,POSITION_DUST_SHARES,PREDICTION_ACTIVITY_TYPES,PREDICTION_AGENT_TOOL_NAMES,PREDICTION_CATEGORIES,PREDICTION_SORTS,PUSD_ADDRESS,PUSD_DECIMALS,PantographService,PolymarketApiError,PolymarketOnboardingError,PolymarketRedeemError,PolymarketService,PolymarketTradeError,PolymarketWithdrawError,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PoolSwapRouter,PredictionActivityTool,PredictionDepositTool,PredictionMarketDetailTool,PredictionMarketsTool,PredictionPortfolioTool,PredictionSetupTool,PredictionTradeTool,PredictionWithdrawTool,PreviewAddLiquidityTool,PublicClient,REDEEM,RELAYER_DEPLOY_POLL,RELAYER_SUBMIT_PATH,RelayProvider,Router,SUPPLIABLE_TYPES,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapProviderFactory,SwapRouter,SwapRouterRegistry,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRADE_ERROR,TRADING_APPROVALS_METADATA,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UNRESOLVED_ASSET,UP_OR_DOWN_TAG_ID,UpstashKnowledgeBase,UserSwapRouter,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WALLET_DERIVATION,WITHDRAW,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletHistoryTool,WalletLendingPositionsTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustKeyringAgent,ZERO_ADDRESS,adjustBuyAmountForFees,allInBuyNotional,amazonDomainForLanguage,apiClient,applyMarketEvent,applyYieldConversions,bestPrice,buildApprovalCalls,buildApprovals,buildBuilderSignature,buildChallenge,buildRangePresets,buildUniswapPoolUrl,builderApiKey,buyNotional,buyNotionalAfterFee,call,canDeriveV3PoolAddress,ceil2,chains,checkNativeGasAffordable,checksumAddress,clampTick,classifyTradeError,classifyWithdrawError,clearPublicClientCache,coinpoolConfigApi,compareDecimal,completeX402,configureSupportedChains,configureSwapProvider,convertSusdsShares,createAiAgent,createDefaultSubagents,createNfcAgent,createNftAgent,createPolymarketSigner,createPoolUniswapAgent,createPredictionAgent,createPublicClient,createTokenAgent,createTransport,createWalletActionAgent,createWalletAgent,createX402SignatureProvider,decodeAbiParameters,decodeErrorResult,decodeFunctionData,decodeFunctionResult,defiLlamaPoolInfoScope,defiLlamaPoolSupportsLabel,deployDepositWallet,depositPriceImpact,deriveBeaconDepositWallet,deriveDepositWallet,deriveSafeWallet,deriveUupsDepositWallet,deriveV3PoolAddress,displayFromChallenge,effectivePriceUSD,encodeAbiParameters,encodeApprove,encodeErrorResult,encodeFunctionData,encodeSignedHeader,erc1155Abi,erc20Abi,erc20Abi_bytes32,erc721Abi,estimateGas,estimateNativeGasReserveWei,estimateTransactionFeeWei,ethCallAt,ethCallByChain,eventHeadline,eventUrl,evmDepositAssets,exactAmountString,extractOutRaw,extractQuoteError,fallback,feePerShare,feeWeiToNative,fetchOnboardingSnapshot,fetchTopMarketplaces,fetchTradingApprovalsStatus,fetchUnderlyingPricesUSD,findWalletDepositOptions,floor2,floorToDecimals,formatDefiLlamaPool,getAbiItem,getAddress,getBalance,getBlock,getBlockNumber,getCashBalance,getCashBalanceBaseUnits,getChain,getChainContractAddress,getChainId,getChainMeta,getCode,getDefaultRpcUrl,getGasPrice,getNativeTokenInfo,getPolymarketBuilderCode,getPublicClient,getRevertReason,getRpcOverrides,getStorageAt,getTokenPriceUSD,getTransactionCount,http,humanToWei,ingestKnowledgeBase,isAbortError,isAddress,isAddressEqual,isBelowWithdrawMinimum,isEvmAddress,isMarketOpen,isPaymentRequired,isShareBasedProtocol,isShareBasedYieldToken,isSupplyChain,keyringSettingApi,listCandidateChains,listSupplyChains,mapEvent,mapMarket,marketFee,marketProtocol,moneylineMarket,mulDivFloor,multicall,multicall3Abi,multicallRaw,nativeGasShortfall,nfcAmazonSearchUrl,normaliseCountry,normalizeDecimal,normalizeLevels,normalizePriceRangeToPool,normalizeText,onboardingStep,openSecureClient,parseAbi,parseAbiItem,parseAbiParameters,parsePolymarketUrl,parsePredictionHint,pickLogo,placePredictionOrder,planYieldTokenConversions,predictionHint,prepareMarketOrder,priceToTick,protocolLabelFor,psm3For,pusdFromBaseUnits,pusdToBaseUnits,quoteBuyAsPolymarket,quoteBuyUsd,quoteDeposit,quoteMarketOrder,quoteSellShares,quoteWithdrawal,readContract,readPaymentError,readPaymentRequired,readProtocolFeeWei,readReceipt,readSpendableBalance,readTokenUsdPrice,redeemPredictionPositions,registerMaybeNoForm,remoteBuilderSigning,requestWithX402,resolveAccountWallet,resolveCategory,resolveGasLimit,resolveNfcShopLinks,resolveRawYieldAsset,resolveRawYieldIdentity,resolveRawYieldProtocol,resolveRpcUrl,resolveRpcUrls,resolveTokenPriceUSD,roundTickToSpacing,rpcCall,runPolymarketOnboarding,setPolymarketBuilderCode,setRpcOverrides,slippagePrice,spendableNative,swapProviderFactory,swapRouterRegistry,tickToPrice,ticketFee,toBuilderAuthorization,toEventSelector,toFunctionSelector,toPantographChain,toPlainDecimal,unitPriceUSD,upDownWindow,valueYieldTokens,walletDepositAssets,watchCryptoPrice,watchOrderBooks,weiToHuman,withdrawDestinations,withdrawFromPolymarket});
|
|
1540
|
+
${QW}`}async askJson(t,n={}){let{signal:r,googleSearch:o=!0,system:s=QW,maxRetries:i=2,maxOutputTokens:a,thinkingBudget:l}=n,c=Date.now(),u=[{role:"system",content:s,timestamp:c},{role:"user",content:t,timestamp:c}],d=await this.llm.chat(u,void 0,{googleSearch:o,maxRetries:i,maxOutputTokens:a,thinkingBudget:l,signal:r}),p=this.parseJson(d.text?.trim()??"");return this.debug&&!p&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(d.text??"").slice(0,200)),p}normalizeSite(t){try{let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`,r=new URL(n).hostname||t;return this.decodeIdn(r)}catch{return t}}toHost(t){return this.normalizeSite(t.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(t){return t.includes("xn--")?t.split(".").map(n=>n.startsWith("xn--")?this.punycodeDecodeLabel(n.slice(4)):n).join("."):t}punycodeDecodeLabel(t){let c=(d,p,m)=>{d=m?Math.floor(d/700):d>>1,d+=Math.floor(d/p);let g=0;for(;d>455;)d=Math.floor(d/35),g+=36;return g+Math.floor(36*d/(d+38))},u=d=>d-48<10?d-22:d-65<26?d-65:d-97<26?d-97:36;try{let d=[],p=t.lastIndexOf("-");for(let w=0;w<Math.max(0,p);w++){let v=t.charCodeAt(w);if(v>=128)return t;d.push(v)}let m=0,g=128,f=72,y=p<0?0:p+1;for(;y<t.length;){let w=m,v=1;for(let k=36;;k+=36){if(y>=t.length)return t;let T=u(t.charCodeAt(y++));if(T>=36)return t;m+=T*v;let D=k<=f?1:k>=f+26?26:k-f;if(T<D)break;v*=36-D}let A=d.length+1;f=c(m-w,A,w===0),g+=Math.floor(m/A),m%=A,d.splice(m,0,g),m++}return String.fromCodePoint(...d)}catch{return t}}isSameRegistrableDomain(t,n){let r=this.toHost(t),o=this.toHost(n);return!r||!o?!1:r===o||r.endsWith(`.${o}`)}alnum(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(t){return this.toHost(t).split(".").map(n=>this.alnum(n)).filter(Boolean)}brandCore(t){return this.hostLabels(t)[0]??""}editDistance(t,n){let r=t.length,o=n.length;if(!r)return o;if(!o)return r;let s=Array.from({length:o+1},(i,a)=>a);for(let i=1;i<=r;i++){let a=[i];for(let l=1;l<=o;l++){let c=t[i-1]===n[l-1]?0:1;a[l]=Math.min(s[l]+1,a[l-1]+1,s[l-1]+c)}s=a}return s[o]}isNearMiss(t,n){if(!t||!n||t===n)return!1;let r=Math.max(t.length,n.length);if(r<4||Math.abs(t.length-n.length)>2)return!1;let o=this.editDistance(t,n);return o>=1&&o<=(r>=8?2:1)}carriesBrandName(t,n,r){let o=this.alnum(this.toHost(t));if(!o)return!1;let s=this.hostLabels(t);return[n?this.brandCore(n):"",this.alnum(r??"")].filter(a=>a.length>=4).some(a=>o.includes(a)||s.some(l=>this.isNearMiss(l,a)))}looksLikeSquatOf(t,n){if(this.isSameRegistrableDomain(t,n))return!1;let r=this.brandCore(n);if(r.length<4)return!1;let o=this.hostLabels(t);return o.includes(r)?!1:o.some(s=>this.isNearMiss(s,r)||s.length>r.length&&s.includes(r))}describeLookAlike(t,n){let r=this.toHost(t),o=this.toHost(n);if(!r||!o||r===o)return;if(/[^\u0020-\u007E]/.test(r))return`The address "${r}" uses look-alike (non-standard) characters to imitate the official ${o}; to the eye it reads the same, but it is a different address.`;let s=r.lastIndexOf("."),i=o.lastIndexOf(".");if(s>0&&i>0){let c=r.slice(0,s),u=o.slice(0,i),d=r.slice(s+1),p=o.slice(i+1);if(c===u&&d!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${d}" (${r} vs ${o}) \u2014 a look-alike that is easy to miss at a glance.`}let a=this.brandCore(o),l=this.hostLabels(r).find(c=>this.isNearMiss(c,a));if(l){let c=this.editDistance(l,a);return`The address "${r}" is a near-copy of the official ${o} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${a}"), a typo that is easy to overlook.`}if(a.length>=4&&this.alnum(r).includes(a))return`The address "${r}" reuses the "${a}" name with extra text added to look affiliated with the official ${o}, but it is a different, unofficial domain.`}parseJson(t){if(!t)return null;let n=t.replace(/```(?:json)?/gi,"").trim(),r=n.indexOf("{"),o=n.lastIndexOf("}");if(r===-1||o===-1||o<=r)return null;try{return JSON.parse(n.slice(r,o+1))}catch{return null}}cleanStr(t){if(typeof t!="string")return;let n=t.trim();if(!n)return;let r=n.toLowerCase();if(!(r==="null"||r==="none"||r==="n/a"||r==="undefined"))return n}cleanStrArray(t){let n=Array.isArray(t)?t:typeof t=="string"?t.split(/\r?\n|(?:^|\s)[-•]\s+/):[],r=[];for(let o of n){let s=this.coerceToStr(o);s&&r.push(s)}return r}coerceToStr(t){if(typeof t=="string")return this.cleanStr(t);if(!t||typeof t!="object")return;let n=t,r=this.cleanStr(n.feature)??this.cleanStr(n.name)??this.cleanStr(n.title),o=this.cleanStr(n.description)??this.cleanStr(n.detail)??this.cleanStr(n.text)??this.cleanStr(n.value);return r&&o?r===o?r:`${r} \u2014 ${o}`:r||o?r??o:Object.values(n).map(i=>this.cleanStr(i)).filter(i=>!!i).join(" \u2014 ")||void 0}dedupe(t){let n=new Set,r=[];for(let o of t){let s=o.toLowerCase();n.has(s)||(n.add(s),r.push(o))}return r}};var fye=e=>{let t=JSON.parse(e),n=Array.isArray(t)?t:t?.entries;if(!Array.isArray(n))throw new Error("JSON must be an array or { entries: [...] }");return n.map((r,o)=>{if(!r||typeof r.question!="string"||typeof r.answer!="string")throw new Error(`Entry #${o} is missing "question" or "answer"`);return r})};async function JW(e,t){let n=e.entries??(e.json?fye(e.json):[]);return n.length===0?{count:0}:new Ra(t).upsert(n)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BRIDGE_NON_EVM_CHAIN_FAMILY,BRIDGE_STATUS_POLL_MS,BRIDGE_SUPPORT_URL,BUILDER_CODE,BaseNftAiTool,BaseSwapProvider,BaseTool,BaseWalletActionTool,BuyTokenTool,CachedResource,ChatHistory,CoinpoolConfigApi,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DEFILLAMA_EXTRA_SIGNALS,DEFILLAMA_POOL_CHAIN_HEXES,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION,DELAYED_ORDER,DEPOSIT_REFERENCE_USD,DEPOSIT_STABLE_SYMBOLS,DebridgeProvider,DefiLlamaEstimatePoolYieldTool,DefiLlamaPoolByAddressTool,DefiLlamaPoolCandidateResolver,DefiLlamaPoolDetailTool,DefiLlamaPoolSearchTool,DefiLlamaPoolService,DefiLlamaTopPoolsTool,ERC1967_INIT_CODE,EstimatePoolYieldTool,GAMES_TAG_ID,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,HIDE_FROM_NEW_TAG_ID,KeyringSettingApi,KnowledgeBase,LendingMarketDetailTool,LendingMarketsTool,LendingReadService,LendingService,LendingSupplyService,MARKET_ORDER,MARKET_STREAM,MULTICALL3_ADDRESS,ManageLiquidityRedirectTool,MoralisService,NATIVE_GAS_LIMIT,NATIVE_TOKEN_PLACEHOLDER,NFC_AGENT_TOOL_NAMES,NFC_AMAZON_DEFAULT_DOMAIN,NFC_AMAZON_DOMAINS,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,NfcBuyTool,NfcInfoTool,NoFormTool,ONBOARDING_STEP,ONBOARDING_TRACKING,ORDER_INPUT_ERROR,OpenAddLiquidityFormTool,OpenSupplyFormTool,PERPS_DEPOSIT_CONTRACT,POLYGON_CHAIN_ID,POLYGON_HEX_CHAIN_ID,POLYMARKET_API,POLYMARKET_LIVE_DATA_WS,POLYMARKET_WEB_URL,POOL_UNISWAP_AGENT_TOOL_NAMES,POSITION_DUST_SHARES,PREDICTION_ACTIVITY_TYPES,PREDICTION_AGENT_TOOL_NAMES,PREDICTION_CATEGORIES,PREDICTION_SORTS,PUSD_ADDRESS,PUSD_DECIMALS,PantographService,PolymarketApiError,PolymarketOnboardingError,PolymarketRedeemError,PolymarketService,PolymarketTradeError,PolymarketWithdrawError,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PoolSwapRouter,PredictionActivityTool,PredictionDepositTool,PredictionMarketDetailTool,PredictionMarketsTool,PredictionPortfolioTool,PredictionSetupTool,PredictionTradeTool,PredictionWithdrawTool,PreviewAddLiquidityTool,PublicClient,REDEEM,RELAYER_DEPLOY_POLL,RELAYER_SUBMIT_PATH,RelayProvider,Router,SUPPLIABLE_TYPES,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapProviderFactory,SwapRouter,SwapRouterRegistry,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRADE_ERROR,TRADING_APPROVALS_METADATA,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UNRESOLVED_ASSET,UP_OR_DOWN_TAG_ID,UpstashKnowledgeBase,UserSwapRouter,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WALLET_DERIVATION,WITHDRAW,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletHistoryTool,WalletLendingPositionsTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustKeyringAgent,ZERO_ADDRESS,adjustBuyAmountForFees,allInBuyNotional,amazonDomainForLanguage,apiClient,applyMarketEvent,applyYieldConversions,bestPrice,buildApprovalCalls,buildApprovals,buildBuilderSignature,buildChallenge,buildRangePresets,buildUniswapPoolUrl,builderApiKey,buyNotional,buyNotionalAfterFee,call,canDeriveV3PoolAddress,ceil2,chains,checkNativeGasAffordable,checksumAddress,clampTick,classifyTradeError,classifyWithdrawError,clearPublicClientCache,coinpoolConfigApi,compareDecimal,completeX402,configureSupportedChains,configureSwapProvider,convertSusdsShares,createAiAgent,createDefaultSubagents,createNfcAgent,createNftAgent,createPolymarketSigner,createPoolUniswapAgent,createPredictionAgent,createPublicClient,createTokenAgent,createTransport,createWalletActionAgent,createWalletAgent,createX402SignatureProvider,decodeAbiParameters,decodeErrorResult,decodeFunctionData,decodeFunctionResult,defiLlamaPoolInfoScope,defiLlamaPoolSupportsLabel,deployDepositWallet,depositPriceImpact,deriveBeaconDepositWallet,deriveDepositWallet,deriveSafeWallet,deriveUupsDepositWallet,deriveV3PoolAddress,displayFromChallenge,effectivePriceUSD,encodeAbiParameters,encodeApprove,encodeErrorResult,encodeFunctionData,encodeSignedHeader,erc1155Abi,erc20Abi,erc20Abi_bytes32,erc721Abi,estimateGas,estimateNativeGasReserveWei,estimateTransactionFeeWei,ethCallAt,ethCallByChain,eventHeadline,eventUrl,evmDepositAssets,exactAmountString,extractOutRaw,extractQuoteError,fallback,feePerShare,feeWeiToNative,fetchOnboardingSnapshot,fetchTopMarketplaces,fetchTradingApprovalsStatus,fetchUnderlyingPricesUSD,findWalletDepositOptions,floor2,floorToDecimals,formatDefiLlamaPool,getAbiItem,getAddress,getBalance,getBlock,getBlockNumber,getCashBalance,getCashBalanceBaseUnits,getChain,getChainContractAddress,getChainId,getChainMeta,getCode,getDefaultRpcUrl,getGasPrice,getNativeTokenInfo,getPolymarketBuilderCode,getPublicClient,getRevertReason,getRpcOverrides,getStorageAt,getTokenPriceUSD,getTransactionCount,http,humanToWei,ingestKnowledgeBase,isAbortError,isAddress,isAddressEqual,isBelowWithdrawMinimum,isEvmAddress,isMarketOpen,isPaymentRequired,isShareBasedProtocol,isShareBasedYieldToken,isSupplyChain,keyringSettingApi,listCandidateChains,listSupplyChains,mapEvent,mapMarket,marketFee,marketProtocol,moneylineMarket,mulDivFloor,multicall,multicall3Abi,multicallRaw,nativeGasShortfall,nfcAmazonSearchUrl,normaliseCountry,normalizeDecimal,normalizeLevels,normalizePriceRangeToPool,normalizeText,onboardingStep,openSecureClient,parseAbi,parseAbiItem,parseAbiParameters,parsePolymarketUrl,parsePredictionHint,pickLogo,placePredictionOrder,planYieldTokenConversions,predictionHint,prepareMarketOrder,priceToTick,protocolLabelFor,psm3For,pusdFromBaseUnits,pusdToBaseUnits,quoteBuyAsPolymarket,quoteBuyUsd,quoteDeposit,quoteMarketOrder,quoteSellShares,quoteWithdrawal,readContract,readPaymentError,readPaymentRequired,readProtocolFeeWei,readReceipt,readSpendableBalance,readTokenUsdPrice,redeemPredictionPositions,registerMaybeNoForm,remoteBuilderSigning,requestWithX402,resolveAccountWallet,resolveCategory,resolveGasLimit,resolveNfcShopLinks,resolveRawYieldAsset,resolveRawYieldIdentity,resolveRawYieldProtocol,resolveRpcUrl,resolveRpcUrls,resolveTokenPriceUSD,roundTickToSpacing,rpcCall,runPolymarketOnboarding,setPolymarketBuilderCode,setRpcOverrides,slippagePrice,spendableNative,swapProviderFactory,swapRouterRegistry,tickToPrice,ticketFee,toBuilderAuthorization,toEventSelector,toFunctionSelector,toPantographChain,toPlainDecimal,unitPriceUSD,upDownWindow,valueYieldTokens,walletDepositAssets,watchCryptoPrice,watchOrderBooks,weiToHuman,withdrawDestinations,withdrawFromPolymarket});
|
|
1544
1541
|
/*! Bundled license information:
|
|
1545
1542
|
|
|
1546
1543
|
@noble/curves/esm/abstract/utils.js:
|