@gardenfi/core 3.0.7 → 3.0.8-beta.3

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.
@@ -0,0 +1,104 @@
1
+ "use strict";var s2=Object.defineProperty;var mp=t=>{throw TypeError(t)};var i2=(t,e,r)=>e in t?s2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var A=(t,e,r)=>i2(t,typeof e!="symbol"?e+"":e,r),bp=(t,e,r)=>e.has(t)||mp("Cannot "+r);var ge=(t,e,r)=>(bp(t,e,"read from private field"),r?r.call(t):e.get(t)),Ur=(t,e,r)=>e.has(t)?mp("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),bs=(t,e,r,n)=>(bp(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);const V=require("@gardenfi/orderbook"),E=require("@gardenfi/utils"),pe=require("bitcoinjs-lib"),o2=require("tiny-secp256k1"),Am=require("varuint-bitcoin"),Ma=require("bitcore-lib-ltc"),Cf=require("bignumber.js"),ic=require("ecpair"),Xe=require("starknet"),mr=require("@coral-xyz/anchor"),a2=require("@solana/spl-token"),gp=require("@mysten/wallet-standard"),wp=require("tronweb"),Cu=require("xrpl"),c2=require("node-cache"),vp=require("yup"),Ep=require("bip39"),u2=require("bip32");function Uc(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Ae=Uc(pe),lr=Uc(o2),Sp=Uc(Am),l2=Uc(a2),f2="1.2.3";let Ht=class Nf extends Error{constructor(e,r={}){var o;const n=r.cause instanceof Nf?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,s=r.cause instanceof Nf&&r.cause.docsPath||r.docsPath,i=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${f2}`].join(`
2
+ `);super(i),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"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=e}};function Cn(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const km=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,xm=/^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)?$/,Tm=/^\(.+?\).*?$/,Ap=/^tuple(?<array>(\[(\d*)\])*)$/;function Rf(t){let e=t.type;if(Ap.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=Rf(i),s<r-1&&(e+=", ")}const n=Cn(Ap,t.type);return e+=`)${(n==null?void 0:n.array)||""}`,Rf({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function ci(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=Rf(s),n!==r-1&&(e+=", ")}return e}function wc(t){var e;return t.type==="function"?`function ${t.name}(${ci(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${ci(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${ci(t.inputs)})`:t.type==="error"?`error ${t.name}(${ci(t.inputs)})`:t.type==="constructor"?`constructor(${ci(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const _m=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function d2(t){return _m.test(t)}function h2(t){return Cn(_m,t)}const Pm=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function p2(t){return Pm.test(t)}function y2(t){return Cn(Pm,t)}const Om=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function m2(t){return Om.test(t)}function b2(t){return Cn(Om,t)}const Im=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Fc(t){return Im.test(t)}function g2(t){return Cn(Im,t)}const Bm=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function w2(t){return Bm.test(t)}function v2(t){return Cn(Bm,t)}const Cm=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function E2(t){return Cm.test(t)}function S2(t){return Cn(Cm,t)}const A2=/^receive\(\) external payable$/;function k2(t){return A2.test(t)}const kp=new Set(["memory","indexed","storage","calldata"]),x2=new Set(["indexed"]),Mf=new Set(["calldata","memory","storage"]);class T2 extends Ht{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class _2 extends Ht{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" 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"})}}class P2 extends Ht{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class O2 extends Ht{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}class I2 extends Ht{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class B2 extends Ht{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" 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"})}}class C2 extends Ht{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class N2 extends Ht{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class R2 extends Ht{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Hi extends Ht{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class M2 extends Ht{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class j2 extends Ht{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class U2 extends Ht{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class F2 extends Ht{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function $2(t,e,r){let n="";if(r)for(const s of Object.entries(r)){if(!s)continue;let i="";for(const o of s[1])i+=`[${o.type}${o.name?`:${o.name}`:""}]`;n+=`(${s[0]}{${i}})`}return e?`${e}:${t}${n}`:`${t}${n}`}const Nu=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 jf(t,e={}){if(m2(t))return L2(t,e);if(p2(t))return D2(t,e);if(d2(t))return H2(t,e);if(w2(t))return z2(t,e);if(E2(t))return V2(t);if(k2(t))return{type:"receive",stateMutability:"payable"};throw new M2({signature:t})}function L2(t,e={}){const r=b2(t);if(!r)throw new Hi({signature:t,type:"function"});const n=Gt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Tn(n[a],{modifiers:Mf,structs:e,type:"function"}));const o=[];if(r.returns){const a=Gt(r.returns),c=a.length;for(let u=0;u<c;u++)o.push(Tn(a[u],{modifiers:Mf,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function D2(t,e={}){const r=y2(t);if(!r)throw new Hi({signature:t,type:"event"});const n=Gt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Tn(n[o],{modifiers:x2,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function H2(t,e={}){const r=h2(t);if(!r)throw new Hi({signature:t,type:"error"});const n=Gt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Tn(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function z2(t,e={}){const r=v2(t);if(!r)throw new Hi({signature:t,type:"constructor"});const n=Gt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Tn(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function V2(t){const e=S2(t);if(!e)throw new Hi({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const G2=/^(?<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$_]*))?$/,q2=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,W2=/^u?int$/;function Tn(t,e){var f,h;const r=$2(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(Nu.has(r))return Nu.get(r);const n=Tm.test(t),s=Cn(n?q2:G2,t);if(!s)throw new I2({param:t});if(s.name&&X2(s.name))throw new B2({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const d=Gt(s.type),p=[],m=d.length;for(let v=0;v<m;v++)p.push(Tn(d[v],{structs:a}));u={components:p}}else if(s.type in a)c="tuple",u={components:a[s.type]};else if(W2.test(s.type))c=`${s.type}256`;else if(s.type==="address payable")c="address";else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!Nm(c))throw new P2({type:c});if(s.modifier){if(!((h=(f=e==null?void 0:e.modifiers)==null?void 0:f.has)!=null&&h.call(f,s.modifier)))throw new C2({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(Mf.has(s.modifier)&&!Y2(c,!!s.array))throw new N2({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const l={type:`${c}${s.array??""}`,...i,...o,...u};return Nu.set(r,l),l}function Gt(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const o=t[i],a=t.slice(i+1);switch(o){case",":return n===0?Gt(a,[...e,r.trim()]):Gt(a,e,`${r}${o}`,n);case"(":return Gt(a,e,`${r}${o}`,n+1);case")":return Gt(a,e,`${r}${o}`,n-1);default:return Gt(a,e,`${r}${o}`,n)}}if(r==="")return e;if(n!==0)throw new F2({current:r,depth:n});return e.push(r.trim()),e}function Nm(t){return t==="address"||t==="bool"||t==="function"||t==="string"||km.test(t)||xm.test(t)}const K2=/^(?: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 X2(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||km.test(t)||xm.test(t)||K2.test(t)}function Y2(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function Dd(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!Fc(a))continue;const c=g2(a);if(!c)throw new Hi({signature:a,type:"struct"});const u=c.properties.split(";"),l=[],f=u.length;for(let h=0;h<f;h++){const p=u[h].trim();if(!p)continue;const m=Tn(p,{type:"struct"});l.push(m)}if(!l.length)throw new j2({signature:a});e[c.name]=l}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=Rm(c,e)}return n}const J2=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Rm(t=[],e={},r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(Tm.test(o.type))n.push(o);else{const c=Cn(J2,o.type);if(!(c!=null&&c.type))throw new R2({abiParameter:o});const{array:u,type:l}=c;if(l in e){if(r.has(l))throw new U2({type:l});n.push({...o,type:`tuple${u??""}`,components:Rm(e[l],e,new Set([...r,l]))})}else if(Nm(l))n.push(o);else throw new _2({type:l})}}return n}function Mm(t){const e=Dd(t),r=[],n=t.length;for(let s=0;s<n;s++){const i=t[s];Fc(i)||r.push(jf(i,e))}return r}function xp(t){let e;if(typeof t=="string")e=jf(t);else{const r=Dd(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(!Fc(i)){e=jf(i,r);break}}}if(!e)throw new T2({signature:t});return e}function Tp(t){const e=[];if(typeof t=="string"){const r=Gt(t),n=r.length;for(let s=0;s<n;s++)e.push(Tn(r[s],{modifiers:kp}))}else{const r=Dd(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(Fc(i))continue;const o=Gt(i),a=o.length;for(let c=0;c<a;c++)e.push(Tn(o[c],{modifiers:kp,structs:r}))}}if(e.length===0)throw new O2({params:t});return e}function ne(t,e,r){const n=t[e.name];if(typeof n=="function")return n;const s=t[r];return typeof s=="function"?s:i=>e(t,i)}function Tr(t,{includeName:e=!1}={}){if(t.type!=="function"&&t.type!=="event"&&t.type!=="error")throw new f6(t.type);return`${t.name}(${$c(t.inputs,{includeName:e})})`}function $c(t,{includeName:e=!1}={}){return t?t.map(r=>Z2(r,{includeName:e})).join(e?", ":","):""}function Z2(t,{includeName:e}){return t.type.startsWith("tuple")?`(${$c(t.components,{includeName:e})})${t.type.slice(5)}`:t.type+(e&&t.name?` ${t.name}`:"")}function _r(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function He(t){return _r(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const jm="2.43.3";let Qi={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${jm}`},q=class Uf extends Error{constructor(e,r={}){var a;const n=(()=>{var c;return r.cause instanceof Uf?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof Uf&&r.cause.docsPath||r.docsPath,i=(a=Qi.getDocsUrl)==null?void 0:a.call(Qi,{...r,docsPath:s}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...Qi.version?[`Version: ${Qi.version}`]:[]].join(`
3
+ `);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=jm}walk(e){return Um(this,e)}};function Um(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Um(t.cause,e):e?null:t}class Q2 extends q{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
4
+ `),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class _p extends q{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
5
+ `),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class Fm extends q{constructor({data:e,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
6
+ `),{metaMessages:[`Params: (${$c(r,{includeName:!0})})`,`Data: ${e} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=r,this.size=n}}class fa extends q{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class e6 extends q{constructor({expectedLength:e,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${r}`].join(`
7
+ `),{name:"AbiEncodingArrayLengthMismatchError"})}}class t6 extends q{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${He(r)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class r6 extends q{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${r}`].join(`
8
+ `),{name:"AbiEncodingLengthMismatchError"})}}class n6 extends q{constructor(e,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${e}", but "${e}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
9
+ `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}}class Pp extends q{constructor(e,{docsPath:r}={}){super([`Error ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
10
+ `),{docsPath:r,name:"AbiErrorNotFoundError"})}}class $m extends q{constructor(e,{docsPath:r}){super([`Encoded error signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
11
+ `),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class s6 extends q{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class i6 extends q{constructor(e,{docsPath:r}){super([`Encoded event signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
12
+ `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class Op extends q{constructor(e,{docsPath:r}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
13
+ `),{docsPath:r,name:"AbiEventNotFoundError"})}}class Ii extends q{constructor(e,{docsPath:r}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
14
+ `),{docsPath:r,name:"AbiFunctionNotFoundError"})}}class Lm extends q{constructor(e,{docsPath:r}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
15
+ `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}}class o6 extends q{constructor(e,{docsPath:r}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
16
+ `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class a6 extends q{constructor(e,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${Tr(e.abiItem)}\`, and`,`\`${r.type}\` in \`${Tr(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}let c6=class extends q{constructor({expectedSize:e,givenSize:r}){super(`Expected bytes${e}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};class vc extends q{constructor({abiItem:e,data:r,params:n,size:s}){super([`Data size of ${s} bytes is too small for non-indexed event parameters.`].join(`
17
+ `),{metaMessages:[`Params: (${$c(n,{includeName:!0})})`,`Data: ${r} (${s} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e,this.data=r,this.params=n,this.size=s}}class Hd extends q{constructor({abiItem:e,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${Tr(e,{includeName:!0})}".`].join(`
18
+ `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}class u6 extends q{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
19
+ `),{docsPath:r,name:"InvalidAbiEncodingType"})}}class l6 extends q{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
20
+ `),{docsPath:r,name:"InvalidAbiDecodingType"})}}let Dm=class extends q{constructor(e){super([`Value "${e}" is not a valid array.`].join(`
21
+ `),{name:"InvalidArrayError"})}};class f6 extends q{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
22
+ `),{name:"InvalidDefinitionTypeError"})}}class d6 extends q{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let Hm=class extends q{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},zm=class extends q{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class Ip extends q{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function zi(t,{dir:e,size:r=32}={}){return typeof t=="string"?ts(t,{dir:e,size:r}):h6(t,{dir:e,size:r})}function ts(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new zm({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function h6(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new zm({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const i=e==="right";n[i?s:r-s-1]=t[i?s:t.length-s-1]}return n}let Vm=class extends q{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},p6=class extends q{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};class y6 extends q{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let m6=class extends q{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function fr(t,{dir:e="left"}={}){let r=typeof t=="string"?t.replace("0x",""):t,n=0;for(let s=0;s<r.length-1&&r[e==="left"?s:r.length-s-1].toString()==="0";s++)n++;return r=e==="left"?r.slice(n):r.slice(0,r.length-n),typeof t=="string"?(r.length===1&&e==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function Cr(t,{size:e}){if(He(t)>e)throw new m6({givenSize:He(t),maxSize:e})}function ot(t,e={}){const{signed:r}=e;e.size&&Cr(t,{size:e.size});const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function b6(t,e={}){let r=t;if(e.size&&(Cr(r,{size:e.size}),r=fr(r)),fr(r)==="0x00")return!1;if(fr(r)==="0x01")return!0;throw new y6(r)}function dr(t,e={}){return Number(ot(t,e))}const g6=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ot(t,e={}){return typeof t=="number"||typeof t=="bigint"?J(t,e):typeof t=="string"?Bi(t,e):typeof t=="boolean"?Gm(t,e):Je(t,e)}function Gm(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Cr(r,{size:e.size}),zi(r,{size:e.size})):r}function Je(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=g6[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Cr(n,{size:e.size}),zi(n,{dir:"right",size:e.size})):n}function J(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const c=typeof t=="bigint"?"n":"";throw new Vm({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${t}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?zi(a,{size:n}):a}const w6=new TextEncoder;function Bi(t,e={}){const r=w6.encode(t);return Je(r,e)}const v6=new TextEncoder;function Vi(t,e={}){return typeof t=="number"||typeof t=="bigint"?S6(t,e):typeof t=="boolean"?E6(t,e):_r(t)?en(t,e):Is(t,e)}function E6(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(Cr(r,{size:e.size}),zi(r,{size:e.size})):r}const nn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Bp(t){if(t>=nn.zero&&t<=nn.nine)return t-nn.zero;if(t>=nn.A&&t<=nn.F)return t-(nn.A-10);if(t>=nn.a&&t<=nn.f)return t-(nn.a-10)}function en(t,e={}){let r=t;e.size&&(Cr(r,{size:e.size}),r=zi(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,i=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=Bp(n.charCodeAt(a++)),u=Bp(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new q(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+u}return i}function S6(t,e){const r=J(t,e);return en(r)}function Is(t,e={}){const r=v6.encode(t);return typeof e.size=="number"?(Cr(r,{size:e.size}),zi(r,{dir:"right",size:e.size})):r}const ja=BigInt(2**32-1),Cp=BigInt(32);function qm(t,e=!1){return e?{h:Number(t&ja),l:Number(t>>Cp&ja)}:{h:Number(t>>Cp&ja)|0,l:Number(t&ja)|0}}function A6(t,e=!1){const r=t.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=qm(t[i],e);[n[i],s[i]]=[o,a]}return[n,s]}const Wm=(t,e,r)=>t>>>r|e<<32-r,Km=(t,e,r)=>t<<32-r|e>>>r,k6=(t,e,r)=>t<<64-r|e>>>r-32,x6=(t,e,r)=>t>>>r-32|e<<64-r,T6=(t,e)=>e,_6=(t,e)=>t,P6=(t,e,r)=>t<<r|e>>>32-r,O6=(t,e,r)=>e<<r|t>>>32-r,I6=(t,e,r)=>e<<r-32|t>>>64-r,B6=(t,e,r)=>t<<r-32|e>>>64-r;function Xm(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const Ym=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Jm=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,si=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function C6(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ss(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function is(t,...e){if(!C6(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function N6(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ss(t.outputLen),ss(t.blockLen)}function os(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function zd(t,e){is(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Oo(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Pr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ru(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Fr(t,e){return t<<32-e|t>>>e}function Ua(t,e){return t<<e|t>>>32-e>>>0}const Zm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Qm(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const pn=Zm?t=>t:t=>Qm(t);function R6(t){for(let e=0;e<t.length;e++)t[e]=Qm(t[e]);return t}const Kn=Zm?t=>t:R6;function M6(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Sn(t){return typeof t=="string"&&(t=M6(t)),is(t),t}function j6(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];is(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}class Lc{}function Dc(t){const e=n=>t().update(Sn(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function U6(t){const e=(n,s)=>t(s).update(Sn(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function F6(t=32){if(si&&typeof si.getRandomValues=="function")return si.getRandomValues(new Uint8Array(t));if(si&&typeof si.randomBytes=="function")return Uint8Array.from(si.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const $6=BigInt(0),eo=BigInt(1),L6=BigInt(2),D6=BigInt(7),H6=BigInt(256),z6=BigInt(113),eb=[],tb=[],rb=[];for(let t=0,e=eo,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],eb.push(2*(5*n+r)),tb.push((t+1)*(t+2)/2%64);let s=$6;for(let i=0;i<7;i++)e=(e<<eo^(e>>D6)*z6)%H6,e&L6&&(s^=eo<<(eo<<BigInt(i))-eo);rb.push(s)}const nb=A6(rb,!0),V6=nb[0],G6=nb[1],Np=(t,e,r)=>r>32?I6(t,e,r):P6(t,e,r),Rp=(t,e,r)=>r>32?B6(t,e,r):O6(t,e,r);function q6(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],f=Np(u,l,1)^r[a],h=Rp(u,l,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=f,t[o+d+1]^=h}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=tb[o],c=Np(s,i,a),u=Rp(s,i,a),l=eb[o];s=t[l],i=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=V6[n],t[1]^=G6[n]}Pr(r)}class Vd extends Lc{constructor(e,r,n,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=s,this.rounds=i,ss(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Oo(this.state)}clone(){return this._cloneInto()}keccak(){Kn(this.state32),q6(this.state32,this.rounds),Kn(this.state32),this.posOut=0,this.pos=0}update(e){os(this),e=Sn(e),is(e);const{blockLen:r,state:n}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:s}=this;e[n]^=r,r&128&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){os(this,!1),is(e),this.finish();const r=this.state,{blockLen:n}=this;for(let s=0,i=e.length;s<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ss(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(zd(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Pr(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Vd(r,n,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const W6=(t,e,r)=>Dc(()=>new Vd(e,t,r)),sb=W6(1,136,256/8);function dt(t,e){const r=e||"hex",n=sb(_r(t,{strict:!1})?Vi(t):t);return r==="bytes"?n:Ot(n)}const K6=t=>dt(Vi(t));function X6(t){return K6(t)}function Y6(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new q("Unable to normalize signature.");return s}const J6=t=>{const e=typeof t=="string"?t:wc(t);return Y6(e)};function ib(t){return X6(J6(t))}const Hc=ib;let Bt=class extends q{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},Gi=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const Mu=new Gi(8192);function da(t,e){if(Mu.has(`${t}.${e}`))return Mu.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=dt(Is(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(n[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const i=`0x${s.join("")}`;return Mu.set(`${t}.${e}`,i),i}function Gd(t,e){if(!st(t,{strict:!1}))throw new Bt({address:t});return da(t,e)}const Z6=/^0x[a-fA-F0-9]{40}$/,ju=new Gi(8192);function st(t,e){const{strict:r=!0}=e??{},n=`${t}.${r}`;if(ju.has(n))return ju.get(n);const s=Z6.test(t)?t.toLowerCase()===t?!0:r?da(t)===t:!0:!1;return ju.set(n,s),s}function Jt(t){return typeof t[0]=="string"?Nr(t):Q6(t)}function Q6(t){let e=0;for(const s of t)e+=s.length;const r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function Nr(t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Fs(t,e,r,{strict:n}={}){return _r(t,{strict:!1})?Ff(t,e,r,{strict:n}):cb(t,e,r,{strict:n})}function ob(t,e){if(typeof e=="number"&&e>0&&e>He(t)-1)throw new Hm({offset:e,position:"start",size:He(t)})}function ab(t,e,r){if(typeof e=="number"&&typeof r=="number"&&He(t)!==r-e)throw new Hm({offset:r,position:"end",size:He(t)})}function cb(t,e,r,{strict:n}={}){ob(t,e);const s=t.slice(e,r);return n&&ab(s,e,r),s}function Ff(t,e,r,{strict:n}={}){ob(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&ab(s,e,r),s}const e5=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,ub=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function fs(t,e){if(t.length!==e.length)throw new r6({expectedLength:t.length,givenLength:e.length});const r=t5({params:t,values:e}),n=Wd(r);return n.length===0?"0x":n}function t5({params:t,values:e}){const r=[];for(let n=0;n<t.length;n++)r.push(qd({param:t[n],value:e[n]}));return r}function qd({param:t,value:e}){const r=Kd(t.type);if(r){const[n,s]=r;return n5(e,{length:n,param:{...t,type:s}})}if(t.type==="tuple")return c5(e,{param:t});if(t.type==="address")return r5(e);if(t.type==="bool")return i5(e);if(t.type.startsWith("uint")||t.type.startsWith("int")){const n=t.type.startsWith("int"),[,,s="256"]=ub.exec(t.type)??[];return o5(e,{signed:n,size:Number(s)})}if(t.type.startsWith("bytes"))return s5(e,{param:t});if(t.type==="string")return a5(e);throw new u6(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function Wd(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=He(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(J(e+s,{size:32})),n.push(a),s+=He(a)):r.push(a)}return Jt([...r,...n])}function r5(t){if(!st(t))throw new Bt({address:t});return{dynamic:!1,encoded:ts(t.toLowerCase())}}function n5(t,{length:e,param:r}){const n=e===null;if(!Array.isArray(t))throw new Dm(t);if(!n&&t.length!==e)throw new e6({expectedLength:e,givenLength:t.length,type:`${r.type}[${e}]`});let s=!1;const i=[];for(let o=0;o<t.length;o++){const a=qd({param:r,value:t[o]});a.dynamic&&(s=!0),i.push(a)}if(n||s){const o=Wd(i);if(n){const a=J(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?Jt([a,o]):a}}if(s)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:Jt(i.map(({encoded:o})=>o))}}function s5(t,{param:e}){const[,r]=e.type.split("bytes"),n=He(t);if(!r){let s=t;return n%32!==0&&(s=ts(s,{dir:"right",size:Math.ceil((t.length-2)/2/32)*32})),{dynamic:!0,encoded:Jt([ts(J(n,{size:32})),s])}}if(n!==Number.parseInt(r,10))throw new t6({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:ts(t,{dir:"right"})}}function i5(t){if(typeof t!="boolean")throw new q(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:ts(Gm(t))}}function o5(t,{signed:e,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new Vm({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:J(t,{size:32,signed:e})}}function a5(t){const e=Bi(t),r=Math.ceil(He(e)/32),n=[];for(let s=0;s<r;s++)n.push(ts(Fs(e,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Jt([ts(J(He(e),{size:32})),...n])}}function c5(t,{param:e}){let r=!1;const n=[];for(let s=0;s<e.components.length;s++){const i=e.components[s],o=Array.isArray(t)?s:i.name,a=qd({param:i,value:t[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?Wd(n):Jt(n.map(({encoded:s})=>s))}}function Kd(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}const ha=t=>Fs(ib(t),0,4);function Ys(t){const{abi:e,args:r=[],name:n}=t,s=_r(n,{strict:!1}),i=e.filter(a=>s?a.type==="function"?ha(a)===n:a.type==="event"?Hc(a)===n:!1:"name"in a&&a.name===n);if(i.length===0)return;if(i.length===1)return i[0];let o;for(const a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((u,l)=>{const f="inputs"in a&&a.inputs[l];return f?$f(u,f):!1})){if(o&&"inputs"in o&&o.inputs){const u=lb(a.inputs,o.inputs,r);if(u)throw new a6({abiItem:a,type:u[0]},{abiItem:o,type:u[1]})}o=a}}return o||i[0]}function $f(t,e){const r=typeof t,n=e.type;switch(n){case"address":return st(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>$f(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>$f(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function lb(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return lb(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?st(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?st(r[n],{strict:!1}):!1)return o}}const Mp="/docs/contract/encodeEventTopics";function pa(t){var c;const{abi:e,eventName:r,args:n}=t;let s=e[0];if(r){const u=Ys({abi:e,name:r});if(!u)throw new Op(r,{docsPath:Mp});s=u}if(s.type!=="event")throw new Op(void 0,{docsPath:Mp});const i=Tr(s),o=Hc(i);let a=[];if(n&&"inputs"in s){const u=(c=s.inputs)==null?void 0:c.filter(f=>"indexed"in f&&f.indexed),l=Array.isArray(n)?n:Object.values(n).length>0?(u==null?void 0:u.map(f=>n[f.name]))??[]:[];l.length>0&&(a=(u==null?void 0:u.map((f,h)=>Array.isArray(l[h])?l[h].map((d,p)=>jp({param:f,value:l[h][p]})):typeof l[h]<"u"&&l[h]!==null?jp({param:f,value:l[h]}):null))??[])}return[o,...a]}function jp({param:t,value:e}){if(t.type==="string"||t.type==="bytes")return dt(Vi(e));if(t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/))throw new d6(t.type);return fs([t],[e])}function zc(t,{method:e}){var n,s;const r={};return t.transport.type==="fallback"&&((s=(n=t.transport).onResponse)==null||s.call(n,({method:i,response:o,status:a,transport:c})=>{a==="success"&&e===i&&(r[o]=c.request)})),i=>r[i]||t.request}async function Xd(t,e){const{address:r,abi:n,args:s,eventName:i,fromBlock:o,strict:a,toBlock:c}=e,u=zc(t,{method:"eth_newFilter"}),l=i?pa({abi:n,args:s,eventName:i}):void 0,f=await t.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?J(o):o,toBlock:typeof c=="bigint"?J(c):c,topics:l}]});return{abi:n,args:s,eventName:i,id:f,request:u(f),strict:!!a,type:"event"}}function Fe(t){return typeof t=="string"?{address:t,type:"json-rpc"}:t}const Up="/docs/contract/encodeFunctionData";function u5(t){const{abi:e,args:r,functionName:n}=t;let s=e[0];if(n){const i=Ys({abi:e,args:r,name:n});if(!i)throw new Ii(n,{docsPath:Up});s=i}if(s.type!=="function")throw new Ii(void 0,{docsPath:Up});return{abi:[s],functionName:ha(Tr(s))}}function er(t){const{args:e}=t,{abi:r,functionName:n}=(()=>{var a;return t.abi.length===1&&((a=t.functionName)!=null&&a.startsWith("0x"))?t:u5(t)})(),s=r[0],i=n,o="inputs"in s&&s.inputs?fs(s.inputs,e??[]):void 0;return Nr([i,o??"0x"])}const l5={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},fb={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},f5={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};let Fp=class extends q{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}},db=class extends q{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}},d5=class extends q{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}};const h5={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 d5({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new db({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new Fp({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new Fp({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function Yd(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(h5);return r.bytes=t,r.dataView=new DataView(t.buffer??t,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}function p5(t,e={}){typeof e.size<"u"&&Cr(t,{size:e.size});const r=Je(t,e);return ot(r,e)}function y5(t,e={}){let r=t;if(typeof e.size<"u"&&(Cr(r,{size:e.size}),r=fr(r)),r.length>1||r[0]>1)throw new p6(r);return!!r[0]}function An(t,e={}){typeof e.size<"u"&&Cr(t,{size:e.size});const r=Je(t,e);return dr(r,e)}function m5(t,e={}){let r=t;return typeof e.size<"u"&&(Cr(r,{size:e.size}),r=fr(r,{dir:"right"})),new TextDecoder().decode(r)}function ya(t,e){const r=typeof e=="string"?en(e):e,n=Yd(r);if(He(r)===0&&t.length>0)throw new fa;if(He(e)&&He(e)<32)throw new Fm({data:typeof e=="string"?e:Je(e),params:t,size:He(e)});let s=0;const i=[];for(let o=0;o<t.length;++o){const a=t[o];n.setPosition(s);const[c,u]=wi(n,a,{staticPosition:0});s+=u,i.push(c)}return i}function wi(t,e,{staticPosition:r}){const n=Kd(e.type);if(n){const[s,i]=n;return g5(t,{...e,type:i},{length:s,staticPosition:r})}if(e.type==="tuple")return S5(t,e,{staticPosition:r});if(e.type==="address")return b5(t);if(e.type==="bool")return w5(t);if(e.type.startsWith("bytes"))return v5(t,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return E5(t,e);if(e.type==="string")return A5(t,{staticPosition:r});throw new l6(e.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const $p=32,Lf=32;function b5(t){const e=t.readBytes(32);return[da(Je(cb(e,-20))),32]}function g5(t,e,{length:r,staticPosition:n}){if(!r){const o=An(t.readBytes(Lf)),a=n+o,c=a+$p;t.setPosition(a);const u=An(t.readBytes($p)),l=Io(e);let f=0;const h=[];for(let d=0;d<u;++d){t.setPosition(c+(l?d*32:f));const[p,m]=wi(t,e,{staticPosition:c});f+=m,h.push(p)}return t.setPosition(n+32),[h,32]}if(Io(e)){const o=An(t.readBytes(Lf)),a=n+o,c=[];for(let u=0;u<r;++u){t.setPosition(a+u*32);const[l]=wi(t,e,{staticPosition:a});c.push(l)}return t.setPosition(n+32),[c,32]}let s=0;const i=[];for(let o=0;o<r;++o){const[a,c]=wi(t,e,{staticPosition:n+s});s+=c,i.push(a)}return[i,s]}function w5(t){return[y5(t.readBytes(32),{size:32}),32]}function v5(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const o=An(t.readBytes(32));t.setPosition(r+o);const a=An(t.readBytes(32));if(a===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(a);return t.setPosition(r+32),[Je(c),32]}return[Je(t.readBytes(Number.parseInt(s,10),32)),32]}function E5(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?p5(s,{signed:r}):An(s,{signed:r}),32]}function S5(t,e,{staticPosition:r}){const n=e.components.length===0||e.components.some(({name:o})=>!o),s=n?[]:{};let i=0;if(Io(e)){const o=An(t.readBytes(Lf)),a=r+o;for(let c=0;c<e.components.length;++c){const u=e.components[c];t.setPosition(a+i);const[l,f]=wi(t,u,{staticPosition:a});i+=f,s[n?c:u==null?void 0:u.name]=l}return t.setPosition(r+32),[s,32]}for(let o=0;o<e.components.length;++o){const a=e.components[o],[c,u]=wi(t,a,{staticPosition:r});s[n?o:a==null?void 0:a.name]=c,i+=u}return[s,i]}function A5(t,{staticPosition:e}){const r=An(t.readBytes(32)),n=e+r;t.setPosition(n);const s=An(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),o=m5(fr(i));return t.setPosition(e+32),[o,32]}function Io(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(Io);const r=Kd(t.type);return!!(r&&Io({...t,type:r[1]}))}function hb(t){const{abi:e,data:r}=t,n=Fs(r,0,4);if(n==="0x")throw new fa;const i=[...e||[],fb,f5].find(o=>o.type==="error"&&n===ha(Tr(o)));if(!i)throw new $m(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?ya(i.inputs,Fs(r,4)):void 0,errorName:i.name}}const Ye=(t,e,r)=>JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString():s,r);function pb({abiItem:t,args:e,includeFunctionName:r=!0,includeName:n=!1}){if("name"in t&&"inputs"in t&&t.inputs)return`${r?t.name:""}(${t.inputs.map((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof e[i]=="object"?Ye(e[i]):e[i]}`).join(", ")})`}const k5={gwei:9,wei:18},x5={ether:-9,wei:9};function yb(t,e){let r=t.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(e,"0");let[s,i]=[r.slice(0,r.length-e),r.slice(r.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${s||"0"}${i?`.${i}`:""}`}function Jd(t,e="wei"){return yb(t,k5[e])}function $t(t,e="wei"){return yb(t,x5[e])}class T5 extends q{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class _5 extends q{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Lp(t){return t.reduce((e,{slot:r,value:n})=>`${e} ${r}: ${n}
23
+ `,"")}function P5(t){return t.reduce((e,{address:r,...n})=>{let s=`${e} ${r}:
24
+ `;return n.nonce&&(s+=` nonce: ${n.nonce}
25
+ `),n.balance&&(s+=` balance: ${n.balance}
26
+ `),n.code&&(s+=` code: ${n.code}
27
+ `),n.state&&(s+=` state:
28
+ `,s+=Lp(n.state)),n.stateDiff&&(s+=` stateDiff:
29
+ `,s+=Lp(n.stateDiff)),s},` State Override:
30
+ `).slice(0,-1)}function ma(t){const e=Object.entries(t).map(([n,s])=>s===void 0||s===!1?null:[n,s]).filter(Boolean),r=e.reduce((n,[s])=>Math.max(n,s.length),0);return e.map(([n,s])=>` ${`${n}:`.padEnd(r+1)} ${s}`).join(`
31
+ `)}class O5 extends q{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class I5 extends q{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",ma(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class B5 extends q{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class C5 extends q{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:h}){var p;const d=ma({chain:s&&`${s==null?void 0:s.name} (id: ${s==null?void 0:s.id})`,from:r==null?void 0:r.address,to:f,value:typeof h<"u"&&`${Jd(h)} ${((p=s==null?void 0:s.nativeCurrency)==null?void 0:p.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${$t(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${$t(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${$t(u)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",d].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class mb extends q{constructor({blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){let o="Transaction";n&&i!==void 0&&(o=`Transaction at block time "${n}" at index "${i}"`),e&&i!==void 0&&(o=`Transaction at block hash "${e}" at index "${i}"`),r&&i!==void 0&&(o=`Transaction at block number "${r}" at index "${i}"`),s&&(o=`Transaction with hash "${s}"`),super(`${o} could not be found.`,{name:"TransactionNotFoundError"})}}class bb extends q{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class gb extends q{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class N5 extends q{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const R5=t=>t,Vc=t=>t;class wb extends q{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:h,stateOverride:d}){var v;const p=r?Fe(r):void 0;let m=ma({from:p==null?void 0:p.address,to:f,value:typeof h<"u"&&`${Jd(h)} ${((v=s==null?void 0:s.nativeCurrency)==null?void 0:v.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${$t(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${$t(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${$t(u)} gwei`,nonce:l});d&&(m+=`
32
+ ${P5(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",m].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class vb extends q{constructor(e,{abi:r,args:n,contractAddress:s,docsPath:i,functionName:o,sender:a}){const c=Ys({abi:r,args:n,name:o}),u=c?pb({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,l=c?Tr(c,{includeName:!0}):void 0,f=ma({address:s&&R5(s),function:l,args:u&&u!=="()"&&`${[...Array((o==null?void 0:o.length)??0).keys()].map(()=>" ").join("")}${u}`,sender:a});super(e.shortMessage||`An unknown error occurred while executing the contract function "${o}".`,{cause:e,docsPath:i,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],f&&"Contract Call:",f].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=e,this.contractAddress=s,this.functionName=o,this.sender=a}}class Df extends q{constructor({abi:e,data:r,functionName:n,message:s}){let i,o,a,c;if(r&&r!=="0x")try{o=hb({abi:e,data:r});const{abiItem:l,errorName:f,args:h}=o;if(f==="Error")c=h[0];else if(f==="Panic"){const[d]=h;c=l5[d]}else{const d=l?Tr(l,{includeName:!0}):void 0,p=l&&h?pb({abiItem:l,args:h,includeFunctionName:!1,includeName:!1}):void 0;a=[d?`Error: ${d}`:"",p&&p!=="()"?` ${[...Array((f==null?void 0:f.length)??0).keys()].map(()=>" ").join("")}${p}`:""]}}catch(l){i=l}else s&&(c=s);let u;i instanceof $m&&(u=i.signature,a=[`Unable to decode signature "${u}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${u}.`]),super(c&&c!=="execution reverted"||u?[`The contract function "${n}" reverted with the following ${u?"signature":"reason"}:`,c||u].join(`
33
+ `):`The contract function "${n}" reverted.`,{cause:i,metaMessages:a,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=o,this.raw=r,this.reason=c,this.signature=u}}class M5 extends q{constructor({functionName:e}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class j5 extends q{constructor({factory:e}){super(`Deployment for counterfactual contract call failed${e?` for factory "${e}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class Gc extends q{constructor({data:e,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}class vi extends q{constructor({body:e,cause:r,details:n,headers:s,status:i,url:o}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${Vc(o)}`,e&&`Request body: ${Ye(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=s,this.status=i,this.url=o}}class Zd extends q{constructor({body:e,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${Vc(n)}`,`Request body: ${Ye(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.url=n}}class Dp extends q{constructor({body:e,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Vc(r)}`,`Request body: ${Ye(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}}const U5=-1;class zt extends q{constructor(e,{code:r,docsPath:n,metaMessages:s,name:i,shortMessage:o}){super(o,{cause:e,docsPath:n,metaMessages:s||(e==null?void 0:e.metaMessages),name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof Zd?e.code:r??U5}}class tr extends zt{constructor(e,r){super(e,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class Bo extends zt{constructor(e){super(e,{code:Bo.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Co extends zt{constructor(e){super(e,{code:Co.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Co,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class No extends zt{constructor(e,{method:r}={}){super(e,{code:No.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(No,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Ro extends zt{constructor(e){super(e,{code:Ro.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
34
+ `)})}}Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class $s extends zt{constructor(e){super(e,{code:$s.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty($s,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class as extends zt{constructor(e){super(e,{code:as.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
35
+ `)})}}Object.defineProperty(as,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Mo extends zt{constructor(e){super(e,{code:Mo.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Mo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class jo extends zt{constructor(e){super(e,{code:jo.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(jo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Uo extends zt{constructor(e){super(e,{code:Uo.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Uo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class As extends zt{constructor(e,{method:r}={}){super(e,{code:As.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(As,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Ci extends zt{constructor(e){super(e,{code:Ci.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Fo extends zt{constructor(e){super(e,{code:Fo.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Fo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Ei extends tr{constructor(e){super(e,{code:Ei.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Ei,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class $o extends tr{constructor(e){super(e,{code:$o.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty($o,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Lo extends tr{constructor(e,{method:r}={}){super(e,{code:Lo.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Lo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Do extends tr{constructor(e){super(e,{code:Do.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Do,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Ho extends tr{constructor(e){super(e,{code:Ho.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Ho,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class zo extends tr{constructor(e){super(e,{code:zo.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(zo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class Ni extends tr{constructor(e){super(e,{code:Ni.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(Ni,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Vo extends tr{constructor(e){super(e,{code:Vo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Vo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class Go extends tr{constructor(e){super(e,{code:Go.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(Go,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class qo extends tr{constructor(e){super(e,{code:qo.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(qo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class Wo extends tr{constructor(e){super(e,{code:Wo.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(Wo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Ko extends tr{constructor(e){super(e,{code:Ko.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Ri extends tr{constructor(e){super(e,{code:Ri.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class F5 extends zt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const $5=3;function Ls(t,{abi:e,address:r,args:n,docsPath:s,functionName:i,sender:o}){const a=t instanceof Gc?t:t instanceof q?t.walk(p=>"data"in p)||t.walk():{},{code:c,data:u,details:l,message:f,shortMessage:h}=a,d=t instanceof fa?new M5({functionName:i}):[$5,$s.code].includes(c)&&(u||l||f||h)||c===as.code&&l==="execution reverted"&&u?new Df({abi:e,data:typeof u=="object"?u.data:u,functionName:i,message:a instanceof Zd?l:h??f}):t;return new vb(d,{abi:e,args:n,contractAddress:r,docsPath:s,functionName:i,sender:o})}function L5(t){const e=dt(`0x${t.substring(4)}`).substring(26);return da(`0x${e}`)}async function D5({hash:t,signature:e}){const r=_r(t)?t:Ot(t),{secp256k1:n}=await Promise.resolve().then(()=>Bk);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:f,yParity:h}=e,d=Number(h??f),p=Hp(d);return new n.Signature(ot(u),ot(l)).addRecoveryBit(p)}const o=_r(e)?e:Ot(e);if(He(o)!==65)throw new Error("invalid signature length");const a=dr(`0x${o.slice(130)}`),c=Hp(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Hp(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Eb({hash:t,signature:e}){return L5(await D5({hash:t,signature:e}))}function cs(t,e="hex"){const r=Sb(t),n=Yd(new Uint8Array(r.length));return r.encode(n),e==="hex"?Je(n.bytes):n.bytes}function Sb(t){return Array.isArray(t)?H5(t.map(e=>Sb(e))):z5(t)}function H5(t){const e=t.reduce((s,i)=>s+i.length,0),r=Ab(e);return{length:e<=55?1+e:1+r+e,encode(s){e<=55?s.pushByte(192+e):(s.pushByte(247+r),r===1?s.pushUint8(e):r===2?s.pushUint16(e):r===3?s.pushUint24(e):s.pushUint32(e));for(const{encode:i}of t)i(s)}}}function z5(t){const e=typeof t=="string"?en(t):t,r=Ab(e.length);return{length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+r+e.length,encode(s){e.length===1&&e[0]<128?s.pushBytes(e):e.length<=55?(s.pushByte(128+e.length),s.pushBytes(e)):(s.pushByte(183+r),r===1?s.pushUint8(e.length):r===2?s.pushUint16(e.length):r===3?s.pushUint24(e.length):s.pushUint32(e.length),s.pushBytes(e))}}}function Ab(t){if(t<2**8)return 1;if(t<2**16)return 2;if(t<2**24)return 3;if(t<2**32)return 4;throw new q("Length is too large.")}function V5(t){const{chainId:e,nonce:r,to:n}=t,s=t.contractAddress??t.address,i=dt(Nr(["0x05",cs([e?J(e):"0x",s,r?J(r):"0x"])]));return n==="bytes"?en(i):i}async function qc(t){const{authorization:e,signature:r}=t;return Eb({hash:V5(e),signature:r??e})}class G5 extends q{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:h}){var p;const d=ma({from:r==null?void 0:r.address,to:f,value:typeof h<"u"&&`${Jd(h)} ${((p=s==null?void 0:s.nativeCurrency)==null?void 0:p.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${$t(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${$t(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${$t(u)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",d].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class mi extends q{constructor({cause:e,message:r}={}){var s;const n=(s=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:s.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(mi,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(mi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});class Ds extends q{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${$t(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(Ds,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class Hf extends q{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${$t(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(Hf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class zf extends q{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(zf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class Vf extends q{constructor({cause:e,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
36
+ `),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(Vf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class Gf extends q{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(Gf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class qf extends q{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
37
+ `),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(qf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class Wf extends q{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(Wf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Kf extends q{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(Kf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class Xf extends q{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(Xf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Xo extends q{constructor({cause:e,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${$t(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${$t(n)} gwei`:""}).`].join(`
38
+ `),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(Xo,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class ba extends q{constructor({cause:e}){super(`An error occurred while executing: ${e==null?void 0:e.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function Wc(t,e){const r=(t.details||"").toLowerCase(),n=t instanceof q?t.walk(s=>(s==null?void 0:s.code)===mi.code):t;return n instanceof q?new mi({cause:t,message:n.details}):mi.nodeMessage.test(r)?new mi({cause:t,message:t.details}):Ds.nodeMessage.test(r)?new Ds({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):Hf.nodeMessage.test(r)?new Hf({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):zf.nodeMessage.test(r)?new zf({cause:t,nonce:e==null?void 0:e.nonce}):Vf.nodeMessage.test(r)?new Vf({cause:t,nonce:e==null?void 0:e.nonce}):Gf.nodeMessage.test(r)?new Gf({cause:t,nonce:e==null?void 0:e.nonce}):qf.nodeMessage.test(r)?new qf({cause:t}):Wf.nodeMessage.test(r)?new Wf({cause:t,gas:e==null?void 0:e.gas}):Kf.nodeMessage.test(r)?new Kf({cause:t,gas:e==null?void 0:e.gas}):Xf.nodeMessage.test(r)?new Xf({cause:t}):Xo.nodeMessage.test(r)?new Xo({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas,maxPriorityFeePerGas:e==null?void 0:e.maxPriorityFeePerGas}):new ba({cause:t})}function q5(t,{docsPath:e,...r}){const n=(()=>{const s=Wc(t,r);return s instanceof ba?t:s})();return new G5(n,{docsPath:e,...r})}function qi(t,{format:e}){if(!e)return{};const r={};function n(i){const o=Object.keys(i);for(const a of o)a in t&&(r[a]=t[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&n(i[a])}const s=e(t||{});return n(s),r}function Qd(t,e){return({exclude:r,format:n})=>({exclude:r,format:(s,i)=>{const o=e(s,i);if(r)for(const a of r)delete o[a];return{...o,...n(s,i)}},type:t})}const W5={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function ds(t,e){const r={};return typeof t.authorizationList<"u"&&(r.authorizationList=K5(t.authorizationList)),typeof t.accessList<"u"&&(r.accessList=t.accessList),typeof t.blobVersionedHashes<"u"&&(r.blobVersionedHashes=t.blobVersionedHashes),typeof t.blobs<"u"&&(typeof t.blobs[0]!="string"?r.blobs=t.blobs.map(n=>Je(n)):r.blobs=t.blobs),typeof t.data<"u"&&(r.data=t.data),t.account&&(r.from=t.account.address),typeof t.from<"u"&&(r.from=t.from),typeof t.gas<"u"&&(r.gas=J(t.gas)),typeof t.gasPrice<"u"&&(r.gasPrice=J(t.gasPrice)),typeof t.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=J(t.maxFeePerBlobGas)),typeof t.maxFeePerGas<"u"&&(r.maxFeePerGas=J(t.maxFeePerGas)),typeof t.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=J(t.maxPriorityFeePerGas)),typeof t.nonce<"u"&&(r.nonce=J(t.nonce)),typeof t.to<"u"&&(r.to=t.to),typeof t.type<"u"&&(r.type=W5[t.type]),typeof t.value<"u"&&(r.value=J(t.value)),r}function K5(t){return t.map(e=>({address:e.address,r:e.r?J(BigInt(e.r)):e.r,s:e.s?J(BigInt(e.s)):e.s,chainId:J(e.chainId),nonce:J(e.nonce),...typeof e.yParity<"u"?{yParity:J(e.yParity)}:{},...typeof e.v<"u"&&typeof e.yParity>"u"?{v:J(e.v)}:{}}))}function zp(t){if(!(!t||t.length===0))return t.reduce((e,{slot:r,value:n})=>{if(r.length!==66)throw new Ip({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new Ip({size:n.length,targetSize:66,type:"hex"});return e[r]=n,e},{})}function X5(t){const{balance:e,nonce:r,state:n,stateDiff:s,code:i}=t,o={};if(i!==void 0&&(o.code=i),e!==void 0&&(o.balance=J(e)),r!==void 0&&(o.nonce=J(r)),n!==void 0&&(o.state=zp(n)),s!==void 0){if(o.state)throw new _5;o.stateDiff=zp(s)}return o}function eh(t){if(!t)return;const e={};for(const{address:r,...n}of t){if(!st(r,{strict:!1}))throw new Bt({address:r});if(e[r])throw new T5({address:r});e[r]=X5(n)}return e}const Kc=2n**256n-1n;function Nn(t){const{account:e,maxFeePerGas:r,maxPriorityFeePerGas:n,to:s}=t,i=e?Fe(e):void 0;if(i&&!st(i.address))throw new Bt({address:i.address});if(s&&!st(s))throw new Bt({address:s});if(r&&r>Kc)throw new Ds({maxFeePerGas:r});if(n&&r&&n>r)throw new Xo({maxFeePerGas:r,maxPriorityFeePerGas:n})}class kb extends q{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class th extends q{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class Y5 extends q{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${$t(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class xb extends q{constructor({blockHash:e,blockNumber:r}){let n="Block";e&&(n=`Block at hash "${e}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const Tb={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function ga(t,e){const r={...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,chainId:t.chainId?dr(t.chainId):void 0,gas:t.gas?BigInt(t.gas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,maxFeePerBlobGas:t.maxFeePerBlobGas?BigInt(t.maxFeePerBlobGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,nonce:t.nonce?dr(t.nonce):void 0,to:t.to?t.to:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,type:t.type?Tb[t.type]:void 0,typeHex:t.type?t.type:void 0,value:t.value?BigInt(t.value):void 0,v:t.v?BigInt(t.v):void 0};return t.authorizationList&&(r.authorizationList=Z5(t.authorizationList)),r.yParity=(()=>{if(t.yParity)return Number(t.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}const J5=Qd("transaction",ga);function Z5(t){return t.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))}function rh(t,e){const r=(t.transactions??[]).map(n=>typeof n=="string"?n:ga(n));return{...t,baseFeePerGas:t.baseFeePerGas?BigInt(t.baseFeePerGas):null,blobGasUsed:t.blobGasUsed?BigInt(t.blobGasUsed):void 0,difficulty:t.difficulty?BigInt(t.difficulty):void 0,excessBlobGas:t.excessBlobGas?BigInt(t.excessBlobGas):void 0,gasLimit:t.gasLimit?BigInt(t.gasLimit):void 0,gasUsed:t.gasUsed?BigInt(t.gasUsed):void 0,hash:t.hash?t.hash:null,logsBloom:t.logsBloom?t.logsBloom:null,nonce:t.nonce?t.nonce:null,number:t.number?BigInt(t.number):null,size:t.size?BigInt(t.size):void 0,timestamp:t.timestamp?BigInt(t.timestamp):void 0,transactions:r,totalDifficulty:t.totalDifficulty?BigInt(t.totalDifficulty):null}}const Q5=Qd("block",rh);async function Sr(t,{blockHash:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",includeTransactions:s}={}){var u,l,f;const i=s??!1,o=r!==void 0?J(r):void 0;let a=null;if(e?a=await t.request({method:"eth_getBlockByHash",params:[e,i]},{dedupe:!0}):a=await t.request({method:"eth_getBlockByNumber",params:[o||n,i]},{dedupe:!!o}),!a)throw new xb({blockHash:e,blockNumber:r});return(((f=(l=(u=t.chain)==null?void 0:u.formatters)==null?void 0:l.block)==null?void 0:f.format)||rh)(a,"getBlock")}async function nh(t){const e=await t.request({method:"eth_gasPrice"});return BigInt(e)}async function eE(t,e){return _b(t,e)}async function _b(t,e){var i,o;const{block:r,chain:n=t.chain,request:s}=e||{};try{const a=((i=n==null?void 0:n.fees)==null?void 0:i.maxPriorityFeePerGas)??((o=n==null?void 0:n.fees)==null?void 0:o.defaultPriorityFee);if(typeof a=="function"){const u=r||await ne(t,Sr,"getBlock")({}),l=await a({block:u,client:t,request:s});if(l===null)throw new Error;return l}if(typeof a<"u")return a;const c=await t.request({method:"eth_maxPriorityFeePerGas"});return ot(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):ne(t,Sr,"getBlock")({}),ne(t,nh,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new th;const u=c-a.baseFeePerGas;return u<0n?0n:u}}async function tE(t,e){return Yf(t,e)}async function Yf(t,e){var h,d;const{block:r,chain:n=t.chain,request:s,type:i="eip1559"}=e||{},o=await(async()=>{var p,m;return typeof((p=n==null?void 0:n.fees)==null?void 0:p.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:t,request:s}):((m=n==null?void 0:n.fees)==null?void 0:m.baseFeeMultiplier)??1.2})();if(o<1)throw new kb;const c=10**(((h=o.toString().split(".")[1])==null?void 0:h.length)??0),u=p=>p*BigInt(Math.ceil(o*c))/BigInt(c),l=r||await ne(t,Sr,"getBlock")({});if(typeof((d=n==null?void 0:n.fees)==null?void 0:d.estimateFeesPerGas)=="function"){const p=await n.fees.estimateFeesPerGas({block:r,client:t,multiply:u,request:s,type:i});if(p!==null)return p}if(i==="eip1559"){if(typeof l.baseFeePerGas!="bigint")throw new th;const p=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await _b(t,{block:l,chain:n,request:s}),m=u(l.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??m+p,maxPriorityFeePerGas:p}}return{gasPrice:(s==null?void 0:s.gasPrice)??u(await ne(t,nh,"getGasPrice")({}))}}async function sh(t,{address:e,blockTag:r="latest",blockNumber:n}){const s=await t.request({method:"eth_getTransactionCount",params:[e,typeof n=="bigint"?J(n):r]},{dedupe:!!n});return dr(s)}function ih(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(i=>en(i)):t.blobs,s=[];for(const i of n)s.push(Uint8Array.from(e.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>Je(i))}function oh(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(o=>en(o)):t.blobs,s=typeof t.commitments[0]=="string"?t.commitments.map(o=>en(o)):t.commitments,i=[];for(let o=0;o<n.length;o++){const a=n[o],c=s[o];i.push(Uint8Array.from(e.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(o=>Je(o))}function rE(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function nE(t,e,r){return t&e^~t&r}function sE(t,e,r){return t&e^t&r^e&r}let Pb=class extends Lc{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ru(this.buffer)}update(e){os(this),e=Sn(e),is(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=Ru(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){os(this),zd(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,Pr(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)r[f]=0;rE(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=Ru(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const jn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Un=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),iE=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Fn=new Uint32Array(64);let ah=class extends Pb{constructor(e=32){super(64,e,8,!1),this.A=jn[0]|0,this.B=jn[1]|0,this.C=jn[2]|0,this.D=jn[3]|0,this.E=jn[4]|0,this.F=jn[5]|0,this.G=jn[6]|0,this.H=jn[7]|0}get(){const{A:e,B:r,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[e,r,n,s,i,o,a,c]}set(e,r,n,s,i,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)Fn[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const h=Fn[f-15],d=Fn[f-2],p=Fr(h,7)^Fr(h,18)^h>>>3,m=Fr(d,17)^Fr(d,19)^d>>>10;Fn[f]=m+Fn[f-7]+p+Fn[f-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const h=Fr(a,6)^Fr(a,11)^Fr(a,25),d=l+h+nE(a,c,u)+iE[f]+Fn[f]|0,m=(Fr(n,2)^Fr(n,13)^Fr(n,22))+sE(n,s,i)|0;l=u,u=c,c=a,a=o+d|0,o=i,i=s,s=n,n=d+m|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,i,o,a,c,u,l)}roundClean(){Pr(Fn)}destroy(){this.set(0,0,0,0,0,0,0,0),Pr(this.buffer)}},Ob=class extends ah{constructor(){super(28),this.A=Un[0]|0,this.B=Un[1]|0,this.C=Un[2]|0,this.D=Un[3]|0,this.E=Un[4]|0,this.F=Un[5]|0,this.G=Un[6]|0,this.H=Un[7]|0}};const Ib=Dc(()=>new ah),oE=Dc(()=>new Ob),aE=ah,Bb=Ib,cE=Ob,uE=oE,lE=Object.freeze(Object.defineProperty({__proto__:null,SHA224:cE,SHA256:aE,sha224:uE,sha256:Bb},Symbol.toStringTag,{value:"Module"}));function fo(t,e){const r=e||"hex",n=Bb(_r(t,{strict:!1})?Vi(t):t);return r==="bytes"?n:Ot(n)}function fE(t){const{commitment:e,version:r=1}=t,n=t.to??(typeof e=="string"?"hex":"bytes"),s=fo(e,"bytes");return s.set([r],0),n==="bytes"?s:Je(s)}function Cb(t){const{commitments:e,version:r}=t,n=t.to??(typeof e[0]=="string"?"hex":"bytes"),s=[];for(const i of e)s.push(fE({commitment:i,to:n,version:r}));return s}const Vp=6,Nb=32,ch=4096,Rb=Nb*ch,Gp=Rb*Vp-1-1*ch*Vp,Mb=1;class dE extends q{constructor({maxSize:e,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class jb extends q{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class hE extends q{constructor({hash:e,size:r}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class pE extends q{constructor({hash:e,version:r}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${Mb}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function yE(t){const e=t.to??(typeof t.data=="string"?"hex":"bytes"),r=typeof t.data=="string"?en(t.data):t.data,n=He(r);if(!n)throw new jb;if(n>Gp)throw new dE({maxSize:Gp,size:n});const s=[];let i=!0,o=0;for(;i;){const a=Yd(new Uint8Array(Rb));let c=0;for(;c<ch;){const u=r.slice(o,o+(Nb-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),i=!1;break}c++,o+=31}s.push(a)}return e==="bytes"?s.map(a=>a.bytes):s.map(a=>Je(a.bytes))}function Ub(t){const{data:e,kzg:r,to:n}=t,s=t.blobs??yE({data:e,to:n}),i=t.commitments??ih({blobs:s,kzg:r,to:n}),o=t.proofs??oh({blobs:s,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<s.length;c++)a.push({blob:s[c],commitment:i[c],proof:o[c]});return a}function Fb(t){if(t.type)return t.type;if(typeof t.authorizationList<"u")return"eip7702";if(typeof t.blobs<"u"||typeof t.blobVersionedHashes<"u"||typeof t.maxFeePerBlobGas<"u"||typeof t.sidecars<"u")return"eip4844";if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")return"eip1559";if(typeof t.gasPrice<"u")return typeof t.accessList<"u"?"eip2930":"legacy";throw new I5({transaction:t})}function Xc(t,{docsPath:e,...r}){const n=(()=>{const s=Wc(t,r);return s instanceof ba?t:s})();return new C5(n,{docsPath:e,...r})}async function hs(t){const e=await t.request({method:"eth_chainId"},{dedupe:!0});return dr(e)}async function uh(t,e){var B,N,$,j,H;const{account:r=t.account,accessList:n,authorizationList:s,chain:i=t.chain,blobVersionedHashes:o,blobs:a,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:p,nonceManager:m,to:v,type:S,value:T,...g}=e,w=await(async()=>{if(!r||!m||typeof p<"u")return p;const G=Fe(r),ee=i?i.id:await ne(t,hs,"getChainId")({});return await m.consume({address:G.address,chainId:ee,client:t})})();Nn(e);const k=(N=(B=i==null?void 0:i.formatters)==null?void 0:B.transactionRequest)==null?void 0:N.format,O=(k||ds)({...qi(g,{format:k}),account:r?Fe(r):void 0,accessList:n,authorizationList:s,blobs:a,blobVersionedHashes:o,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:w,to:v,type:S,value:T},"fillTransaction");try{const G=await t.request({method:"eth_fillTransaction",params:[O]}),U=(((j=($=i==null?void 0:i.formatters)==null?void 0:$.transaction)==null?void 0:j.format)||ga)(G.tx);delete U.blockHash,delete U.blockNumber,delete U.r,delete U.s,delete U.transactionIndex,delete U.v,delete U.yParity,U.data=U.input,U.gas&&(U.gas=e.gas??U.gas),U.gasPrice&&(U.gasPrice=e.gasPrice??U.gasPrice),U.maxFeePerBlobGas&&(U.maxFeePerBlobGas=e.maxFeePerBlobGas??U.maxFeePerBlobGas),U.maxFeePerGas&&(U.maxFeePerGas=e.maxFeePerGas??U.maxFeePerGas),U.maxPriorityFeePerGas&&(U.maxPriorityFeePerGas=e.maxPriorityFeePerGas??U.maxPriorityFeePerGas),U.nonce&&(U.nonce=e.nonce??U.nonce);const X=await(async()=>{var D,Z;if(typeof((D=i==null?void 0:i.fees)==null?void 0:D.baseFeeMultiplier)=="function"){const R=await ne(t,Sr,"getBlock")({});return i.fees.baseFeeMultiplier({block:R,client:t,request:e})}return((Z=i==null?void 0:i.fees)==null?void 0:Z.baseFeeMultiplier)??1.2})();if(X<1)throw new kb;const W=10**(((H=X.toString().split(".")[1])==null?void 0:H.length)??0),C=D=>D*BigInt(Math.ceil(X*W))/BigInt(W);return U.maxFeePerGas&&!e.maxFeePerGas&&(U.maxFeePerGas=C(U.maxFeePerGas)),U.gasPrice&&!e.gasPrice&&(U.gasPrice=C(U.gasPrice)),{raw:G.raw,transaction:{from:O.from,...U}}}catch(G){throw Xc(G,{...e,chain:t.chain})}}const lh=["blobVersionedHashes","chainId","fees","gas","nonce","type"],qp=new Map,Uu=new Gi(128);async function wa(t,e){var w,k,_;let r=e;r.account??(r.account=t.account),r.parameters??(r.parameters=lh);const{account:n,chain:s=t.chain,nonceManager:i,parameters:o}=r,a=(()=>{if(typeof(s==null?void 0:s.prepareTransactionRequest)=="function")return{fn:s.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(s==null?void 0:s.prepareTransactionRequest))return{fn:s.prepareTransactionRequest[0],runAt:s.prepareTransactionRequest[1].runAt}})();let c;async function u(){return c||(typeof r.chainId<"u"?r.chainId:s?s.id:(c=await ne(t,hs,"getChainId")({}),c))}const l=n&&Fe(n);let f=r.nonce;if(o.includes("nonce")&&typeof f>"u"&&l&&i){const O=await u();f=await i.consume({address:l.address,chainId:O,client:t})}a!=null&&a.fn&&((w=a.runAt)!=null&&w.includes("beforeFillTransaction"))&&(r=await a.fn({...r,chain:s},{phase:"beforeFillTransaction"}),f??(f=r.nonce));const d=((o.includes("blobVersionedHashes")||o.includes("sidecars"))&&r.kzg&&r.blobs||Uu.get(t.uid)===!1||!["fees","gas"].some(B=>o.includes(B))?!1:!!(o.includes("chainId")&&typeof r.chainId!="number"||o.includes("nonce")&&typeof f!="number"||o.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||o.includes("gas")&&typeof r.gas!="bigint"))?await ne(t,uh,"fillTransaction")({...r,nonce:f}).then(O=>{const{chainId:B,from:N,gas:$,gasPrice:j,nonce:H,maxFeePerBlobGas:G,maxFeePerGas:ee,maxPriorityFeePerGas:U,type:X,...te}=O.transaction;return Uu.set(t.uid,!0),{...r,...N?{from:N}:{},...X?{type:X}:{},...typeof B<"u"?{chainId:B}:{},...typeof $<"u"?{gas:$}:{},...typeof j<"u"?{gasPrice:j}:{},...typeof H<"u"?{nonce:H}:{},...typeof G<"u"?{maxFeePerBlobGas:G}:{},...typeof ee<"u"?{maxFeePerGas:ee}:{},...typeof U<"u"?{maxPriorityFeePerGas:U}:{},..."nonceKey"in te&&typeof te.nonceKey<"u"?{nonceKey:te.nonceKey}:{}}}).catch(O=>{var $;const B=O;return B.name!=="TransactionExecutionError"||(($=B.walk)==null?void 0:$.call(B,j=>{const H=j;return H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError"}))&&Uu.set(t.uid,!1),r}):r;f??(f=d.nonce),r={...d,...l?{from:l==null?void 0:l.address}:{},...f?{nonce:f}:{}};const{blobs:p,gas:m,kzg:v,type:S}=r;a!=null&&a.fn&&((k=a.runAt)!=null&&k.includes("beforeFillParameters"))&&(r=await a.fn({...r,chain:s},{phase:"beforeFillParameters"}));let T;async function g(){return T||(T=await ne(t,Sr,"getBlock")({blockTag:"latest"}),T)}if(o.includes("nonce")&&typeof f>"u"&&l&&!i&&(r.nonce=await ne(t,sh,"getTransactionCount")({address:l.address,blockTag:"pending"})),(o.includes("blobVersionedHashes")||o.includes("sidecars"))&&p&&v){const O=ih({blobs:p,kzg:v});if(o.includes("blobVersionedHashes")){const B=Cb({commitments:O,to:"hex"});r.blobVersionedHashes=B}if(o.includes("sidecars")){const B=oh({blobs:p,commitments:O,kzg:v}),N=Ub({blobs:p,commitments:O,proofs:B,to:"hex"});r.sidecars=N}}if(o.includes("chainId")&&(r.chainId=await u()),(o.includes("fees")||o.includes("type"))&&typeof S>"u")try{r.type=Fb(r)}catch{let O=qp.get(t.uid);if(typeof O>"u"){const B=await g();O=typeof(B==null?void 0:B.baseFeePerGas)=="bigint",qp.set(t.uid,O)}r.type=O?"eip1559":"legacy"}if(o.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){const O=await g(),{maxFeePerGas:B,maxPriorityFeePerGas:N}=await Yf(t,{block:O,chain:s,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<N)throw new Y5({maxPriorityFeePerGas:N});r.maxPriorityFeePerGas=N,r.maxFeePerGas=B}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new th;if(typeof r.gasPrice>"u"){const O=await g(),{gasPrice:B}=await Yf(t,{block:O,chain:s,request:r,type:"legacy"});r.gasPrice=B}}return o.includes("gas")&&typeof m>"u"&&(r.gas=await ne(t,fh,"estimateGas")({...r,account:l,prepare:(l==null?void 0:l.type)==="local"?[]:["blobVersionedHashes"]})),a!=null&&a.fn&&((_=a.runAt)!=null&&_.includes("afterFillParameters"))&&(r=await a.fn({...r,chain:s},{phase:"afterFillParameters"})),Nn(r),delete r.parameters,r}async function fh(t,e){var o,a,c;const{account:r=t.account,prepare:n=!0}=e,s=r?Fe(r):void 0,i=(()=>{if(Array.isArray(n))return n;if((s==null?void 0:s.type)!=="local")return["blobVersionedHashes"]})();try{const u=await(async()=>{if(e.to)return e.to;if(e.authorizationList&&e.authorizationList.length>0)return await qc({authorization:e.authorizationList[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:l,authorizationList:f,blobs:h,blobVersionedHashes:d,blockNumber:p,blockTag:m,data:v,gas:S,gasPrice:T,maxFeePerBlobGas:g,maxFeePerGas:w,maxPriorityFeePerGas:k,nonce:_,value:O,stateOverride:B,...N}=n?await wa(t,{...e,parameters:i,to:u}):e;if(S&&e.gas!==S)return S;const j=(typeof p=="bigint"?J(p):void 0)||m,H=eh(B);Nn(e);const G=(c=(a=(o=t.chain)==null?void 0:o.formatters)==null?void 0:a.transactionRequest)==null?void 0:c.format,U=(G||ds)({...qi(N,{format:G}),account:s,accessList:l,authorizationList:f,blobs:h,blobVersionedHashes:d,data:v,gasPrice:T,maxFeePerBlobGas:g,maxFeePerGas:w,maxPriorityFeePerGas:k,nonce:_,to:u,value:O},"estimateGas");return BigInt(await t.request({method:"eth_estimateGas",params:H?[U,j??t.experimental_blockTag??"latest",H]:j?[U,j]:[U]}))}catch(u){throw q5(u,{...e,account:s,chain:t.chain})}}async function $b(t,e){const{abi:r,address:n,args:s,functionName:i,dataSuffix:o,...a}=e,c=er({abi:r,args:s,functionName:i});try{return await ne(t,fh,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(u){const l=a.account?Fe(a.account):void 0;throw Ls(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:l==null?void 0:l.address})}}function Wi(t,e){if(!st(t,{strict:!1}))throw new Bt({address:t});if(!st(e,{strict:!1}))throw new Bt({address:e});return t.toLowerCase()===e.toLowerCase()}const Wp="/docs/contract/decodeEventLog";function Ec(t){const{abi:e,data:r,strict:n,topics:s}=t,i=n??!0,[o,...a]=s;if(!o)throw new s6({docsPath:Wp});const c=e.find(m=>m.type==="event"&&o===Hc(Tr(m)));if(!(c&&"name"in c)||c.type!=="event")throw new i6(o,{docsPath:Wp});const{name:u,inputs:l}=c,f=l==null?void 0:l.some(m=>!("name"in m&&m.name)),h=f?[]:{},d=l.map((m,v)=>[m,v]).filter(([m])=>"indexed"in m&&m.indexed);for(let m=0;m<d.length;m++){const[v,S]=d[m],T=a[m];if(!T)throw new Hd({abiItem:c,param:v});h[f?S:v.name||S]=mE({param:v,value:T})}const p=l.filter(m=>!("indexed"in m&&m.indexed));if(p.length>0){if(r&&r!=="0x")try{const m=ya(p,r);if(m)if(f)for(let v=0;v<l.length;v++)h[v]=h[v]??m.shift();else for(let v=0;v<p.length;v++)h[p[v].name]=m[v]}catch(m){if(i)throw m instanceof Fm||m instanceof db?new vc({abiItem:c,data:r,params:p,size:He(r)}):m}else if(i)throw new vc({abiItem:c,data:"0x",params:p,size:0})}return{eventName:u,args:Object.values(h).length>0?h:void 0}}function mE({param:t,value:e}){return t.type==="string"||t.type==="bytes"||t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/)?e:(ya([t],e)||[])[0]}function dh(t){const{abi:e,args:r,logs:n,strict:s=!0}=t,i=(()=>{if(t.eventName)return Array.isArray(t.eventName)?t.eventName:[t.eventName]})();return n.map(o=>{var l;const a=e.filter(f=>f.type==="event"&&o.topics[0]===Hc(f));if(a.length===0)return null;let c,u;for(const f of a)try{c=Ec({...o,abi:[f],strict:!0}),u=f;break}catch{}if(!c&&!s){u=a[0];try{c=Ec({...o,abi:[u],strict:!1})}catch{const f=(l=u.inputs)==null?void 0:l.some(h=>!("name"in h&&h.name));return{...o,args:f?[]:{},eventName:u.name}}}return!c||!u||i&&!i.includes(c.eventName)||!bE({args:c.args,inputs:u.inputs,matchArgs:r})?null:{...c,...o}}).filter(Boolean)}function bE(t){const{args:e,inputs:r,matchArgs:n}=t;if(!n)return!0;if(!e)return!1;function s(i,o,a){try{return i.type==="address"?Wi(o,a):i.type==="string"||i.type==="bytes"?dt(Vi(o))===a:o===a}catch{return!1}}return Array.isArray(e)&&Array.isArray(n)?n.every((i,o)=>{if(i==null)return!0;const a=r[o];return a?(Array.isArray(i)?i:[i]).some(u=>s(a,u,e[o])):!1}):typeof e=="object"&&!Array.isArray(e)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,o])=>{if(o==null)return!0;const a=r.find(u=>u.name===i);return a?(Array.isArray(o)?o:[o]).some(u=>s(a,u,e[i])):!1}):!1}function _n(t,{args:e,eventName:r}={}){return{...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,blockTimestamp:t.blockTimestamp?BigInt(t.blockTimestamp):t.blockTimestamp===null?null:void 0,logIndex:t.logIndex?Number(t.logIndex):null,transactionHash:t.transactionHash?t.transactionHash:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,...r?{args:e,eventName:r}:{}}}async function hh(t,{address:e,blockHash:r,fromBlock:n,toBlock:s,event:i,events:o,args:a,strict:c}={}){const u=c??!1,l=o??(i?[i]:void 0);let f=[];l&&(f=[l.flatMap(m=>pa({abi:[m],eventName:m.name,args:o?void 0:a}))],i&&(f=f[0]));let h;r?h=await t.request({method:"eth_getLogs",params:[{address:e,topics:f,blockHash:r}]}):h=await t.request({method:"eth_getLogs",params:[{address:e,topics:f,fromBlock:typeof n=="bigint"?J(n):n,toBlock:typeof s=="bigint"?J(s):s}]});const d=h.map(p=>_n(p));return l?dh({abi:l,args:a,logs:d,strict:u}):d}async function ph(t,e){const{abi:r,address:n,args:s,blockHash:i,eventName:o,fromBlock:a,toBlock:c,strict:u}=e,l=o?Ys({abi:r,name:o}):void 0,f=l?void 0:r.filter(h=>h.type==="event");return ne(t,hh,"getLogs")({address:n,args:s,blockHash:i,event:l,events:f,fromBlock:a,toBlock:c,strict:u})}const Fu="/docs/contract/decodeFunctionResult";function Js(t){const{abi:e,args:r,functionName:n,data:s}=t;let i=e[0];if(n){const a=Ys({abi:e,args:r,name:n});if(!a)throw new Ii(n,{docsPath:Fu});i=a}if(i.type!=="function")throw new Ii(void 0,{docsPath:Fu});if(!i.outputs)throw new Lm(i.name,{docsPath:Fu});const o=ya(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const yh=BigInt(0),Jf=BigInt(1);function va(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function mh(t){if(!va(t))throw new Error("Uint8Array expected")}function Yo(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Fa(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Lb(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?yh:BigInt("0x"+t)}const Db=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",gE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Jo(t){if(mh(t),Db)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=gE[t[r]];return e}const sn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Kp(t){if(t>=sn._0&&t<=sn._9)return t-sn._0;if(t>=sn.A&&t<=sn.F)return t-(sn.A-10);if(t>=sn.a&&t<=sn.f)return t-(sn.a-10)}function Sc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Db)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let s=0,i=0;s<r;s++,i+=2){const o=Kp(t.charCodeAt(i)),a=Kp(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function Bs(t){return Lb(Jo(t))}function Hb(t){return mh(t),Lb(Jo(Uint8Array.from(t).reverse()))}function Ea(t,e){return Sc(t.toString(16).padStart(e*2,"0"))}function zb(t,e){return Ea(t,e).reverse()}function or(t,e,r){let n;if(typeof e=="string")try{n=Sc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(va(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=n.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return n}function Ac(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];mh(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}const $u=t=>typeof t=="bigint"&&yh<=t;function bh(t,e,r){return $u(t)&&$u(e)&&$u(r)&&e<=t&&t<r}function Si(t,e,r,n){if(!bh(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function wE(t){let e;for(e=0;t>yh;t>>=Jf,e+=1);return e}const Yc=t=>(Jf<<BigInt(t))-Jf,Lu=t=>new Uint8Array(t),Xp=t=>Uint8Array.from(t);function vE(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=Lu(t),s=Lu(t),i=0;const o=()=>{n.fill(1),s.fill(0),i=0},a=(...f)=>r(s,n,...f),c=(f=Lu(0))=>{s=a(Xp([0]),f),n=a(),f.length!==0&&(s=a(Xp([1]),f),n=a())},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const h=[];for(;f<e;){n=a();const d=n.slice();h.push(d),f+=n.length}return Ac(...h)};return(f,h)=>{o(),c(f);let d;for(;!(d=h(u()));)c();return o(),d}}const EE={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||va(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Jc(t,e,r={}){const n=(s,i,o)=>{const a=EE[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))n(s,i,!1);for(const[s,i]of Object.entries(r))n(s,i,!0);return t}function Yp(t){const e=new WeakMap;return(r,...n)=>{const s=e.get(r);if(s!==void 0)return s;const i=t(r,...n);return e.set(r,i),i}}const SE="0.1.1";function AE(){return SE}class le extends Error{static setStaticOptions(e){le.prototype.docsOrigin=e.docsOrigin,le.prototype.showVersion=e.showVersion,le.prototype.version=e.version}constructor(e,r={}){const n=(()=>{var l;if(r.cause instanceof le){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(l=r.cause)!=null&&l.message?r.cause.message:r.details})(),s=r.cause instanceof le&&r.cause.docsPath||r.docsPath,i=r.docsOrigin??le.prototype.docsOrigin,o=`${i}${s??""}`,a=!!(r.version??le.prototype.showVersion),c=r.version??le.prototype.version,u=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||s||a?["",n?`Details: ${n}`:void 0,s?`See: ${o}`:void 0,a?`Version: ${c}`:void 0]:[]].filter(l=>typeof l=="string").join(`
39
+ `);super(u,r.cause?{cause:r.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=r.cause,this.details=n,this.docs=o,this.docsOrigin=i,this.docsPath=s,this.shortMessage=e,this.showVersion=a,this.version=c}walk(e){return Vb(this,e)}}Object.defineProperty(le,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${AE()}`}});le.setStaticOptions(le.defaultStaticOptions);function Vb(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Vb(t.cause,e):e?null:t}function Sa(t,e){if(bi(t)>e)throw new LE({givenSize:bi(t),maxSize:e})}const on={zero:48,nine:57,A:65,F:70,a:97,f:102};function Jp(t){if(t>=on.zero&&t<=on.nine)return t-on.zero;if(t>=on.A&&t<=on.F)return t-(on.A-10);if(t>=on.a&&t<=on.f)return t-(on.a-10)}function kE(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new DE({size:t.length,targetSize:n,type:"Bytes"});const s=new Uint8Array(n);for(let i=0;i<n;i++){const o=r==="right";s[o?i:n-i-1]=t[o?i:t.length-i-1]}return s}function Gb(t,e={}){const{dir:r="left"}=e;let n=t,s=0;for(let i=0;i<n.length-1&&n[r==="left"?i:n.length-i-1].toString()==="0";i++)s++;return n=r==="left"?n.slice(s):n.slice(0,n.length-s),n}function Zc(t,e){if(Zt(t)>e)throw new WE({givenSize:Zt(t),maxSize:e})}function xE(t,e){if(typeof e=="number"&&e>0&&e>Zt(t)-1)throw new eg({offset:e,position:"start",size:Zt(t)})}function TE(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Zt(t)!==r-e)throw new eg({offset:r,position:"end",size:Zt(t)})}function qb(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const s=t.replace("0x","");if(s.length>n*2)throw new KE({size:Math.ceil(s.length/2),targetSize:n,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const _E="#__bigint";function Wb(t,e,r){return JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString()+_E:s,r)}const PE=new TextDecoder,OE=new TextEncoder;function IE(t){return t instanceof Uint8Array?t:typeof t=="string"?Kb(t):BE(t)}function BE(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Kb(t,e={}){const{size:r}=e;let n=t;r&&(Zc(t,r),n=zs(t,r));let s=n.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const u=Jp(s.charCodeAt(c++)),l=Jp(s.charCodeAt(c++));if(u===void 0||l===void 0)throw new le(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=u<<4|l}return o}function CE(t,e={}){const{size:r}=e,n=OE.encode(t);return typeof r=="number"?(Sa(n,r),NE(n,r)):n}function NE(t,e){return kE(t,{dir:"right",size:e})}function bi(t){return t.length}function RE(t,e,r,n={}){const{strict:s}=n;return t.slice(e,r)}function ME(t,e={}){const{size:r}=e;typeof r<"u"&&Sa(t,r);const n=Ir(t,e);return Jb(n,e)}function jE(t,e={}){const{size:r}=e;let n=t;if(typeof r<"u"&&(Sa(n,r),n=Xb(n)),n.length>1||n[0]>1)throw new $E(n);return!!n[0]}function kn(t,e={}){const{size:r}=e;typeof r<"u"&&Sa(t,r);const n=Ir(t,e);return Zb(n,e)}function UE(t,e={}){const{size:r}=e;let n=t;return typeof r<"u"&&(Sa(n,r),n=FE(n)),PE.decode(n)}function Xb(t){return Gb(t,{dir:"left"})}function FE(t){return Gb(t,{dir:"right"})}class $E extends le{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}}let LE=class extends le{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},DE=class extends le{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const HE=new TextEncoder,zE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function VE(t,e={}){const{strict:r=!1}=e;if(!t)throw new Zp(t);if(typeof t!="string")throw new Zp(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Qp(t);if(!t.startsWith("0x"))throw new Qp(t)}function Or(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function GE(t){return t instanceof Uint8Array?Ir(t):Array.isArray(t)?Ir(new Uint8Array(t)):t}function Yb(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Zc(r,e.size),Hs(r,e.size)):r}function Ir(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=zE[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Zc(n,e.size),zs(n,e.size)):n}function _t(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const u=typeof t=="bigint"?"n":"";throw new Qb({max:i?`${i}${u}`:void 0,min:`${o}${u}`,signed:r,size:n,value:`${t}${u}`})}const c=`0x${(r&&s<0?BigInt.asUintN(n*8,BigInt(s)):s).toString(16)}`;return n?Hs(c,n):c}function gh(t,e={}){return Ir(HE.encode(t),e)}function Hs(t,e){return qb(t,{dir:"left",size:e})}function zs(t,e){return qb(t,{dir:"right",size:e})}function Zr(t,e,r,n={}){const{strict:s}=n;xE(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&TE(i,e,r),i}function Zt(t){return Math.ceil((t.length-2)/2)}function Jb(t,e={}){const{signed:r}=e;e.size&&Zc(t,e.size);const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n)-1n,o=i>>1n;return n<=o?n:n-i-1n}function Zb(t,e={}){const{signed:r,size:n}=e;return Number(!r&&!n?t:Jb(t,e))}function qE(t,e={}){const{strict:r=!1}=e;try{return VE(t,{strict:r}),!0}catch{return!1}}class Qb extends le{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Zp extends le{constructor(e){super(`Value \`${typeof e=="object"?Wb(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Qp extends le{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class WE extends le{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class eg extends le{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class KE extends le{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function XE(t){return{address:t.address,amount:_t(t.amount),index:_t(t.index),validatorIndex:_t(t.validatorIndex)}}function tg(t){return{...typeof t.baseFeePerGas=="bigint"&&{baseFeePerGas:_t(t.baseFeePerGas)},...typeof t.blobBaseFee=="bigint"&&{blobBaseFee:_t(t.blobBaseFee)},...typeof t.feeRecipient=="string"&&{feeRecipient:t.feeRecipient},...typeof t.gasLimit=="bigint"&&{gasLimit:_t(t.gasLimit)},...typeof t.number=="bigint"&&{number:_t(t.number)},...typeof t.prevRandao=="bigint"&&{prevRandao:_t(t.prevRandao)},...typeof t.time=="bigint"&&{time:_t(t.time)},...t.withdrawals&&{withdrawals:t.withdrawals.map(XE)}}}const kc=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],Zf=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],rg=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],ng=[...rg,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],YE=[...rg,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],e0=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],t0=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],sg=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],r0=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],JE="0x82ad56cb",ig="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",ZE="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",QE="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",wh="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";class Qf extends q{constructor({blockNumber:e,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...e&&n.blockCreated&&n.blockCreated>e?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${e}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class eS extends q{constructor({chain:e,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${e.id} – ${e.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${e.id} – ${e.name}`],name:"ChainMismatchError"})}}class tS extends q{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
40
+ `),{name:"ChainNotFoundError"})}}class og extends q{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class Qc extends q{constructor({chainId:e}){super(typeof e=="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const Du="/docs/contract/encodeDeployData";function eu(t){const{abi:e,args:r,bytecode:n}=t;if(!r||r.length===0)return n;const s=e.find(o=>"type"in o&&o.type==="constructor");if(!s)throw new Q2({docsPath:Du});if(!("inputs"in s))throw new _p({docsPath:Du});if(!s.inputs||s.inputs.length===0)throw new _p({docsPath:Du});const i=fs(s.inputs,r);return Nr([n,i])}function Ki({blockNumber:t,chain:e,contract:r}){var s;const n=(s=e==null?void 0:e.contracts)==null?void 0:s[r];if(!n)throw new Qf({chain:e,contract:{name:r}});if(t&&n.blockCreated&&n.blockCreated>t)throw new Qf({blockNumber:t,chain:e,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function ag(t,{docsPath:e,...r}){const n=(()=>{const s=Wc(t,r);return s instanceof ba?t:s})();return new wb(n,{docsPath:e,...r})}function vh(){let t=()=>{},e=()=>{};return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}const Hu=new Map;function cg({fn:t,id:e,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const l=c();o();const f=l.map(({args:h})=>h);f.length!==0&&t(f).then(h=>{s&&Array.isArray(h)&&h.sort(s);for(let d=0;d<l.length;d++){const{resolve:p}=l[d];p==null||p([h[d],h])}}).catch(h=>{for(let d=0;d<l.length;d++){const{reject:p}=l[d];p==null||p(h)}})},o=()=>Hu.delete(e),a=()=>c().map(({args:l})=>l),c=()=>Hu.get(e)||[],u=l=>Hu.set(e,[...c(),l]);return{flush:o,async schedule(l){const{promise:f,resolve:h,reject:d}=vh();return(r==null?void 0:r([...a(),l]))&&i(),c().length>0?(u({args:l,resolve:h,reject:d}),f):(u({args:l,resolve:h,reject:d}),setTimeout(i,n),f)}}}async function Aa(t,e){var G,ee,U,X;const{account:r=t.account,authorizationList:n,batch:s=!!((G=t.batch)!=null&&G.multicall),blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:u,code:l,data:f,factory:h,factoryData:d,gas:p,gasPrice:m,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:T,nonce:g,to:w,value:k,stateOverride:_,...O}=e,B=r?Fe(r):void 0;if(l&&(h||d))throw new q("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(l&&w)throw new q("Cannot provide both `code` & `to` as parameters.");const N=l&&f,$=h&&d&&w&&f,j=N||$,H=N?ug({code:l,data:f}):$?sS({data:f,factory:h,factoryData:d,to:w}):f;try{Nn(e);const W=(typeof i=="bigint"?J(i):void 0)||o,C=u?tg(u):void 0,D=eh(_),Z=(X=(U=(ee=t.chain)==null?void 0:ee.formatters)==null?void 0:U.transactionRequest)==null?void 0:X.format,F=(Z||ds)({...qi(O,{format:Z}),accessList:a,account:B,authorizationList:n,blobs:c,data:H,gas:p,gasPrice:m,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:T,nonce:g,to:j?void 0:w,value:k},"call");if(s&&rS({request:F})&&!D&&!C)try{return await nS(t,{...F,blockNumber:i,blockTag:o})}catch(ae){if(!(ae instanceof og)&&!(ae instanceof Qf))throw ae}const z=(()=>{const ae=[F,W];return D&&C?[...ae,D,C]:D?[...ae,D]:C?[...ae,{},C]:ae})(),se=await t.request({method:"eth_call",params:z});return se==="0x"?{data:void 0}:{data:se}}catch(te){const W=iS(te),{offchainLookup:C,offchainLookupSignature:D}=await Promise.resolve().then(()=>require("./ccip-rfAqgfGh.cjs"));if(t.ccipRead!==!1&&(W==null?void 0:W.slice(0,10))===D&&w)return{data:await C(t,{data:W,to:w})};throw j&&(W==null?void 0:W.slice(0,10))==="0x101bb98d"?new j5({factory:h}):ag(te,{...e,account:B,chain:t.chain})}}function rS({request:t}){const{data:e,to:r,...n}=t;return!(!e||e.startsWith(JE)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function nS(t,e){var m;const{batchSize:r=1024,deployless:n=!1,wait:s=0}=typeof((m=t.batch)==null?void 0:m.multicall)=="object"?t.batch.multicall:{},{blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",data:a,to:c}=e,u=(()=>{if(n)return null;if(e.multicallAddress)return e.multicallAddress;if(t.chain)return Ki({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new og})(),f=(typeof i=="bigint"?J(i):void 0)||o,{schedule:h}=cg({id:`${t.uid}.${f}`,wait:s,shouldSplitBatch(v){return v.reduce((T,{data:g})=>T+(g.length-2),0)>r*2},fn:async v=>{const S=v.map(w=>({allowFailure:!0,callData:w.data,target:w.to})),T=er({abi:kc,args:[S],functionName:"aggregate3"}),g=await t.request({method:"eth_call",params:[{...u===null?{data:ug({code:wh,data:T})}:{to:u,data:T}},f]});return Js({abi:kc,args:[S],functionName:"aggregate3",data:g||"0x"})}}),[{returnData:d,success:p}]=await h({data:a,to:c});if(!p)throw new Gc({data:d});return d==="0x"?{data:void 0}:{data:d}}function ug(t){const{code:e,data:r}=t;return eu({abi:Mm(["constructor(bytes, bytes)"]),bytecode:ig,args:[e,r]})}function sS(t){const{data:e,factory:r,factoryData:n,to:s}=t;return eu({abi:Mm(["constructor(address, bytes, address, bytes)"]),bytecode:ZE,args:[s,e,r,n]})}function iS(t){var r;if(!(t instanceof q))return;const e=t.walk();return typeof(e==null?void 0:e.data)=="object"?(r=e.data)==null?void 0:r.data:e.data}async function hr(t,e){const{abi:r,address:n,args:s,functionName:i,...o}=e,a=er({abi:r,args:s,functionName:i});try{const{data:c}=await ne(t,Aa,"call")({...o,data:a,to:n});return Js({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Ls(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function lg(t,e){const{abi:r,address:n,args:s,dataSuffix:i,functionName:o,...a}=e,c=a.account?Fe(a.account):t.account,u=er({abi:r,args:s,functionName:o});try{const{data:l}=await ne(t,Aa,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),f=Js({abi:r,args:s,functionName:o,data:l||"0x"}),h=r.filter(d=>"name"in d&&d.name===e.functionName);return{result:f,request:{abi:h,address:n,args:s,dataSuffix:i,functionName:o,...a,account:c}}}catch(l){throw Ls(l,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const zu=new Map,n0=new Map;let oS=0;function Pn(t,e,r){const n=++oS,s=()=>zu.get(t)||[],i=()=>{const l=s();zu.set(t,l.filter(f=>f.id!==n))},o=()=>{const l=s();if(!l.some(h=>h.id===n))return;const f=n0.get(t);if(l.length===1&&f){const h=f();h instanceof Promise&&h.catch(()=>{})}i()},a=s();if(zu.set(t,[...a,{id:n,fns:e}]),a&&a.length>0)return o;const c={};for(const l in e)c[l]=(...f)=>{var d,p;const h=s();if(h.length!==0)for(const m of h)(p=(d=m.fns)[l])==null||p.call(d,...f)};const u=r(c);return typeof u=="function"&&n0.set(t,u),o}async function ed(t){return new Promise(e=>setTimeout(e,t))}function Xi(t,{emitOnBegin:e,initialWaitTime:r,interval:n}){let s=!0;const i=()=>s=!1;return(async()=>{let a;e&&(a=await t({unpoll:i}));const c=await(r==null?void 0:r(a))??n;await ed(c);const u=async()=>{s&&(await t({unpoll:i}),await ed(n),u())};u()})(),i}const aS=new Map,cS=new Map;function uS(t){const e=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),r=e(t,aS),n=e(t,cS);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function lS(t,{cacheKey:e,cacheTime:r=Number.POSITIVE_INFINITY}){const n=uS(e),s=n.response.get();if(s&&r>0&&Date.now()-s.created.getTime()<r)return s.data;let i=n.promise.get();i||(i=t(),n.promise.set(i));try{const o=await i;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const fS=t=>`blockNumber.${t}`;async function ka(t,{cacheTime:e=t.cacheTime}={}){const r=await lS(()=>t.request({method:"eth_blockNumber"}),{cacheKey:fS(t.uid),cacheTime:e});return BigInt(r)}async function tu(t,{filter:e}){const r="strict"in e&&e.strict,n=await e.request({method:"eth_getFilterChanges",params:[e.id]});if(typeof n[0]=="string")return n;const s=n.map(i=>_n(i));return!("abi"in e)||!e.abi?s:dh({abi:e.abi,logs:s,strict:r})}async function ru(t,{filter:e}){return e.request({method:"eth_uninstallFilter",params:[e.id]})}function fg(t,e){const{abi:r,address:n,args:s,batch:i=!0,eventName:o,fromBlock:a,onError:c,onLogs:u,poll:l,pollingInterval:f=t.pollingInterval,strict:h}=e;return(typeof l<"u"?l:typeof a=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")))?(()=>{const v=h??!1,S=Ye(["watchContractEvent",n,s,i,t.uid,o,f,v,a]);return Pn(S,{onLogs:u,onError:c},T=>{let g;a!==void 0&&(g=a-1n);let w,k=!1;const _=Xi(async()=>{var O;if(!k){try{w=await ne(t,Xd,"createContractEventFilter")({abi:r,address:n,args:s,eventName:o,strict:v,fromBlock:a})}catch{}k=!0;return}try{let B;if(w)B=await ne(t,tu,"getFilterChanges")({filter:w});else{const N=await ne(t,ka,"getBlockNumber")({});g&&g<N?B=await ne(t,ph,"getContractEvents")({abi:r,address:n,args:s,eventName:o,fromBlock:g+1n,toBlock:N,strict:v}):B=[],g=N}if(B.length===0)return;if(i)T.onLogs(B);else for(const N of B)T.onLogs([N])}catch(B){w&&B instanceof as&&(k=!1),(O=T.onError)==null||O.call(T,B)}},{emitOnBegin:!0,interval:f});return async()=>{w&&await ne(t,ru,"uninstallFilter")({filter:w}),_()}})})():(()=>{const v=h??!1,S=Ye(["watchContractEvent",n,s,i,t.uid,o,f,v]);let T=!0,g=()=>T=!1;return Pn(S,{onLogs:u,onError:c},w=>((async()=>{try{const k=(()=>{if(t.transport.type==="fallback"){const B=t.transport.transports.find(N=>N.config.type==="webSocket"||N.config.type==="ipc");return B?B.value:t.transport}return t.transport})(),_=o?pa({abi:r,eventName:o,args:s}):[],{unsubscribe:O}=await k.subscribe({params:["logs",{address:n,topics:_}],onData(B){var $;if(!T)return;const N=B.result;try{const{eventName:j,args:H}=Ec({abi:r,data:N.data,topics:N.topics,strict:h}),G=_n(N,{args:H,eventName:j});w.onLogs([G])}catch(j){let H,G;if(j instanceof vc||j instanceof Hd){if(h)return;H=j.abiItem.name,G=($=j.abiItem.inputs)==null?void 0:$.some(U=>!("name"in U&&U.name))}const ee=_n(N,{args:G?[]:{},eventName:H});w.onLogs([ee])}},onError(B){var N;(N=w.onError)==null||N.call(w,B)}});g=O,T||g()}catch(k){c==null||c(k)}})(),()=>g()))})()}class ps extends q{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
41
+ `),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class Cs extends q{constructor({docsPath:e,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:e,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function Eh({chain:t,currentChainId:e}){if(!t)throw new tS;if(e!==t.id)throw new eS({chain:t,currentChainId:e})}async function Sh(t,{serializedTransaction:e}){return t.request({method:"eth_sendRawTransaction",params:[e]},{retryCount:0})}const Vu=new Gi(128);async function nu(t,e){var T,g,w,k;const{account:r=t.account,chain:n=t.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,type:p,value:m,...v}=e;if(typeof r>"u")throw new ps({docsPath:"/docs/actions/wallet/sendTransaction"});const S=r?Fe(r):null;try{Nn(e);const _=await(async()=>{if(e.to)return e.to;if(e.to!==null&&i&&i.length>0)return await qc({authorization:i[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`.")})})();if((S==null?void 0:S.type)==="json-rpc"||S===null){let O;n!==null&&(O=await ne(t,hs,"getChainId")({}),Eh({currentChainId:O,chain:n}));const B=(w=(g=(T=t.chain)==null?void 0:T.formatters)==null?void 0:g.transactionRequest)==null?void 0:w.format,$=(B||ds)({...qi(v,{format:B}),accessList:s,account:S,authorizationList:i,blobs:o,chainId:O,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,to:_,type:p,value:m},"sendTransaction"),j=Vu.get(t.uid),H=j?"wallet_sendTransaction":"eth_sendTransaction";try{return await t.request({method:H,params:[$]},{retryCount:0})}catch(G){if(j===!1)throw G;const ee=G;if(ee.name==="InvalidInputRpcError"||ee.name==="InvalidParamsRpcError"||ee.name==="MethodNotFoundRpcError"||ee.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[$]},{retryCount:0}).then(U=>(Vu.set(t.uid,!0),U)).catch(U=>{const X=U;throw X.name==="MethodNotFoundRpcError"||X.name==="MethodNotSupportedRpcError"?(Vu.set(t.uid,!1),ee):X});throw ee}}if((S==null?void 0:S.type)==="local"){const O=await ne(t,wa,"prepareTransactionRequest")({account:S,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,nonceManager:S.nonceManager,parameters:[...lh,"sidecars"],type:p,value:m,...v,to:_}),B=(k=n==null?void 0:n.serializers)==null?void 0:k.transaction,N=await S.signTransaction(O,{serializer:B});return await ne(t,Sh,"sendRawTransaction")({serializedTransaction:N})}throw(S==null?void 0:S.type)==="smart"?new Cs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Cs({docsPath:"/docs/actions/wallet/sendTransaction",type:S==null?void 0:S.type})}catch(_){throw _ instanceof Cs?_:Xc(_,{...e,account:S,chain:e.chain||void 0})}}async function Mi(t,e){return Mi.internal(t,nu,"sendTransaction",e)}(function(t){async function e(r,n,s,i){const{abi:o,account:a=r.account,address:c,args:u,dataSuffix:l,functionName:f,...h}=i;if(typeof a>"u")throw new ps({docsPath:"/docs/contract/writeContract"});const d=a?Fe(a):null,p=er({abi:o,args:u,functionName:f});try{return await ne(r,n,s)({data:`${p}${l?l.replace("0x",""):""}`,to:c,account:d,...h})}catch(m){throw Ls(m,{abi:o,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:f,sender:d==null?void 0:d.address})}}t.internal=e})(Mi||(Mi={}));function Ah({abi:t,address:e,client:r}){const n=r,[s,i]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],o=s!=null,a=i!=null,c={};let u=!1,l=!1,f=!1;for(const h of t)if(h.type==="function"?h.stateMutability==="view"||h.stateMutability==="pure"?u=!0:l=!0:h.type==="event"&&(f=!0),u&&l&&f)break;return o&&(u&&(c.read=new Proxy({},{get(h,d){return(...p)=>{const{args:m,options:v}=$a(p);return ne(s,hr,"readContract")({abi:t,address:e,functionName:d,args:m,...v})}}})),l&&(c.simulate=new Proxy({},{get(h,d){return(...p)=>{const{args:m,options:v}=$a(p);return ne(s,lg,"simulateContract")({abi:t,address:e,functionName:d,args:m,...v})}}})),f&&(c.createEventFilter=new Proxy({},{get(h,d){return(...p)=>{const m=t.find(T=>T.type==="event"&&T.name===d),{args:v,options:S}=Gu(p,m);return ne(s,Xd,"createContractEventFilter")({abi:t,address:e,eventName:d,args:v,...S})}}}),c.getEvents=new Proxy({},{get(h,d){return(...p)=>{const m=t.find(T=>T.type==="event"&&T.name===d),{args:v,options:S}=Gu(p,m);return ne(s,ph,"getContractEvents")({abi:t,address:e,eventName:d,args:v,...S})}}}),c.watchEvent=new Proxy({},{get(h,d){return(...p)=>{const m=t.find(T=>T.type==="event"&&T.name===d),{args:v,options:S}=Gu(p,m);return ne(s,fg,"watchContractEvent")({abi:t,address:e,eventName:d,args:v,...S})}}}))),a&&l&&(c.write=new Proxy({},{get(h,d){return(...p)=>{const{args:m,options:v}=$a(p);return ne(i,Mi,"writeContract")({abi:t,address:e,functionName:d,args:m,...v})}}})),(o||a)&&l&&(c.estimateGas=new Proxy({},{get(h,d){return(...p)=>{const{args:m,options:v}=$a(p);return ne(s??i,$b,"estimateContractGas")({abi:t,address:e,functionName:d,args:m,...v,account:v.account??i.account})}}})),c.address=e,c.abi=t,c}function $a(t){const e=t.length&&Array.isArray(t[0]),r=e?t[0]:[],n=(e?t[1]:t[0])??{};return{args:r,options:n}}function Gu(t,e){let r=!1;Array.isArray(t[0])?r=!0:t.length===1?r=e.inputs.some(i=>i.indexed):t.length===2&&(r=!0);const n=r?t[0]:void 0,s=(r?t[1]:t[0])??{};return{args:n,options:s}}class dS extends q{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}function xc(t,{delay:e=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((s,i)=>{const o=async({count:a=0}={})=>{const c=async({error:u})=>{const l=typeof e=="function"?e({count:a,error:u}):e;l&&await ed(l),o({count:a+1})};try{const u=await t();s(u)}catch(u){if(a<r&&await n({count:a,error:u}))return c({error:u});i(u)}};o()})}const dg={"0x0":"reverted","0x1":"success"};function kh(t,e){const r={...t,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,contractAddress:t.contractAddress?t.contractAddress:null,cumulativeGasUsed:t.cumulativeGasUsed?BigInt(t.cumulativeGasUsed):null,effectiveGasPrice:t.effectiveGasPrice?BigInt(t.effectiveGasPrice):null,gasUsed:t.gasUsed?BigInt(t.gasUsed):null,logs:t.logs?t.logs.map(n=>_n(n)):null,to:t.to?t.to:null,transactionIndex:t.transactionIndex?dr(t.transactionIndex):null,status:t.status?dg[t.status]:null,type:t.type?Tb[t.type]||t.type:null};return t.blobGasPrice&&(r.blobGasPrice=BigInt(t.blobGasPrice)),t.blobGasUsed&&(r.blobGasUsed=BigInt(t.blobGasUsed)),r}const hS=Qd("transactionReceipt",kh),hg="0x5792579257925792579257925792579257925792579257925792579257925792",pg=J(0,{size:32});async function yg(t,e){const{account:r=t.account,capabilities:n,chain:s=t.chain,experimental_fallback:i,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:u="2.0.0"}=e,l=r?Fe(r):null,f=e.calls.map(h=>{const d=h,p=d.abi?er({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&p?Jt([p,d.dataSuffix]):p,to:d.to,value:d.value?J(d.value):void 0}});try{const h=await t.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:f,capabilities:n,chainId:J(s.id),from:l==null?void 0:l.address,id:c,version:u}]},{retryCount:0});return typeof h=="string"?{id:h}:h}catch(h){const d=h;if(i&&(d.name==="MethodNotFoundRpcError"||d.name==="MethodNotSupportedRpcError"||d.name==="UnknownRpcError"||d.details.toLowerCase().includes("does not exist / is not available")||d.details.toLowerCase().includes("missing or invalid. request()")||d.details.toLowerCase().includes("did not match any variant of untagged enum")||d.details.toLowerCase().includes("account upgraded to unsupported contract")||d.details.toLowerCase().includes("eip-7702 not supported")||d.details.toLowerCase().includes("unsupported wc_ method")||d.details.toLowerCase().includes("feature toggled misconfigured")||d.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(n&&Object.values(n).some(T=>!T.optional)){const T="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new Ni(new q(T,{details:T}))}if(a&&f.length>1){const S="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Ri(new q(S,{details:S}))}const p=[];for(const S of f){const T=nu(t,{account:l,chain:s,data:S.data,to:S.to,value:S.value?ot(S.value):void 0});p.push(T),o>0&&await new Promise(g=>setTimeout(g,o))}const m=await Promise.allSettled(p);if(m.every(S=>S.status==="rejected"))throw m[0].reason;const v=m.map(S=>S.status==="fulfilled"?S.value:pg);return{id:Jt([...v,J(s.id,{size:32}),hg])}}throw Xc(h,{...e,account:l,chain:e.chain})}}async function mg(t,e){async function r(l){if(l.endsWith(hg.slice(2))){const h=fr(Ff(l,-64,-32)),d=Ff(l,0,-64).slice(2).match(/.{1,64}/g),p=await Promise.all(d.map(v=>pg.slice(2)!==v?t.request({method:"eth_getTransactionReceipt",params:[`0x${v}`]},{dedupe:!0}):void 0)),m=p.some(v=>v===null)?100:p.every(v=>(v==null?void 0:v.status)==="0x1")?200:p.every(v=>(v==null?void 0:v.status)==="0x0")?500:600;return{atomic:!1,chainId:dr(h),receipts:p.filter(Boolean),status:m,version:"2.0.0"}}return t.request({method:"wallet_getCallsStatus",params:[l]})}const{atomic:n=!1,chainId:s,receipts:i,version:o="2.0.0",...a}=await r(e.id),[c,u]=(()=>{const l=a.status;return l>=100&&l<200?["pending",l]:l>=200&&l<300?["success",l]:l>=300&&l<700?["failure",l]:l==="CONFIRMED"?["success",200]:l==="PENDING"?["pending",100]:[void 0,l]})();return{...a,atomic:n,chainId:s?dr(s):void 0,receipts:(i==null?void 0:i.map(l=>({...l,blockNumber:ot(l.blockNumber),gasUsed:ot(l.gasUsed),status:dg[l.status]})))??[],statusCode:u,status:c,version:o}}async function bg(t,e){const{id:r,pollingInterval:n=t.pollingInterval,status:s=({statusCode:m})=>m===200||m>=300,retryCount:i=4,retryDelay:o=({count:m})=>~~(1<<m)*200,timeout:a=6e4,throwOnFailure:c=!1}=e,u=Ye(["waitForCallsStatus",t.uid,r]),{promise:l,resolve:f,reject:h}=vh();let d;const p=Pn(u,{resolve:f,reject:h},m=>{const v=Xi(async()=>{const S=T=>{clearTimeout(d),v(),T(),p()};try{const T=await xc(async()=>{const g=await ne(t,mg,"getCallsStatus")({id:r});if(c&&g.status==="failure")throw new dS(g);return g},{retryCount:i,delay:o});if(!s(T))return;S(()=>m.resolve(T))}catch(T){S(()=>m.reject(T))}},{interval:n,emitOnBegin:!0});return v});return d=a?setTimeout(()=>{p(),clearTimeout(d),h(new pS({id:r}))},a):void 0,await l}class pS extends q{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const td=256;let La=td,Da;function gg(t=11){if(!Da||La+t>td*2){Da="",La=0;for(let e=0;e<td;e++)Da+=(256+Math.random()*256|0).toString(16).substring(1)}return Da.substring(La,La+++t)}function wg(t){const{batch:e,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:o="base"}=t,a=t.experimental_blockTag??(typeof(r==null?void 0:r.experimental_preconfirmationTime)=="number"?"pending":void 0),c=(r==null?void 0:r.blockTime)??12e3,u=Math.min(Math.max(Math.floor(c/2),500),4e3),l=t.pollingInterval??u,f=t.cacheTime??l,h=t.account?Fe(t.account):void 0,{config:d,request:p,value:m}=t.transport({account:h,chain:r,pollingInterval:l}),v={...d,...m},S={account:h,batch:e,cacheTime:f,ccipRead:n,chain:r,key:s,name:i,pollingInterval:l,request:p,transport:v,type:o,uid:gg(),...a?{experimental_blockTag:a}:{}};function T(g){return w=>{const k=w(g);for(const O in S)delete k[O];const _={...g,...k};return Object.assign(_,{extend:T(_)})}}return Object.assign(S,{extend:T(S)})}function xh(t){var r,n,s,i,o,a;if(!(t instanceof q))return!1;const e=t.walk(c=>c instanceof Df);return e instanceof Df?((r=e.data)==null?void 0:r.errorName)==="HttpError"||((n=e.data)==null?void 0:n.errorName)==="ResolverError"||((s=e.data)==null?void 0:s.errorName)==="ResolverNotContract"||((i=e.data)==null?void 0:i.errorName)==="ResolverNotFound"||((o=e.data)==null?void 0:o.errorName)==="ReverseAddressMismatch"||((a=e.data)==null?void 0:a.errorName)==="UnsupportedResolverProfile":!1}function yS(t){const{abi:e,data:r}=t,n=Fs(r,0,4),s=e.find(i=>i.type==="function"&&n===ha(Tr(i)));if(!s)throw new o6(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?ya(s.inputs,Fs(r,4)):void 0}}const qu="/docs/contract/encodeErrorResult";function s0(t){const{abi:e,errorName:r,args:n}=t;let s=e[0];if(r){const c=Ys({abi:e,args:n,name:r});if(!c)throw new Pp(r,{docsPath:qu});s=c}if(s.type!=="error")throw new Pp(void 0,{docsPath:qu});const i=Tr(s),o=ha(i);let a="0x";if(n&&n.length>0){if(!s.inputs)throw new n6(s.name,{docsPath:qu});a=fs(s.inputs,n)}return Nr([o,a])}const Wu="/docs/contract/encodeFunctionResult";function mS(t){const{abi:e,functionName:r,result:n}=t;let s=e[0];if(r){const o=Ys({abi:e,name:r});if(!o)throw new Ii(r,{docsPath:Wu});s=o}if(s.type!=="function")throw new Ii(void 0,{docsPath:Wu});if(!s.outputs)throw new Lm(s.name,{docsPath:Wu});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Dm(n)})();return fs(s.outputs,i)}const xa="x-batch-gateway:true";async function vg(t){const{data:e,ccipRequest:r}=t,{args:[n]}=yS({abi:Zf,data:e}),s=[],i=[];return await Promise.all(n.map(async(o,a)=>{try{i[a]=o.urls.includes(xa)?await vg({data:o.data,ccipRequest:r}):await r(o),s[a]=!1}catch(c){s[a]=!0,i[a]=bS(c)}})),mS({abi:Zf,functionName:"query",result:[s,i]})}function bS(t){return t.name==="HttpRequestError"&&t.status?s0({abi:Zf,errorName:"HttpError",args:[t.status,t.shortMessage]}):s0({abi:[fb],errorName:"Error",args:["shortMessage"in t?t.shortMessage:t.message]})}function Eg(t){if(t.length!==66||t.indexOf("[")!==0||t.indexOf("]")!==65)return null;const e=`0x${t.slice(1,65)}`;return _r(e)?e:null}function rd(t){let e=new Uint8Array(32).fill(0);if(!t)return Je(e);const r=t.split(".");for(let n=r.length-1;n>=0;n-=1){const s=Eg(r[n]),i=s?Vi(s):dt(Is(r[n]),"bytes");e=dt(Jt([e,i]),"bytes")}return Je(e)}function gS(t){return`[${t.slice(2)}]`}function wS(t){const e=new Uint8Array(32).fill(0);return t?Eg(t)||dt(Is(t)):Je(e)}function Th(t){const e=t.replace(/^\.|\.$/gm,"");if(e.length===0)return new Uint8Array(1);const r=new Uint8Array(Is(e).byteLength+2);let n=0;const s=e.split(".");for(let i=0;i<s.length;i++){let o=Is(s[i]);o.byteLength>255&&(o=Is(gS(wS(s[i])))),r[n]=o.length,r.set(o,n+1),n+=o.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}async function vS(t,e){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ki({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c==null?void 0:c.ensTlds;if(l&&!l.some(h=>i.endsWith(h)))return null;const f=s!=null?[rd(i),BigInt(s)]:[rd(i)];try{const h=er({abi:t0,functionName:"addr",args:f}),d={address:u,abi:ng,functionName:"resolveWithGateways",args:[Ot(Th(i)),h,o??[xa]],blockNumber:r,blockTag:n},m=await ne(t,hr,"readContract")(d);if(m[0]==="0x")return null;const v=Js({abi:t0,args:f,functionName:"addr",data:m[0]});return v==="0x"||fr(v)==="0x00"?null:v}catch(h){if(a)throw h;if(xh(h))return null;throw h}}class ES extends q{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class to extends q{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class _h extends q{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class SS extends q{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const AS=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,kS=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,xS=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,TS=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function _S(t){try{const e=await fetch(t,{method:"HEAD"});if(e.status===200){const r=e.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(e){return typeof e=="object"&&typeof e.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=t})}}function i0(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:e}function Sg({uri:t,gatewayUrls:e}){const r=xS.test(t);if(r)return{uri:t,isOnChain:!0,isEncoded:r};const n=i0(e==null?void 0:e.ipfs,"https://ipfs.io"),s=i0(e==null?void 0:e.arweave,"https://arweave.net"),i=t.match(AS),{protocol:o,subpath:a,target:c,subtarget:u=""}=(i==null?void 0:i.groups)||{},l=o==="ipns:/"||a==="ipns/",f=o==="ipfs:/"||a==="ipfs/"||kS.test(t);if(t.startsWith("http")&&!l&&!f){let d=t;return e!=null&&e.arweave&&(d=t.replace(/https:\/\/arweave.net/g,e==null?void 0:e.arweave)),{uri:d,isOnChain:!1,isEncoded:!1}}if((l||f)&&c)return{uri:`${n}/${l?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${s}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let h=t.replace(TS,"");if(h.startsWith("<svg")&&(h=`data:image/svg+xml;base64,${btoa(h)}`),h.startsWith("data:")||h.startsWith("{"))return{uri:h,isOnChain:!0,isEncoded:!1};throw new _h({uri:t})}function Ag(t){if(typeof t!="object"||!("image"in t)&&!("image_url"in t)&&!("image_data"in t))throw new ES({data:t});return t.image||t.image_url||t.image_data}async function PS({gatewayUrls:t,uri:e}){try{const r=await fetch(e).then(s=>s.json());return await Ph({gatewayUrls:t,uri:Ag(r)})}catch{throw new _h({uri:e})}}async function Ph({gatewayUrls:t,uri:e}){const{uri:r,isOnChain:n}=Sg({uri:e,gatewayUrls:t});if(n||await _S(r))return r;throw new _h({uri:e})}function OS(t){let e=t;e.startsWith("did:nft:")&&(e=e.replace("did:nft:","").replace(/_/g,"/"));const[r,n,s]=e.split("/"),[i,o]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new to({reason:"Only EIP-155 supported"});if(!o)throw new to({reason:"Chain ID not found"});if(!c)throw new to({reason:"Contract address not found"});if(!s)throw new to({reason:"Token ID not found"});if(!a)throw new to({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:s}}async function IS(t,{nft:e}){if(e.namespace==="erc721")return hr(t,{address:e.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(e.tokenID)]});if(e.namespace==="erc1155")return hr(t,{address:e.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(e.tokenID)]});throw new SS({namespace:e.namespace})}async function BS(t,{gatewayUrls:e,record:r}){return/eip155:/i.test(r)?CS(t,{gatewayUrls:e,record:r}):Ph({uri:r,gatewayUrls:e})}async function CS(t,{gatewayUrls:e,record:r}){const n=OS(r),s=await IS(t,{nft:n}),{uri:i,isOnChain:o,isEncoded:a}=Sg({uri:s,gatewayUrls:e});if(o&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const u=a?atob(i.replace("data:application/json;base64,","")):i,l=JSON.parse(u);return Ph({uri:Ag(l),gatewayUrls:e})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),PS({gatewayUrls:e,uri:i.replace(/(?:0x)?{id}/,c)})}async function kg(t,e){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ki({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c==null?void 0:c.ensTlds;if(l&&!l.some(f=>i.endsWith(f)))return null;try{const f={address:u,abi:ng,args:[Ot(Th(i)),er({abi:e0,functionName:"text",args:[rd(i),s]}),o??[xa]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},d=await ne(t,hr,"readContract")(f);if(d[0]==="0x")return null;const p=Js({abi:e0,functionName:"text",data:d[0]});return p===""?null:p}catch(f){if(a)throw f;if(xh(f))return null;throw f}}async function NS(t,{blockNumber:e,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:o,universalResolverAddress:a}){const c=await ne(t,kg,"getEnsText")({blockNumber:e,blockTag:r,key:"avatar",name:s,universalResolverAddress:a,gatewayUrls:i,strict:o});if(!c)return null;try{return await BS(t,{record:c,gatewayUrls:n})}catch{return null}}async function RS(t,e){const{address:r,blockNumber:n,blockTag:s,coinType:i=60n,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ki({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{const l={address:u,abi:YE,args:[r,i,o??[xa]],functionName:"reverseWithGateways",blockNumber:n,blockTag:s},f=ne(t,hr,"readContract"),[h]=await f(l);return h||null}catch(l){if(a)throw l;if(xh(l))return null;throw l}}async function MS(t,e){const{blockNumber:r,blockTag:n,name:s}=e,{chain:i}=t,o=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!i)throw new Error("client chain not configured. universalResolverAddress is required.");return Ki({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i==null?void 0:i.ensTlds;if(a&&!a.some(u=>s.endsWith(u)))throw new Error(`${s} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);const[c]=await ne(t,hr,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Ot(Th(s))],blockNumber:r,blockTag:n});return c}async function xg(t,e){var v,S,T;const{account:r=t.account,blockNumber:n,blockTag:s="latest",blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:f,to:h,value:d,...p}=e,m=r?Fe(r):void 0;try{Nn(e);const w=(typeof n=="bigint"?J(n):void 0)||s,k=(T=(S=(v=t.chain)==null?void 0:v.formatters)==null?void 0:S.transactionRequest)==null?void 0:T.format,O=(k||ds)({...qi(p,{format:k}),account:m,blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:f,to:h,value:d},"createAccessList"),B=await t.request({method:"eth_createAccessList",params:[O,w]});return{accessList:B.accessList,gasUsed:BigInt(B.gasUsed)}}catch(g){throw ag(g,{...e,account:m,chain:t.chain})}}async function jS(t){const e=zc(t,{method:"eth_newBlockFilter"}),r=await t.request({method:"eth_newBlockFilter"});return{id:r,request:e(r),type:"block"}}async function Tg(t,{address:e,args:r,event:n,events:s,fromBlock:i,strict:o,toBlock:a}={}){const c=s??(n?[n]:void 0),u=zc(t,{method:"eth_newFilter"});let l=[];c&&(l=[c.flatMap(d=>pa({abi:[d],eventName:d.name,args:r}))],n&&(l=l[0]));const f=await t.request({method:"eth_newFilter",params:[{address:e,fromBlock:typeof i=="bigint"?J(i):i,toBlock:typeof a=="bigint"?J(a):a,...l.length?{topics:l}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:f,request:u(f),strict:!!o,toBlock:a,type:"event"}}async function _g(t){const e=zc(t,{method:"eth_newPendingTransactionFilter"}),r=await t.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:e(r),type:"transaction"}}async function US(t,{address:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?J(r):void 0,i=await t.request({method:"eth_getBalance",params:[e,s||n]});return BigInt(i)}async function FS(t){const e=await t.request({method:"eth_blobBaseFee"});return BigInt(e)}async function $S(t,{blockHash:e,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?J(r):void 0;let i;return e?i=await t.request({method:"eth_getBlockTransactionCountByHash",params:[e]},{dedupe:!0}):i=await t.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),dr(i)}async function nd(t,{address:e,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?J(r):void 0,i=await t.request({method:"eth_getCode",params:[e,s||n]},{dedupe:!!s});if(i!=="0x")return i}class LS extends q{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function DS(t,e){const{address:r,factory:n,factoryData:s}=e;try{const[i,o,a,c,u,l,f]=await ne(t,hr,"readContract")({abi:HS,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:u,salt:l},extensions:f,fields:i}}catch(i){const o=i;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new LS({address:r}):o}}const HS=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];function zS(t){var e;return{baseFeePerGas:t.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:t.gasUsedRatio,oldestBlock:BigInt(t.oldestBlock),reward:(e=t.reward)==null?void 0:e.map(r=>r.map(n=>BigInt(n)))}}async function VS(t,{blockCount:e,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?J(r):void 0,o=await t.request({method:"eth_feeHistory",params:[J(e),i||n,s]},{dedupe:!!i});return zS(o)}async function GS(t,{filter:e}){const r=e.strict??!1,s=(await e.request({method:"eth_getFilterLogs",params:[e.id]})).map(i=>_n(i));return e.abi?dh({abi:e.abi,logs:s,strict:r}):s}function qS(t){const{authorizationList:e}=t;if(e)for(const r of e){const{chainId:n}=r,s=r.address;if(!st(s))throw new Bt({address:s});if(n<0)throw new Qc({chainId:n})}Oh(t)}function WS(t){const{blobVersionedHashes:e}=t;if(e){if(e.length===0)throw new jb;for(const r of e){const n=He(r),s=dr(Fs(r,0,1));if(n!==32)throw new hE({hash:r,size:n});if(s!==Mb)throw new pE({hash:r,version:s})}}Oh(t)}function Oh(t){const{chainId:e,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=t;if(e<=0)throw new Qc({chainId:e});if(s&&!st(s))throw new Bt({address:s});if(n&&n>Kc)throw new Ds({maxFeePerGas:n});if(r&&n&&r>n)throw new Xo({maxFeePerGas:n,maxPriorityFeePerGas:r})}function KS(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(e<=0)throw new Qc({chainId:e});if(i&&!st(i))throw new Bt({address:i});if(r||s)throw new q("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Kc)throw new Ds({maxFeePerGas:n})}function XS(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(i&&!st(i))throw new Bt({address:i});if(typeof e<"u"&&e<=0)throw new Qc({chainId:e});if(r||s)throw new q("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Kc)throw new Ds({maxFeePerGas:n})}function su(t){if(!t||t.length===0)return[];const e=[];for(let r=0;r<t.length;r++){const{address:n,storageKeys:s}=t[r];for(let i=0;i<s.length;i++)if(s[i].length-2!==64)throw new B5({storageKey:s[i]});if(!st(n,{strict:!1}))throw new Bt({address:n});e.push([n,s])}return e}function YS(t,e){const r=Fb(t);return r==="eip1559"?QS(t,e):r==="eip2930"?eA(t,e):r==="eip4844"?ZS(t,e):r==="eip7702"?JS(t,e):tA(t,e)}function JS(t,e){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:f}=t;qS(t);const h=su(l),d=rA(r);return Nr(["0x04",cs([J(n),i?J(i):"0x",u?J(u):"0x",c?J(c):"0x",s?J(s):"0x",o??"0x",a?J(a):"0x",f??"0x",h,d,...Ta(t,e)])])}function ZS(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:f}=t;WS(t);let h=t.blobVersionedHashes,d=t.sidecars;if(t.blobs&&(typeof h>"u"||typeof d>"u")){const g=typeof t.blobs[0]=="string"?t.blobs:t.blobs.map(_=>Je(_)),w=t.kzg,k=ih({blobs:g,kzg:w});if(typeof h>"u"&&(h=Cb({commitments:k})),typeof d>"u"){const _=oh({blobs:g,commitments:k,kzg:w});d=Ub({blobs:g,commitments:k,proofs:_})}}const p=su(l),m=[J(r),s?J(s):"0x",u?J(u):"0x",c?J(c):"0x",n?J(n):"0x",i??"0x",o?J(o):"0x",f??"0x",p,a?J(a):"0x",h??[],...Ta(t,e)],v=[],S=[],T=[];if(d)for(let g=0;g<d.length;g++){const{blob:w,commitment:k,proof:_}=d[g];v.push(w),S.push(k),T.push(_)}return Nr(["0x03",cs(d?[m,v,S,T]:m)])}function QS(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:u,data:l}=t;Oh(t);const f=su(u),h=[J(r),s?J(s):"0x",c?J(c):"0x",a?J(a):"0x",n?J(n):"0x",i??"0x",o?J(o):"0x",l??"0x",f,...Ta(t,e)];return Nr(["0x02",cs(h)])}function eA(t,e){const{chainId:r,gas:n,data:s,nonce:i,to:o,value:a,accessList:c,gasPrice:u}=t;KS(t);const l=su(c),f=[J(r),i?J(i):"0x",u?J(u):"0x",n?J(n):"0x",o??"0x",a?J(a):"0x",s??"0x",l,...Ta(t,e)];return Nr(["0x01",cs(f)])}function tA(t,e){const{chainId:r=0,gas:n,data:s,nonce:i,to:o,value:a,gasPrice:c}=t;XS(t);let u=[i?J(i):"0x",c?J(c):"0x",n?J(n):"0x",o??"0x",a?J(a):"0x",s??"0x"];if(e){const l=(()=>{if(e.v>=35n)return(e.v-35n)/2n>0?e.v:27n+(e.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+e.v-27n);const d=27n+(e.v===27n?0n:1n);if(e.v!==d)throw new O5({v:e.v});return d})(),f=fr(e.r),h=fr(e.s);u=[...u,J(l),f==="0x00"?"0x":f,h==="0x00"?"0x":h]}else r>0&&(u=[...u,J(r),"0x","0x"]);return cs(u)}function Ta(t,e){const r=e??t,{v:n,yParity:s}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof s>"u")return[];const i=fr(r.r),o=fr(r.s);return[typeof s=="number"?s?J(1):"0x":n===0n?"0x":n===1n?J(1):n===27n?"0x":J(1),i==="0x00"?"0x":i,o==="0x00"?"0x":o]}function rA(t){if(!t||t.length===0)return[];const e=[];for(const r of t){const{chainId:n,nonce:s,...i}=r,o=r.address;e.push([n?Ot(n):"0x",o,s?Ot(s):"0x",...Ta({},i)])}return e}async function nA({address:t,authorization:e,signature:r}){return Wi(Gd(t),await qc({authorization:e,signature:r}))}const Ha=new Gi(8192);function sA(t,{enabled:e=!0,id:r}){if(!e||!r)return t();if(Ha.get(r))return Ha.get(r);const n=t().finally(()=>Ha.delete(r));return Ha.set(r,n),n}function iA(t,e={}){return async(r,n={})=>{var f;const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...n},{method:u}=r;if((f=i==null?void 0:i.exclude)!=null&&f.includes(u))throw new As(new Error("method not supported"),{method:u});if(i!=null&&i.include&&!i.include.includes(u))throw new As(new Error("method not supported"),{method:u});const l=s?Bi(`${c}.${Ye(r)}`):void 0;return sA(()=>xc(async()=>{try{return await t(r)}catch(h){const d=h;switch(d.code){case Bo.code:throw new Bo(d);case Co.code:throw new Co(d);case No.code:throw new No(d,{method:r.method});case Ro.code:throw new Ro(d);case $s.code:throw new $s(d);case as.code:throw new as(d);case Mo.code:throw new Mo(d);case jo.code:throw new jo(d);case Uo.code:throw new Uo(d);case As.code:throw new As(d,{method:r.method});case Ci.code:throw new Ci(d);case Fo.code:throw new Fo(d);case Ei.code:throw new Ei(d);case $o.code:throw new $o(d);case Lo.code:throw new Lo(d);case Do.code:throw new Do(d);case Ho.code:throw new Ho(d);case zo.code:throw new zo(d);case Ni.code:throw new Ni(d);case Vo.code:throw new Vo(d);case Go.code:throw new Go(d);case qo.code:throw new qo(d);case Wo.code:throw new Wo(d);case Ko.code:throw new Ko(d);case Ri.code:throw new Ri(d);case 5e3:throw new Ei(d);default:throw h instanceof q?h:new F5(d)}}},{delay:({count:h,error:d})=>{var p;if(d&&d instanceof vi){const m=(p=d==null?void 0:d.headers)==null?void 0:p.get("Retry-After");if(m!=null&&m.match(/\d/))return Number.parseInt(m,10)*1e3}return~~(1<<h)*o},retryCount:a,shouldRetry:({error:h})=>oA(h)}),{enabled:s,id:l})}}function oA(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Ci.code||t.code===$s.code:t instanceof vi&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function ht(t){const e={formatters:void 0,fees:void 0,serializers:void 0,...t};function r(n){return s=>{const i=typeof s=="function"?s(n):s,o={...n,...i};return Object.assign(o,{extend:r(o)})}}return Object.assign(e,{extend:r(e)})}const aA=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Pg=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),cA=Pg.map(t=>(9*t+5)%16),Og=(()=>{const r=[[Pg],[cA]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>aA[i]));return r})(),Ig=Og[0],Bg=Og[1],Cg=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),uA=Ig.map((t,e)=>t.map(r=>Cg[e][r])),lA=Bg.map((t,e)=>t.map(r=>Cg[e][r])),fA=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),dA=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function o0(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const za=new Uint32Array(16);let Ng=class extends Pb{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let d=0;d<16;d++,r+=4)za[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,u=this.h3|0,l=u,f=this.h4|0,h=f;for(let d=0;d<5;d++){const p=4-d,m=fA[d],v=dA[d],S=Ig[d],T=Bg[d],g=uA[d],w=lA[d];for(let k=0;k<16;k++){const _=Ua(n+o0(d,i,a,u)+za[S[k]]+m,g[k])+f|0;n=f,f=u,u=Ua(a,10)|0,a=i,i=_}for(let k=0;k<16;k++){const _=Ua(s+o0(p,o,c,l)+za[T[k]]+v,w[k])+h|0;s=h,h=l,l=Ua(c,10)|0,c=o,o=_}}this.set(this.h1+a+l|0,this.h2+u+h|0,this.h3+f+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){Pr(za)}destroy(){this.destroyed=!0,Pr(this.buffer),this.set(0,0,0,0,0)}};const hA=Dc(()=>new Ng),pA=Ng,yA=hA,mA=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:pA,ripemd160:yA},Symbol.toStringTag,{value:"Module"}));function bA(t,{errorInstance:e=new Error("timed out"),timeout:r,signal:n}){return new Promise((s,i)=>{(async()=>{let o;try{const a=new AbortController;r>0&&(o=setTimeout(()=>{n&&a.abort()},r)),s(await t({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&i(e),i(a)}finally{clearTimeout(o)}})()})}function gA(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const a0=gA();function wA(t,e={}){return{async request(r){var h;const{body:n,fetchFn:s=e.fetchFn??fetch,onRequest:i=e.onRequest,onResponse:o=e.onResponse,timeout:a=e.timeout??1e4}=r,c={...e.fetchOptions??{},...r.fetchOptions??{}},{headers:u,method:l,signal:f}=c;try{const d=await bA(async({signal:m})=>{const v={...c,body:Array.isArray(n)?Ye(n.map(w=>({jsonrpc:"2.0",id:w.id??a0.take(),...w}))):Ye({jsonrpc:"2.0",id:n.id??a0.take(),...n}),headers:{"Content-Type":"application/json",...u},method:l||"POST",signal:f||(a>0?m:null)},S=new Request(t,v),T=await(i==null?void 0:i(S,v))??{...v,url:t};return await s(T.url??t,T)},{errorInstance:new Dp({body:n,url:t}),timeout:a,signal:!0});o&&await o(d);let p;if((h=d.headers.get("Content-Type"))!=null&&h.startsWith("application/json"))p=await d.json();else{p=await d.text();try{p=JSON.parse(p||"{}")}catch(m){if(d.ok)throw m;p={error:p}}}if(!d.ok)throw new vi({body:n,details:Ye(p.error)||d.statusText,headers:d.headers,status:d.status,url:t});return p}catch(d){throw d instanceof vi||d instanceof Dp?d:new vi({body:n,cause:d,url:t})}}}}const vA=`Ethereum Signed Message:
42
+ `;function EA(t){const e=typeof t=="string"?Bi(t):typeof t.raw=="string"?t.raw:Je(t.raw),r=Bi(`${vA}${He(e)}`);return Jt([r,e])}function Rg(t,e){return dt(EA(t),e)}class SA extends q{constructor({domain:e}){super(`Invalid domain "${Ye(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class AA extends q{constructor({primaryType:e,types:r}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class kA extends q{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function xA(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(c,u)=>{const l={...u};for(const f of c){const{name:h,type:d}=f;d==="address"&&(l[h]=l[h].toLowerCase())}return l},o=s.EIP712Domain?e?i(s.EIP712Domain,e):{}:{},a=(()=>{if(n!=="EIP712Domain")return i(s[n],r)})();return Ye({domain:o,message:a,primaryType:n,types:s})}function Mg(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(o,a)=>{for(const c of o){const{name:u,type:l}=c,f=a[u],h=l.match(ub);if(h&&(typeof f=="number"||typeof f=="bigint")){const[m,v,S]=h;J(f,{signed:v==="int",size:Number.parseInt(S,10)/8})}if(l==="address"&&typeof f=="string"&&!st(f))throw new Bt({address:f});const d=l.match(e5);if(d){const[m,v]=d;if(v&&He(f)!==Number.parseInt(v,10))throw new c6({expectedSize:Number.parseInt(v,10),givenSize:He(f)})}const p=s[l];p&&(TA(l),i(p,f))}};if(s.EIP712Domain&&e){if(typeof e!="object")throw new SA({domain:e});i(s.EIP712Domain,e)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new AA({primaryType:n,types:s})}function jg({domain:t}){return[typeof(t==null?void 0:t.name)=="string"&&{name:"name",type:"string"},(t==null?void 0:t.version)&&{name:"version",type:"string"},(typeof(t==null?void 0:t.chainId)=="number"||typeof(t==null?void 0:t.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(t==null?void 0:t.verifyingContract)&&{name:"verifyingContract",type:"address"},(t==null?void 0:t.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function TA(t){if(t==="address"||t==="bool"||t==="string"||t.startsWith("bytes")||t.startsWith("uint")||t.startsWith("int"))throw new kA({type:t})}function _A(t){const{domain:e={},message:r,primaryType:n}=t,s={EIP712Domain:jg({domain:e}),...t.types};Mg({domain:e,message:r,primaryType:n,types:s});const i=["0x1901"];return e&&i.push(PA({domain:e,types:s})),n!=="EIP712Domain"&&i.push(Ug({data:r,primaryType:n,types:s})),dt(Jt(i))}function PA({domain:t,types:e}){return Ug({data:t,primaryType:"EIP712Domain",types:e})}function Ug({data:t,primaryType:e,types:r}){const n=Fg({data:t,primaryType:e,types:r});return dt(n)}function Fg({data:t,primaryType:e,types:r}){const n=[{type:"bytes32"}],s=[OA({primaryType:e,types:r})];for(const i of r[e]){const[o,a]=Lg({types:r,name:i.name,type:i.type,value:t[i.name]});n.push(o),s.push(a)}return fs(n,s)}function OA({primaryType:t,types:e}){const r=Ot(IA({primaryType:t,types:e}));return dt(r)}function IA({primaryType:t,types:e}){let r="";const n=$g({primaryType:t,types:e});n.delete(t);const s=[t,...Array.from(n).sort()];for(const i of s)r+=`${i}(${e[i].map(({name:o,type:a})=>`${a} ${o}`).join(",")})`;return r}function $g({primaryType:t,types:e},r=new Set){const n=t.match(/^\w*/u),s=n==null?void 0:n[0];if(r.has(s)||e[s]===void 0)return r;r.add(s);for(const i of e[s])$g({primaryType:i.type,types:e},r);return r}function Lg({types:t,name:e,type:r,value:n}){if(t[r]!==void 0)return[{type:"bytes32"},dt(Fg({data:n,primaryType:r,types:t}))];if(r==="bytes")return[{type:"bytes32"},dt(n)];if(r==="string")return[{type:"bytes32"},dt(Ot(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(o=>Lg({name:e,type:s,types:t,value:o}));return[{type:"bytes32"},dt(fs(i.map(([o])=>o),i.map(([,o])=>o)))]}return[{type:r},n]}class BA extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const CA={checksum:new BA(8192)},Ku=CA.checksum;function Dg(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=sb(IE(t));return r==="Bytes"?n:Ir(n)}const NA=/^0x[a-fA-F0-9]{40}$/;function iu(t,e={}){const{strict:r=!0}=e;if(!NA.test(t))throw new c0({address:t,cause:new RA});if(r){if(t.toLowerCase()===t)return;if(Hg(t)!==t)throw new c0({address:t,cause:new MA})}}function Hg(t){if(Ku.has(t))return Ku.get(t);iu(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=Dg(CE(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)r[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(r[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const s=`0x${n.join("")}`;return Ku.set(t,s),s}function sd(t,e={}){const{strict:r=!0}=e??{};try{return iu(t,{strict:r}),!0}catch{return!1}}class c0 extends le{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class RA 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"})}}class MA extends le{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const jA=/^(.*)\[([0-9]*)\]$/,UA=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,zg=/^(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)?$/,u0=2n**256n-1n;function Ai(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=Ch(e.type);if(i){const[o,a]=i;return $A(t,{...e,type:a},{checksumAddress:n,length:o,staticPosition:s})}if(e.type==="tuple")return zA(t,e,{checksumAddress:n,staticPosition:s});if(e.type==="address")return FA(t,{checksum:n});if(e.type==="bool")return LA(t);if(e.type.startsWith("bytes"))return DA(t,e,{staticPosition:s});if(e.type.startsWith("uint")||e.type.startsWith("int"))return HA(t,e);if(e.type==="string")return VA(t,{staticPosition:s});throw new Rh(e.type)}const l0=32,id=32;function FA(t,e={}){const{checksum:r=!1}=e,n=t.readBytes(32);return[(i=>r?Hg(i):i)(Ir(RE(n,-20))),32]}function $A(t,e,r){const{checksumAddress:n,length:s,staticPosition:i}=r;if(!s){const c=kn(t.readBytes(id)),u=i+c,l=u+l0;t.setPosition(u);const f=kn(t.readBytes(l0)),h=Zo(e);let d=0;const p=[];for(let m=0;m<f;++m){t.setPosition(l+(h?m*32:d));const[v,S]=Ai(t,e,{checksumAddress:n,staticPosition:l});d+=S,p.push(v)}return t.setPosition(i+32),[p,32]}if(Zo(e)){const c=kn(t.readBytes(id)),u=i+c,l=[];for(let f=0;f<s;++f){t.setPosition(u+f*32);const[h]=Ai(t,e,{checksumAddress:n,staticPosition:u});l.push(h)}return t.setPosition(i+32),[l,32]}let o=0;const a=[];for(let c=0;c<s;++c){const[u,l]=Ai(t,e,{checksumAddress:n,staticPosition:i+o});o+=l,a.push(u)}return[a,o]}function LA(t){return[jE(t.readBytes(32),{size:32}),32]}function DA(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const o=kn(t.readBytes(32));t.setPosition(r+o);const a=kn(t.readBytes(32));if(a===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(a);return t.setPosition(r+32),[Ir(c),32]}return[Ir(t.readBytes(Number.parseInt(s,10),32)),32]}function HA(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?ME(s,{signed:r}):kn(s,{signed:r}),32]}function zA(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=e.components.length===0||e.components.some(({name:c})=>!c),o=i?[]:{};let a=0;if(Zo(e)){const c=kn(t.readBytes(id)),u=s+c;for(let l=0;l<e.components.length;++l){const f=e.components[l];t.setPosition(u+a);const[h,d]=Ai(t,f,{checksumAddress:n,staticPosition:u});a+=d,o[i?l:f==null?void 0:f.name]=h}return t.setPosition(s+32),[o,32]}for(let c=0;c<e.components.length;++c){const u=e.components[c],[l,f]=Ai(t,u,{checksumAddress:n,staticPosition:s});o[i?c:u==null?void 0:u.name]=l,a+=f}return[o,a]}function VA(t,{staticPosition:e}){const r=kn(t.readBytes(32)),n=e+r;t.setPosition(n);const s=kn(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),o=UE(Xb(i));return t.setPosition(e+32),[o,32]}function GA({checksumAddress:t,parameters:e,values:r}){const n=[];for(let s=0;s<e.length;s++)n.push(Ih({checksumAddress:t,parameter:e[s],value:r[s]}));return n}function Ih({checksumAddress:t=!1,parameter:e,value:r}){const n=e,s=Ch(n.type);if(s){const[i,o]=s;return WA(r,{checksumAddress:t,length:i,parameter:{...n,type:o}})}if(n.type==="tuple")return ZA(r,{checksumAddress:t,parameter:n});if(n.type==="address")return qA(r,{checksum:t});if(n.type==="bool")return XA(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,o="256"]=zg.exec(n.type)??[];return YA(r,{signed:i,size:Number(o)})}if(n.type.startsWith("bytes"))return KA(r,{type:n.type});if(n.type==="string")return JA(r);throw new Rh(n.type)}function Bh(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=Zt(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(_t(e+s,{size:32})),n.push(a),s+=Zt(a)):r.push(a)}return Or(...r,...n)}function qA(t,e){const{checksum:r=!1}=e;return iu(t,{strict:r}),{dynamic:!1,encoded:Hs(t.toLowerCase())}}function WA(t,e){const{checksumAddress:r,length:n,parameter:s}=e,i=n===null;if(!Array.isArray(t))throw new ak(t);if(!i&&t.length!==n)throw new ok({expectedLength:n,givenLength:t.length,type:`${s.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<t.length;c++){const u=Ih({checksumAddress:r,parameter:s,value:t[c]});u.dynamic&&(o=!0),a.push(u)}if(i||o){const c=Bh(a);if(i){const u=_t(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Or(u,c):u}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Or(...a.map(({encoded:c})=>c))}}function KA(t,{type:e}){const[,r]=e.split("bytes"),n=Zt(t);if(!r){let s=t;return n%32!==0&&(s=zs(s,Math.ceil((t.length-2)/2/32)*32)),{dynamic:!0,encoded:Or(Hs(_t(n,{size:32})),s)}}if(n!==Number.parseInt(r,10))throw new Gg({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:zs(t)}}function XA(t){if(typeof t!="boolean")throw new le(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Hs(Yb(t))}}function YA(t,{signed:e,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new Qb({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:_t(t,{size:32,signed:e})}}function JA(t){const e=gh(t),r=Math.ceil(Zt(e)/32),n=[];for(let s=0;s<r;s++)n.push(zs(Zr(e,s*32,(s+1)*32)));return{dynamic:!0,encoded:Or(zs(_t(Zt(e),{size:32})),...n)}}function ZA(t,e){const{checksumAddress:r,parameter:n}=e;let s=!1;const i=[];for(let o=0;o<n.components.length;o++){const a=n.components[o],c=Array.isArray(t)?o:a.name,u=Ih({checksumAddress:r,parameter:a,value:t[c]});i.push(u),u.dynamic&&(s=!0)}return{dynamic:s,encoded:s?Bh(i):Or(...i.map(({encoded:o})=>o))}}function Ch(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Zo(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(Zo);const r=Ch(t.type);return!!(r&&Zo({...t,type:r[1]}))}const QA={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 rk({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new tk({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new f0({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new f0({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function ek(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(QA);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}class f0 extends le{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class tk extends le{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class rk extends le{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function nk(t,e,r={}){const{as:n="Array",checksumAddress:s=!1}=r,i=typeof e=="string"?Kb(e):e,o=ek(i);if(bi(i)===0&&t.length>0)throw new ik;if(bi(i)&&bi(i)<32)throw new sk({data:typeof e=="string"?e:Ir(e),parameters:t,size:bi(i)});let a=0;const c=n==="Array"?[]:{};for(let u=0;u<t.length;++u){const l=t[u];o.setPosition(a);const[f,h]=Ai(o,l,{checksumAddress:s,staticPosition:0});a+=h,n==="Array"?c.push(f):c[l.name??u]=f}return c}function Nh(t,e,r){const{checksumAddress:n=!1}={};if(t.length!==e.length)throw new qg({expectedLength:t.length,givenLength:e.length});const s=GA({checksumAddress:n,parameters:t,values:e}),i=Bh(s);return i.length===0?"0x":i}function od(t,e){if(t.length!==e.length)throw new qg({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const s=t[n],i=e[n];r.push(od.encode(s,i))}return Or(...r)}(function(t){function e(r,n,s=!1){if(r==="address"){const c=n;return iu(c),Hs(c.toLowerCase(),s?32:0)}if(r==="string")return gh(n);if(r==="bytes")return n;if(r==="bool")return Hs(Yb(n),s?32:1);const i=r.match(zg);if(i){const[c,u,l="256"]=i,f=Number.parseInt(l,10)/8;return _t(n,{size:s?32:f,signed:u==="int"})}const o=r.match(UA);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new Gg({expectedSize:Number.parseInt(u,10),value:n});return zs(n,s?32:0)}const a=r.match(jA);if(a&&Array.isArray(n)){const[c,u]=a,l=[];for(let f=0;f<n.length;f++)l.push(e(u,n[f],!0));return l.length===0?"0x":Or(...l)}throw new Rh(r)}t.encode=e})(od||(od={}));function Vg(t){return Array.isArray(t)&&typeof t[0]=="string"||typeof t=="string"?Tp(t):t}class sk extends le{constructor({data:e,parameters:r,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${ci(r)})`,`Data: ${e} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class ik 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"})}}class ok extends le{constructor({expectedLength:e,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class Gg extends le{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${Zt(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class qg extends le{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
43
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class ak extends le{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class Rh extends le{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class Wg extends Lc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,N6(e);const n=Sn(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Pr(i)}update(e){return os(this),this.iHash.update(e),this}digestInto(e){os(this),is(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:s,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Kg=(t,e,r)=>new Wg(t,e).update(r).digest();Kg.create=(t,e)=>new Wg(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ft=BigInt(0),It=BigInt(1),ks=BigInt(2),ck=BigInt(3),Xg=BigInt(4),Yg=BigInt(5),Jg=BigInt(8);function Nt(t,e){const r=t%e;return r>=Ft?r:e+r}function nr(t,e,r){let n=t;for(;e-- >Ft;)n*=n,n%=r;return n}function ad(t,e){if(t===Ft)throw new Error("invert: expected non-zero number");if(e<=Ft)throw new Error("invert: expected positive modulus, got "+e);let r=Nt(t,e),n=e,s=Ft,i=It;for(;r!==Ft;){const a=n/r,c=n%r,u=s-i*a;n=r,r=c,s=i,i=u}if(n!==It)throw new Error("invert: does not exist");return Nt(s,e)}function Zg(t,e){const r=(t.ORDER+It)/Xg,n=t.pow(e,r);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function uk(t,e){const r=(t.ORDER-Yg)/Jg,n=t.mul(e,ks),s=t.pow(n,r),i=t.mul(e,s),o=t.mul(t.mul(i,ks),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function lk(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-It,r=0;for(;e%ks===Ft;)e/=ks,r++;let n=ks;const s=Mh(t);for(;d0(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Zg;let i=s.pow(n,e);const o=(e+It)/ks;return function(c,u){if(c.is0(u))return u;if(d0(c,u)!==1)throw new Error("Cannot find square root");let l=r,f=c.mul(c.ONE,i),h=c.pow(u,e),d=c.pow(u,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,m=c.sqr(h);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===l)throw new Error("Cannot find square root");const v=It<<BigInt(l-p-1),S=c.pow(f,v);l=p,f=c.sqr(S),h=c.mul(h,f),d=c.mul(d,S)}return d}}function fk(t){return t%Xg===ck?Zg:t%Jg===Yg?uk:lk(t)}const dk=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hk(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=dk.reduce((n,s)=>(n[s]="function",n),e);return Jc(t,r)}function pk(t,e,r){if(r<Ft)throw new Error("invalid exponent, negatives unsupported");if(r===Ft)return t.ONE;if(r===It)return e;let n=t.ONE,s=e;for(;r>Ft;)r&It&&(n=t.mul(n,s)),s=t.sqr(s),r>>=It;return n}function Qg(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function d0(t,e){const r=(t.ORDER-It)/ks,n=t.pow(e,r),s=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function ew(t,e){e!==void 0&&ss(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Mh(t,e,r=!1,n={}){if(t<=Ft)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=ew(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:i,MASK:Yc(s),ZERO:Ft,ONE:It,create:c=>Nt(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ft<=c&&c<t},is0:c=>c===Ft,isOdd:c=>(c&It)===It,neg:c=>Nt(-c,t),eql:(c,u)=>c===u,sqr:c=>Nt(c*c,t),add:(c,u)=>Nt(c+u,t),sub:(c,u)=>Nt(c-u,t),mul:(c,u)=>Nt(c*u,t),pow:(c,u)=>pk(a,c,u),div:(c,u)=>Nt(c*ad(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ad(c,t),sqrt:n.sqrt||(c=>(o||(o=fk(t)),o(a,c))),toBytes:c=>r?zb(c,i):Ea(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return r?Hb(c):Bs(c)},invertBatch:c=>Qg(a,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(a)}function tw(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function rw(t){const e=tw(t);return e+Math.ceil(e/2)}function yk(t,e,r=!1){const n=t.length,s=tw(e),i=rw(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=r?Hb(t):Bs(t),a=Nt(o,e-It)+It;return r?zb(a,s):Ea(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const h0=BigInt(0),cd=BigInt(1);function Xu(t,e){const r=e.negate();return t?r:e}function nw(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Yu(t,e){nw(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,i=Yc(t),o=BigInt(t);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function p0(t,e,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(t&s),c=t>>o;a>n&&(a-=i,c+=cd);const u=e*n,l=u+Math.abs(a)-1,f=a===0,h=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:u}}function mk(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function bk(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const Ju=new WeakMap,sw=new WeakMap;function Zu(t){return sw.get(t)||1}function gk(t,e){return{constTimeNegate:Xu,hasPrecomputes(r){return Zu(r)!==1},unsafeLadder(r,n,s=t.ZERO){let i=r;for(;n>h0;)n&cd&&(s=s.add(i)),i=i.double(),n>>=cd;return s},precomputeWindow(r,n){const{windows:s,windowSize:i}=Yu(n,e),o=[];let a=r,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let l=1;l<i;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,s){let i=t.ZERO,o=t.BASE;const a=Yu(r,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:p}=p0(s,c,a);s=u,f?o=o.add(Xu(d,n[p])):i=i.add(Xu(h,n[l]))}return{p:i,f:o}},wNAFUnsafe(r,n,s,i=t.ZERO){const o=Yu(r,e);for(let a=0;a<o.windows&&s!==h0;a++){const{nextN:c,offset:u,isZero:l,isNeg:f}=p0(s,a,o);if(s=c,!l){const h=n[u];i=i.add(f?h.negate():h)}}return i},getPrecomputes(r,n,s){let i=Ju.get(n);return i||(i=this.precomputeWindow(n,r),r!==1&&Ju.set(n,s(i))),i},wNAFCached(r,n,s){const i=Zu(r);return this.wNAF(i,this.getPrecomputes(i,r,s),n)},wNAFCachedUnsafe(r,n,s,i){const o=Zu(r);return o===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),n,i)},setWindowSize(r,n){nw(n,e),sw.set(r,n),Ju.delete(r)}}}function wk(t,e,r,n){mk(r,t),bk(n,e);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=wE(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Yc(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let h=o;for(let d=f;d>=0;d-=c){l.fill(o);for(let m=0;m<i;m++){const v=n[m],S=Number(v>>BigInt(d)&u);l[S]=l[S].add(r[m])}let p=o;for(let m=l.length-1,v=o;m>0;m--)v=v.add(l[m]),p=p.add(v);if(h=h.add(p),d!==0)for(let m=0;m<c;m++)h=h.double()}return h}function iw(t){return hk(t.Fp),Jc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ew(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function y0(t){t.lowS!==void 0&&Yo("lowS",t.lowS),t.prehash!==void 0&&Yo("prehash",t.prehash)}function vk(t){const e=iw(t);Jc(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:n,a:s}=e;if(r){if(!n.eql(s,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class Ek extends Error{constructor(e=""){super(e)}}const mn={Err:Ek,_tlv:{encode:(t,e)=>{const{Err:r}=mn;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,s=Fa(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?Fa(s.length/2|128):"";return Fa(t)+i+s+e},decode(t,e){const{Err:r}=mn;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[n++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=mn;if(t<wn)throw new e("integer: negative integers are not allowed");let r=Fa(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=mn;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Bs(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=mn,s=or("signature",t),{v:i,l:o}=n.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=mn,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),i=n+s;return e.encode(48,i)}};function Qu(t,e){return Jo(Ea(t,e))}const wn=BigInt(0),it=BigInt(1);BigInt(2);const el=BigInt(3),Sk=BigInt(4);function Ak(t){const e=vk(t),{Fp:r}=e,n=Mh(e.n,e.nBitLength),s=e.toBytes||((g,w,k)=>{const _=w.toAffine();return Ac(Uint8Array.from([4]),r.toBytes(_.x),r.toBytes(_.y))}),i=e.fromBytes||(g=>{const w=g.subarray(1),k=r.fromBytes(w.subarray(0,r.BYTES)),_=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x:k,y:_}});function o(g){const{a:w,b:k}=e,_=r.sqr(g),O=r.mul(_,g);return r.add(r.add(O,r.mul(g,w)),k)}function a(g,w){const k=r.sqr(w),_=o(g);return r.eql(k,_)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,el),Sk),u=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function l(g){return bh(g,it,e.n)}function f(g){const{allowedPrivateKeyLengths:w,nByteLength:k,wrapPrivateKey:_,n:O}=e;if(w&&typeof g!="bigint"){if(va(g)&&(g=Jo(g)),typeof g!="string"||!w.includes(g.length))throw new Error("invalid private key");g=g.padStart(k*2,"0")}let B;try{B=typeof g=="bigint"?g:Bs(or("private key",g,k))}catch{throw new Error("invalid private key, expected hex or "+k+" bytes, got "+typeof g)}return _&&(B=Nt(B,O)),Si("private key",B,it,O),B}function h(g){if(!(g instanceof m))throw new Error("ProjectivePoint expected")}const d=Yp((g,w)=>{const{px:k,py:_,pz:O}=g;if(r.eql(O,r.ONE))return{x:k,y:_};const B=g.is0();w==null&&(w=B?r.ONE:r.inv(O));const N=r.mul(k,w),$=r.mul(_,w),j=r.mul(O,w);if(B)return{x:r.ZERO,y:r.ZERO};if(!r.eql(j,r.ONE))throw new Error("invZ was invalid");return{x:N,y:$}}),p=Yp(g=>{if(g.is0()){if(e.allowInfinityPoint&&!r.is0(g.py))return;throw new Error("bad point: ZERO")}const{x:w,y:k}=g.toAffine();if(!r.isValid(w)||!r.isValid(k))throw new Error("bad point: x or y not FE");if(!a(w,k))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class m{constructor(w,k,_){if(w==null||!r.isValid(w))throw new Error("x required");if(k==null||!r.isValid(k)||r.is0(k))throw new Error("y required");if(_==null||!r.isValid(_))throw new Error("z required");this.px=w,this.py=k,this.pz=_,Object.freeze(this)}static fromAffine(w){const{x:k,y:_}=w||{};if(!w||!r.isValid(k)||!r.isValid(_))throw new Error("invalid affine point");if(w instanceof m)throw new Error("projective point not allowed");const O=B=>r.eql(B,r.ZERO);return O(k)&&O(_)?m.ZERO:new m(k,_,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const k=Qg(r,w.map(_=>_.pz));return w.map((_,O)=>_.toAffine(k[O])).map(m.fromAffine)}static fromHex(w){const k=m.fromAffine(i(or("pointHex",w)));return k.assertValidity(),k}static fromPrivateKey(w){return m.BASE.multiply(f(w))}static msm(w,k){return wk(m,n,w,k)}_setWindowSize(w){T.setWindowSize(this,w)}assertValidity(){p(this)}hasEvenY(){const{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){h(w);const{px:k,py:_,pz:O}=this,{px:B,py:N,pz:$}=w,j=r.eql(r.mul(k,$),r.mul(B,O)),H=r.eql(r.mul(_,$),r.mul(N,O));return j&&H}negate(){return new m(this.px,r.neg(this.py),this.pz)}double(){const{a:w,b:k}=e,_=r.mul(k,el),{px:O,py:B,pz:N}=this;let $=r.ZERO,j=r.ZERO,H=r.ZERO,G=r.mul(O,O),ee=r.mul(B,B),U=r.mul(N,N),X=r.mul(O,B);return X=r.add(X,X),H=r.mul(O,N),H=r.add(H,H),$=r.mul(w,H),j=r.mul(_,U),j=r.add($,j),$=r.sub(ee,j),j=r.add(ee,j),j=r.mul($,j),$=r.mul(X,$),H=r.mul(_,H),U=r.mul(w,U),X=r.sub(G,U),X=r.mul(w,X),X=r.add(X,H),H=r.add(G,G),G=r.add(H,G),G=r.add(G,U),G=r.mul(G,X),j=r.add(j,G),U=r.mul(B,N),U=r.add(U,U),G=r.mul(U,X),$=r.sub($,G),H=r.mul(U,ee),H=r.add(H,H),H=r.add(H,H),new m($,j,H)}add(w){h(w);const{px:k,py:_,pz:O}=this,{px:B,py:N,pz:$}=w;let j=r.ZERO,H=r.ZERO,G=r.ZERO;const ee=e.a,U=r.mul(e.b,el);let X=r.mul(k,B),te=r.mul(_,N),W=r.mul(O,$),C=r.add(k,_),D=r.add(B,N);C=r.mul(C,D),D=r.add(X,te),C=r.sub(C,D),D=r.add(k,O);let Z=r.add(B,$);return D=r.mul(D,Z),Z=r.add(X,W),D=r.sub(D,Z),Z=r.add(_,O),j=r.add(N,$),Z=r.mul(Z,j),j=r.add(te,W),Z=r.sub(Z,j),G=r.mul(ee,D),j=r.mul(U,W),G=r.add(j,G),j=r.sub(te,G),G=r.add(te,G),H=r.mul(j,G),te=r.add(X,X),te=r.add(te,X),W=r.mul(ee,W),D=r.mul(U,D),te=r.add(te,W),W=r.sub(X,W),W=r.mul(ee,W),D=r.add(D,W),X=r.mul(te,D),H=r.add(H,X),X=r.mul(Z,D),j=r.mul(C,j),j=r.sub(j,X),X=r.mul(C,te),G=r.mul(Z,G),G=r.add(G,X),new m(j,H,G)}subtract(w){return this.add(w.negate())}is0(){return this.equals(m.ZERO)}wNAF(w){return T.wNAFCached(this,w,m.normalizeZ)}multiplyUnsafe(w){const{endo:k,n:_}=e;Si("scalar",w,wn,_);const O=m.ZERO;if(w===wn)return O;if(this.is0()||w===it)return this;if(!k||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,w,m.normalizeZ);let{k1neg:B,k1:N,k2neg:$,k2:j}=k.splitScalar(w),H=O,G=O,ee=this;for(;N>wn||j>wn;)N&it&&(H=H.add(ee)),j&it&&(G=G.add(ee)),ee=ee.double(),N>>=it,j>>=it;return B&&(H=H.negate()),$&&(G=G.negate()),G=new m(r.mul(G.px,k.beta),G.py,G.pz),H.add(G)}multiply(w){const{endo:k,n:_}=e;Si("scalar",w,it,_);let O,B;if(k){const{k1neg:N,k1:$,k2neg:j,k2:H}=k.splitScalar(w);let{p:G,f:ee}=this.wNAF($),{p:U,f:X}=this.wNAF(H);G=T.constTimeNegate(N,G),U=T.constTimeNegate(j,U),U=new m(r.mul(U.px,k.beta),U.py,U.pz),O=G.add(U),B=ee.add(X)}else{const{p:N,f:$}=this.wNAF(w);O=N,B=$}return m.normalizeZ([O,B])[0]}multiplyAndAddUnsafe(w,k,_){const O=m.BASE,B=($,j)=>j===wn||j===it||!$.equals(O)?$.multiplyUnsafe(j):$.multiply(j),N=B(this,k).add(B(w,_));return N.is0()?void 0:N}toAffine(w){return d(this,w)}isTorsionFree(){const{h:w,isTorsionFree:k}=e;if(w===it)return!0;if(k)return k(m,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:k}=e;return w===it?this:k?k(m,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return Yo("isCompressed",w),this.assertValidity(),s(m,this,w)}toHex(w=!0){return Yo("isCompressed",w),Jo(this.toRawBytes(w))}}m.BASE=new m(e.Gx,e.Gy,r.ONE),m.ZERO=new m(r.ZERO,r.ONE,r.ZERO);const{endo:v,nBitLength:S}=e,T=gk(m,v?Math.ceil(S/2):S);return{CURVE:e,ProjectivePoint:m,normPrivateKeyToScalar:f,weierstrassEquation:o,isWithinCurveOrder:l}}function kk(t){const e=iw(t);return Jc(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function xk(t){const e=kk(t),{Fp:r,n,nByteLength:s,nBitLength:i}=e,o=r.BYTES+1,a=2*r.BYTES+1;function c(U){return Nt(U,n)}function u(U){return ad(U,n)}const{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:h,isWithinCurveOrder:d}=Ak({...e,toBytes(U,X,te){const W=X.toAffine(),C=r.toBytes(W.x),D=Ac;return Yo("isCompressed",te),te?D(Uint8Array.from([X.hasEvenY()?2:3]),C):D(Uint8Array.from([4]),C,r.toBytes(W.y))},fromBytes(U){const X=U.length,te=U[0],W=U.subarray(1);if(X===o&&(te===2||te===3)){const C=Bs(W);if(!bh(C,it,r.ORDER))throw new Error("Point is not on curve");const D=h(C);let Z;try{Z=r.sqrt(D)}catch(z){const se=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+se)}const R=(Z&it)===it;return(te&1)===1!==R&&(Z=r.neg(Z)),{x:C,y:Z}}else if(X===a&&te===4){const C=r.fromBytes(W.subarray(0,r.BYTES)),D=r.fromBytes(W.subarray(r.BYTES,2*r.BYTES));return{x:C,y:D}}else{const C=o,D=a;throw new Error("invalid Point, expected length of "+C+", or uncompressed "+D+", got "+X)}}});function p(U){const X=n>>it;return U>X}function m(U){return p(U)?c(-U):U}const v=(U,X,te)=>Bs(U.slice(X,te));class S{constructor(X,te,W){Si("r",X,it,n),Si("s",te,it,n),this.r=X,this.s=te,W!=null&&(this.recovery=W),Object.freeze(this)}static fromCompact(X){const te=s;return X=or("compactSignature",X,te*2),new S(v(X,0,te),v(X,te,2*te))}static fromDER(X){const{r:te,s:W}=mn.toSig(or("DER",X));return new S(te,W)}assertValidity(){}addRecoveryBit(X){return new S(this.r,this.s,X)}recoverPublicKey(X){const{r:te,s:W,recovery:C}=this,D=O(or("msgHash",X));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const Z=C===2||C===3?te+e.n:te;if(Z>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const R=C&1?"03":"02",F=l.fromHex(R+Qu(Z,r.BYTES)),z=u(Z),se=c(-D*z),ae=c(W*z),fe=l.BASE.multiplyAndAddUnsafe(F,se,ae);if(!fe)throw new Error("point at infinify");return fe.assertValidity(),fe}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Sc(this.toDERHex())}toDERHex(){return mn.hexFromSig(this)}toCompactRawBytes(){return Sc(this.toCompactHex())}toCompactHex(){const X=s;return Qu(this.r,X)+Qu(this.s,X)}}const T={isValidPrivateKey(U){try{return f(U),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const U=rw(e.n);return yk(e.randomBytes(U),e.n)},precompute(U=8,X=l.BASE){return X._setWindowSize(U),X.multiply(BigInt(3)),X}};function g(U,X=!0){return l.fromPrivateKey(U).toRawBytes(X)}function w(U){if(typeof U=="bigint")return!1;if(U instanceof l)return!0;const te=or("key",U).length,W=r.BYTES,C=W+1,D=2*W+1;if(!(e.allowedPrivateKeyLengths||s===C))return te===C||te===D}function k(U,X,te=!0){if(w(U)===!0)throw new Error("first arg must be private key");if(w(X)===!1)throw new Error("second arg must be public key");return l.fromHex(X).multiply(f(U)).toRawBytes(te)}const _=e.bits2int||function(U){if(U.length>8192)throw new Error("input is too large");const X=Bs(U),te=U.length*8-i;return te>0?X>>BigInt(te):X},O=e.bits2int_modN||function(U){return c(_(U))},B=Yc(i);function N(U){return Si("num < 2^"+i,U,wn,B),Ea(U,s)}function $(U,X,te=j){if(["recovered","canonical"].some(oe=>oe in te))throw new Error("sign() legacy options not supported");const{hash:W,randomBytes:C}=e;let{lowS:D,prehash:Z,extraEntropy:R}=te;D==null&&(D=!0),U=or("msgHash",U),y0(te),Z&&(U=or("prehashed msgHash",W(U)));const F=O(U),z=f(X),se=[N(z),N(F)];if(R!=null&&R!==!1){const oe=R===!0?C(r.BYTES):R;se.push(or("extraEntropy",oe))}const ae=Ac(...se),fe=F;function ue(oe){const ie=_(oe);if(!d(ie))return;const ye=u(ie),me=l.BASE.multiply(ie).toAffine(),ve=c(me.x);if(ve===wn)return;const ke=c(ye*c(fe+ve*z));if(ke===wn)return;let Ze=(me.x===ve?0:2)|Number(me.y&it),Ie=ke;return D&&p(ke)&&(Ie=m(ke),Ze^=1),new S(ve,Ie,Ze)}return{seed:ae,k2sig:ue}}const j={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function G(U,X,te=j){const{seed:W,k2sig:C}=$(U,X,te),D=e;return vE(D.hash.outputLen,D.nByteLength,D.hmac)(W,C)}l.BASE._setWindowSize(8);function ee(U,X,te,W=H){var Ze;const C=U;X=or("msgHash",X),te=or("publicKey",te);const{lowS:D,prehash:Z,format:R}=W;if(y0(W),"strict"in W)throw new Error("options.strict was renamed to lowS");if(R!==void 0&&R!=="compact"&&R!=="der")throw new Error("format must be compact or der");const F=typeof C=="string"||va(C),z=!F&&!R&&typeof C=="object"&&C!==null&&typeof C.r=="bigint"&&typeof C.s=="bigint";if(!F&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let se,ae;try{if(z&&(se=new S(C.r,C.s)),F){try{R!=="compact"&&(se=S.fromDER(C))}catch(Ie){if(!(Ie instanceof mn.Err))throw Ie}!se&&R!=="der"&&(se=S.fromCompact(C))}ae=l.fromHex(te)}catch{return!1}if(!se||D&&se.hasHighS())return!1;Z&&(X=e.hash(X));const{r:fe,s:ue}=se,oe=O(X),ie=u(ue),ye=c(oe*ie),me=c(fe*ie),ve=(Ze=l.BASE.multiplyAndAddUnsafe(ae,ye,me))==null?void 0:Ze.toAffine();return ve?c(ve.x)===fe:!1}return{CURVE:e,getPublicKey:g,getSharedSecret:k,sign:G,verify:ee,ProjectivePoint:l,Signature:S,utils:T}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Tk(t){return{hash:t,hmac:(e,...r)=>Kg(t,e,j6(...r)),randomBytes:F6}}function _k(t,e){const r=n=>xk({...t,...Tk(n)});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ow=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),m0=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Pk=BigInt(0),Ok=BigInt(1),ud=BigInt(2),b0=(t,e)=>(t+e/ud)/e;function Ik(t){const e=ow,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=nr(l,r,e)*l%e,h=nr(f,r,e)*l%e,d=nr(h,ud,e)*u%e,p=nr(d,s,e)*d%e,m=nr(p,i,e)*p%e,v=nr(m,a,e)*m%e,S=nr(v,c,e)*v%e,T=nr(S,a,e)*m%e,g=nr(T,r,e)*l%e,w=nr(g,o,e)*p%e,k=nr(w,n,e)*u%e,_=nr(k,ud,e);if(!ld.eql(ld.sqr(_),t))throw new Error("Cannot find square root");return _}const ld=Mh(ow,void 0,void 0,{sqrt:Ik}),aw=_k({a:Pk,b:BigInt(7),Fp:ld,n:m0,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=m0,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ok*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=b0(i*t,e),c=b0(-n*t,e);let u=Nt(t-a*r-c*s,e),l=Nt(-a*n-c*i,e);const f=u>o,h=l>o;if(f&&(u=e-u),h&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}}},Ib),Bk=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:aw},Symbol.toStringTag,{value:"Module"}));function cw(t,e={}){const{recovered:r}=e;if(typeof t.r>"u")throw new tl({signature:t});if(typeof t.s>"u")throw new tl({signature:t});if(r&&typeof t.yParity>"u")throw new tl({signature:t});if(t.r<0n||t.r>u0)throw new Fk({value:t.r});if(t.s<0n||t.s>u0)throw new $k({value:t.s});if(typeof t.yParity=="number"&&t.yParity!==0&&t.yParity!==1)throw new Uh({value:t.yParity})}function Ck(t){return uw(Ir(t))}function uw(t){if(t.length!==130&&t.length!==132)throw new Uk({signature:t});const e=BigInt(Zr(t,0,32)),r=BigInt(Zr(t,32,64)),n=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return jh(s)}catch{throw new Uh({value:s})}})();return typeof n>"u"?{r:e,s:r}:{r:e,s:r,yParity:n}}function Nk(t){if(!(typeof t.r>"u")&&!(typeof t.s>"u"))return Rk(t)}function Rk(t){const e=typeof t=="string"?uw(t):t instanceof Uint8Array?Ck(t):typeof t.r=="string"?jk(t):t.v?Mk(t):{r:t.r,s:t.s,...typeof t.yParity<"u"?{yParity:t.yParity}:{}};return cw(e),e}function Mk(t){return{r:t.r,s:t.s,yParity:jh(t.v)}}function jk(t){const e=(()=>{const r=t.v?Number(t.v):void 0;let n=t.yParity?Number(t.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=jh(r)),typeof n!="number")throw new Uh({value:t.yParity});return n})();return{r:BigInt(t.r),s:BigInt(t.s),yParity:e}}function jh(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new Lk({value:t})}class Uk extends le{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Zt(GE(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class tl extends le{constructor({signature:e}){super(`Signature \`${Wb(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class Fk extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class $k extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class Uh extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class Lk extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function Dk(t,e={}){return typeof t.chainId=="string"?Hk(t):{...t,...e.signature}}function Hk(t){const{address:e,chainId:r,nonce:n}=t,s=Nk(t);return{address:e,chainId:Number(r),nonce:BigInt(n),...s}}const zk="0x8010801080108010801080108010801080108010801080108010801080108010",Vk=Vg("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function lw(t){if(typeof t=="string"){if(Zr(t,-32)!==zk)throw new Wk(t)}else cw(t.authorization)}function Gk(t){lw(t);const e=Zb(Zr(t,-64,-32)),r=Zr(t,-e-64,-64),n=Zr(t,0,-e-64),[s,i,o]=nk(Vk,r);return{authorization:Dk({address:s.delegation,chainId:Number(s.chainId),nonce:s.nonce,yParity:s.yParity,r:s.r,s:s.s}),signature:n,...o&&o!=="0x"?{data:o,to:i}:{}}}function qk(t){try{return lw(t),!0}catch{return!1}}let Wk=class extends le{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}};function Kk(t){return t.map(e=>({...e,value:BigInt(e.value)}))}function Xk(t){return{...t,balance:t.balance?BigInt(t.balance):void 0,nonce:t.nonce?dr(t.nonce):void 0,storageProof:t.storageProof?Kk(t.storageProof):void 0}}async function Yk(t,{address:e,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",o=r!==void 0?J(r):void 0,a=await t.request({method:"eth_getProof",params:[e,s,o||i]});return Xk(a)}async function Jk(t,{address:e,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?J(r):void 0;return await t.request({method:"eth_getStorageAt",params:[e,s,i||n]})}async function Fh(t,{blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i,sender:o,nonce:a}){var h,d,p;const c=n||"latest",u=r!==void 0?J(r):void 0;let l=null;if(s?l=await t.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):e?l=await t.request({method:"eth_getTransactionByBlockHashAndIndex",params:[e,J(i)]},{dedupe:!0}):typeof i=="number"?l=await t.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,J(i)]},{dedupe:!!u}):o&&typeof a=="number"&&(l=await t.request({method:"eth_getTransactionBySenderAndNonce",params:[o,J(a)]},{dedupe:!0})),!l)throw new mb({blockHash:e,blockNumber:r,blockTag:c,hash:s,index:i});return(((p=(d=(h=t.chain)==null?void 0:h.formatters)==null?void 0:d.transaction)==null?void 0:p.format)||ga)(l,"getTransaction")}async function Zk(t,{hash:e,transactionReceipt:r}){const[n,s]=await Promise.all([ne(t,ka,"getBlockNumber")({}),e?ne(t,Fh,"getTransaction")({hash:e}):void 0]),i=(r==null?void 0:r.blockNumber)||(s==null?void 0:s.blockNumber);return i?n-i+1n:0n}async function oc(t,{hash:e}){var s,i,o;const r=await t.request({method:"eth_getTransactionReceipt",params:[e]},{dedupe:!0});if(!r)throw new bb({hash:e});return(((o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:o.format)||kh)(r,"getTransactionReceipt")}async function Qk(t,e){var T;const{account:r,authorizationList:n,allowFailure:s=!0,blockNumber:i,blockOverrides:o,blockTag:a,stateOverride:c}=e,u=e.contracts,{batchSize:l=e.batchSize??1024,deployless:f=e.deployless??!1}=typeof((T=t.batch)==null?void 0:T.multicall)=="object"?t.batch.multicall:{},h=(()=>{if(e.multicallAddress)return e.multicallAddress;if(f)return null;if(t.chain)return Ki({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),d=[[]];let p=0,m=0;for(let g=0;g<u.length;g++){const{abi:w,address:k,args:_,functionName:O}=u[g];try{const B=er({abi:w,args:_,functionName:O});m+=(B.length-2)/2,l>0&&m>l&&d[p].length>0&&(p++,m=(B.length-2)/2,d[p]=[]),d[p]=[...d[p],{allowFailure:!0,callData:B,target:k}]}catch(B){const N=Ls(B,{abi:w,address:k,args:_,docsPath:"/docs/contract/multicall",functionName:O,sender:r});if(!s)throw N;d[p]=[...d[p],{allowFailure:!0,callData:"0x",target:k}]}}const v=await Promise.allSettled(d.map(g=>ne(t,hr,"readContract")({...h===null?{code:wh}:{address:h},abi:kc,account:r,args:[g],authorizationList:n,blockNumber:i,blockOverrides:o,blockTag:a,functionName:"aggregate3",stateOverride:c}))),S=[];for(let g=0;g<v.length;g++){const w=v[g];if(w.status==="rejected"){if(!s)throw w.reason;for(let _=0;_<d[g].length;_++)S.push({status:"failure",error:w.reason,result:void 0});continue}const k=w.value;for(let _=0;_<k.length;_++){const{returnData:O,success:B}=k[_],{callData:N}=d[g][_],{abi:$,address:j,functionName:H,args:G}=u[S.length];try{if(N==="0x")throw new fa;if(!B)throw new Gc({data:O});const ee=Js({abi:$,args:G,data:O,functionName:H});S.push(s?{result:ee,status:"success"}:ee)}catch(ee){const U=Ls(ee,{abi:$,address:j,args:G,docsPath:"/docs/contract/multicall",functionName:H});if(!s)throw U;S.push({error:U,result:void 0,status:"failure"})}}}if(S.length!==u.length)throw new q("multicall results mismatch");return S}async function fd(t,e){const{blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",blocks:s,returnFullTransactions:i,traceTransfers:o,validation:a}=e;try{const c=[];for(const h of s){const d=h.blockOverrides?tg(h.blockOverrides):void 0,p=h.calls.map(v=>{const S=v,T=S.account?Fe(S.account):void 0,g=S.abi?er(S):S.data,w={...S,account:T,data:S.dataSuffix?Jt([g||"0x",S.dataSuffix]):g,from:S.from??(T==null?void 0:T.address)};return Nn(w),ds(w)}),m=h.stateOverrides?eh(h.stateOverrides):void 0;c.push({blockOverrides:d,calls:p,stateOverrides:m})}const l=(typeof r=="bigint"?J(r):void 0)||n;return(await t.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:o,validation:a},l]})).map((h,d)=>({...rh(h),calls:h.calls.map((p,m)=>{var $,j;const{abi:v,args:S,functionName:T,to:g}=s[d].calls[m],w=(($=p.error)==null?void 0:$.data)??p.returnData,k=BigInt(p.gasUsed),_=(j=p.logs)==null?void 0:j.map(H=>_n(H)),O=p.status==="0x1"?"success":"failure",B=v&&O==="success"&&w!=="0x"?Js({abi:v,data:w,functionName:T}):null,N=(()=>{var G;if(O==="success")return;let H;if(((G=p.error)==null?void 0:G.data)==="0x"?H=new fa:p.error&&(H=new Gc(p.error)),!!H)return Ls(H,{abi:v??[],address:g??"0x",args:S,functionName:T??"<unknown>"})})();return{data:w,gasUsed:k,logs:_,status:O,...O==="success"?{result:B}:{error:N}}})}))}catch(c){const u=c,l=Wc(u,{});throw l instanceof ba?u:l}}function dd(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function","error",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new le("Unable to normalize signature.");return s}function hd(t,e){const r=typeof t,n=e.type;switch(n){case"address":return sd(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>hd(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>hd(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function fw(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return fw(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?sd(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?sd(r[n],{strict:!1}):!1)return o}}function dw(t,e={}){const{prepare:r=!0}=e,n=Array.isArray(t)||typeof t=="string"?xp(t):t;return{...n,...r?{hash:gi(n)}:{}}}function ou(t,e,r){const{args:n=[],prepare:s=!0}=r??{},i=qE(e,{strict:!1}),o=t.filter(u=>i?u.type==="function"||u.type==="error"?hw(u)===Zr(e,0,4):u.type==="event"?gi(u)===e:!1:"name"in u&&u.name===e);if(o.length===0)throw new Tc({name:e});if(o.length===1)return{...o[0],...s?{hash:gi(o[0])}:{}};let a;for(const u of o){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...s?{hash:gi(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((f,h)=>{const d="inputs"in u&&u.inputs[h];return d?hd(f,d):!1})){if(a&&"inputs"in a&&a.inputs){const f=fw(u.inputs,a.inputs,n);if(f)throw new tx({abiItem:u,type:f[0]},{abiItem:a,type:f[1]})}a=u}}const c=(()=>{if(a)return a;const[u,...l]=o;return{...u,overloads:l}})();if(!c)throw new Tc({name:e});return{...c,...s?{hash:gi(c)}:{}}}function hw(...t){const e=(()=>{if(Array.isArray(t[0])){const[r,n]=t;return ou(r,n)}return t[0]})();return Zr(gi(e),0,4)}function ex(...t){const e=(()=>{if(Array.isArray(t[0])){const[n,s]=t;return ou(n,s)}return t[0]})(),r=typeof e=="string"?e:wc(e);return dd(r)}function gi(...t){const e=(()=>{if(Array.isArray(t[0])){const[r,n]=t;return ou(r,n)}return t[0]})();return typeof e!="string"&&"hash"in e&&e.hash?e.hash:Dg(gh(ex(e)))}class tx extends le{constructor(e,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${dd(wc(e.abiItem))}\`, and`,`\`${r.type}\` in \`${dd(wc(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class Tc extends le{constructor({name:e,data:r,type:n="item"}){const s=e?` with name "${e}"`:r?` with data "${r}"`:"";super(`ABI ${n}${s} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}function rx(...t){var i;const[e,r]=(()=>{if(Array.isArray(t[0])){const[o,a]=t;return[sx(o),a]}return t})(),{bytecode:n,args:s}=r;return Or(n,(i=e.inputs)!=null&&i.length&&(s!=null&&s.length)?Nh(e.inputs,s):"0x")}function nx(t){return dw(t)}function sx(t){const e=t.find(r=>r.type==="constructor");if(!e)throw new Tc({name:"constructor"});return e}function ix(...t){const[e,r=[]]=(()=>{if(Array.isArray(t[0])){const[u,l,f]=t;return[g0(u,l,{args:f}),f]}const[a,c]=t;return[a,c]})(),{overloads:n}=e,s=n?g0([e,...n],e.name,{args:r}):e,i=ox(s),o=r.length>0?Nh(s.inputs,r):void 0;return o?Or(i,o):i}function ii(t,e={}){return dw(t,e)}function g0(t,e,r){const n=ou(t,e,r);if(n.type!=="function")throw new Tc({name:e,type:"function"});return n}function ox(t){return hw(t)}const ax="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",$r="0x0000000000000000000000000000000000000000",cx="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function ux(t,e){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:o,traceTransfers:a,validation:c}=e,u=e.account?Fe(e.account):void 0;if(o&&!u)throw new q("`account` is required when `traceAssetChanges` is true");const l=u?rx(nx("constructor(bytes, bytes)"),{bytecode:ig,args:[cx,ix(ii("function getBalance(address)"),[u.address])]}):void 0,f=o?await Promise.all(e.calls.map(async W=>{if(!W.data&&!W.abi)return;const{accessList:C}=await xg(t,{account:u.address,...W,data:W.abi?er(W):W.data});return C.map(({address:D,storageKeys:Z})=>Z.length>0?D:null)})).then(W=>W.flat().filter(Boolean)):[],h=await fd(t,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:l}],stateOverrides:i},{calls:f.map((W,C)=>({abi:[ii("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:W,from:$r,nonce:C})),stateOverrides:[{address:$r,nonce:0}]}]:[],{calls:[...s,{}].map(W=>({...W,from:u==null?void 0:u.address})),stateOverrides:i},...o?[{calls:[{data:l}]},{calls:f.map((W,C)=>({abi:[ii("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:W,from:$r,nonce:C})),stateOverrides:[{address:$r,nonce:0}]},{calls:f.map((W,C)=>({to:W,abi:[ii("function decimals() returns (uint256)")],functionName:"decimals",from:$r,nonce:C})),stateOverrides:[{address:$r,nonce:0}]},{calls:f.map((W,C)=>({to:W,abi:[ii("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:$r,nonce:C})),stateOverrides:[{address:$r,nonce:0}]},{calls:f.map((W,C)=>({to:W,abi:[ii("function symbol() returns (string)")],functionName:"symbol",from:$r,nonce:C})),stateOverrides:[{address:$r,nonce:0}]}]:[]],traceTransfers:a,validation:c}),d=o?h[2]:h[0],[p,m,,v,S,T,g,w]=o?h:[],{calls:k,..._}=d,O=k.slice(0,-1)??[],B=(p==null?void 0:p.calls)??[],N=(m==null?void 0:m.calls)??[],$=[...B,...N].map(W=>W.status==="success"?ot(W.data):null),j=(v==null?void 0:v.calls)??[],H=(S==null?void 0:S.calls)??[],G=[...j,...H].map(W=>W.status==="success"?ot(W.data):null),ee=((T==null?void 0:T.calls)??[]).map(W=>W.status==="success"?W.result:null),U=((w==null?void 0:w.calls)??[]).map(W=>W.status==="success"?W.result:null),X=((g==null?void 0:g.calls)??[]).map(W=>W.status==="success"?W.result:null),te=[];for(const[W,C]of G.entries()){const D=$[W];if(typeof C!="bigint"||typeof D!="bigint")continue;const Z=ee[W-1],R=U[W-1],F=X[W-1],z=W===0?{address:ax,decimals:18,symbol:"ETH"}:{address:f[W-1],decimals:F||Z?Number(Z??1):void 0,symbol:R??void 0};te.some(se=>se.token.address===z.address)||te.push({token:z,value:{pre:D,post:C,diff:C-D}})}return{assetChanges:te,block:_,results:O}}const pw="0x6492649264926492649264926492649264926492649264926492649264926492";function lx(t){if(Zr(t,-32)!==pw)throw new hx(t)}function fx(t){const{data:e,signature:r,to:n}=t;return Or(Nh(Vg("address, bytes, bytes"),[n,e,r]),pw)}function dx(t){try{return lx(t),!0}catch{return!1}}class hx extends le{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}function px({r:t,s:e,to:r="hex",v:n,yParity:s}){const i=(()=>{if(s===0||s===1)return s;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),o=`0x${new aw.Signature(ot(t),ot(e)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?o:en(o)}async function au(t,e){var c,u,l,f;const{address:r,chain:n=t.chain,hash:s,erc6492VerifierAddress:i=e.universalSignatureVerifierAddress??((u=(c=n==null?void 0:n.contracts)==null?void 0:c.erc6492Verifier)==null?void 0:u.address),multicallAddress:o=e.multicallAddress??((f=(l=n==null?void 0:n.contracts)==null?void 0:l.multicall3)==null?void 0:f.address)}=e;if(n!=null&&n.verifyHash)return await n.verifyHash(t,e);const a=(()=>{const h=e.signature;return _r(h)?h:typeof h=="object"&&"r"in h&&"s"in h?px(h):Je(h)})();try{return qk(a)?await yx(t,{...e,multicallAddress:o,signature:a}):await mx(t,{...e,verifierAddress:i,signature:a})}catch(h){try{if(Wi(Gd(r),await Eb({hash:s,signature:a})))return!0}catch{}if(h instanceof Vs)return!1;throw h}}async function yx(t,e){var v;const{address:r,blockNumber:n,blockTag:s,hash:i,multicallAddress:o}=e,{authorization:a,data:c,signature:u,to:l}=Gk(e.signature);if(await nd(t,{address:r,blockNumber:n,blockTag:s})===Nr(["0xef0100",a.address]))return await bx(t,{address:r,blockNumber:n,blockTag:s,hash:i,signature:u});const h={address:a.address,chainId:Number(a.chainId),nonce:Number(a.nonce),r:J(a.r,{size:32}),s:J(a.s,{size:32}),yParity:a.yParity};if(!await nA({address:r,authorization:h}))throw new Vs;const p=await ne(t,hr,"readContract")({...o?{address:o}:{code:wh},authorizationList:[h],abi:kc,blockNumber:n,blockTag:"pending",functionName:"aggregate3",args:[[...c?[{allowFailure:!0,target:l??r,callData:c}]:[],{allowFailure:!0,target:r,callData:er({abi:sg,functionName:"isValidSignature",args:[i,u]})}]]}),m=(v=p[p.length-1])==null?void 0:v.returnData;if(m!=null&&m.startsWith("0x1626ba7e"))return!0;throw new Vs}async function mx(t,e){const{address:r,factory:n,factoryData:s,hash:i,signature:o,verifierAddress:a,...c}=e,u=await(async()=>!n&&!s||dx(o)?o:fx({data:s,signature:o,to:n}))(),l=a?{to:a,data:er({abi:r0,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:eu({abi:r0,args:[r,i,u],bytecode:QE}),...c},{data:f}=await ne(t,Aa,"call")(l).catch(h=>{throw h instanceof wb?new Vs:h});if(b6(f??"0x0"))return!0;throw new Vs}async function bx(t,e){const{address:r,blockNumber:n,blockTag:s,hash:i,signature:o}=e;if((await ne(t,hr,"readContract")({address:r,abi:sg,args:[i,o],blockNumber:n,blockTag:s,functionName:"isValidSignature"}).catch(c=>{throw c instanceof vb?new Vs:c})).startsWith("0x1626ba7e"))return!0;throw new Vs}class Vs extends Error{}async function gx(t,{address:e,message:r,factory:n,factoryData:s,signature:i,...o}){const a=Rg(r);return ne(t,au,"verifyHash")({address:e,factory:n,factoryData:s,hash:a,signature:i,...o})}async function wx(t,e){const{address:r,factory:n,factoryData:s,signature:i,message:o,primaryType:a,types:c,domain:u,...l}=e,f=_A({message:o,primaryType:a,types:c,domain:u});return ne(t,au,"verifyHash")({address:r,factory:n,factoryData:s,hash:f,signature:i,...l})}function yw(t,{emitOnBegin:e=!1,emitMissed:r=!1,onBlockNumber:n,onError:s,poll:i,pollingInterval:o=t.pollingInterval}){const a=typeof i<"u"?i:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc"));let c;return a?(()=>{const f=Ye(["watchBlockNumber",t.uid,e,r,o]);return Pn(f,{onBlockNumber:n,onError:s},h=>Xi(async()=>{var d;try{const p=await ne(t,ka,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(p===c)return;if(p-c>1&&r)for(let m=c+1n;m<p;m++)h.onBlockNumber(m,c),c=m}(c===void 0||p>c)&&(h.onBlockNumber(p,c),c=p)}catch(p){(d=h.onError)==null||d.call(h,p)}},{emitOnBegin:e,interval:o}))})():(()=>{const f=Ye(["watchBlockNumber",t.uid,e,r]);return Pn(f,{onBlockNumber:n,onError:s},h=>{let d=!0,p=()=>d=!1;return(async()=>{try{const m=(()=>{if(t.transport.type==="fallback"){const S=t.transport.transports.find(T=>T.config.type==="webSocket"||T.config.type==="ipc");return S?S.value:t.transport}return t.transport})(),{unsubscribe:v}=await m.subscribe({params:["newHeads"],onData(S){var g;if(!d)return;const T=ot((g=S.result)==null?void 0:g.number);h.onBlockNumber(T,c),c=T},onError(S){var T;(T=h.onError)==null||T.call(h,S)}});p=v,d||p()}catch(m){s==null||s(m)}})(),()=>p()})})()}async function mw(t,e){const{checkReplacement:r=!0,confirmations:n=1,hash:s,onReplaced:i,retryCount:o=6,retryDelay:a=({count:k})=>~~(1<<k)*200,timeout:c=18e4}=e,u=Ye(["waitForTransactionReceipt",t.uid,s]),l=(()=>{var k;return e.pollingInterval?e.pollingInterval:(k=t.chain)!=null&&k.experimental_preconfirmationTime?t.chain.experimental_preconfirmationTime:t.pollingInterval})();let f,h,d,p=!1,m,v;const{promise:S,resolve:T,reject:g}=vh(),w=c?setTimeout(()=>{v==null||v(),m==null||m(),g(new N5({hash:s}))},c):void 0;return m=Pn(u,{onReplaced:i,resolve:T,reject:g},async k=>{if(d=await ne(t,oc,"getTransactionReceipt")({hash:s}).catch(()=>{}),d&&n<=1){clearTimeout(w),k.resolve(d),m==null||m();return}v=ne(t,yw,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:l,async onBlockNumber(_){const O=N=>{clearTimeout(w),v==null||v(),N(),m==null||m()};let B=_;if(!p)try{if(d){if(n>1&&(!d.blockNumber||B-d.blockNumber+1n<n))return;O(()=>k.resolve(d));return}if(r&&!f&&(p=!0,await xc(async()=>{f=await ne(t,Fh,"getTransaction")({hash:s}),f.blockNumber&&(B=f.blockNumber)},{delay:a,retryCount:o}),p=!1),d=await ne(t,oc,"getTransactionReceipt")({hash:s}),n>1&&(!d.blockNumber||B-d.blockNumber+1n<n))return;O(()=>k.resolve(d))}catch(N){if(N instanceof mb||N instanceof bb){if(!f){p=!1;return}try{h=f,p=!0;const $=await xc(()=>ne(t,Sr,"getBlock")({blockNumber:B,includeTransactions:!0}),{delay:a,retryCount:o,shouldRetry:({error:G})=>G instanceof xb});p=!1;const j=$.transactions.find(({from:G,nonce:ee})=>G===h.from&&ee===h.nonce);if(!j||(d=await ne(t,oc,"getTransactionReceipt")({hash:j.hash}),n>1&&(!d.blockNumber||B-d.blockNumber+1n<n)))return;let H="replaced";j.to===h.to&&j.value===h.value&&j.input===h.input?H="repriced":j.from===j.to&&j.value===0n&&(H="cancelled"),O(()=>{var G;(G=k.onReplaced)==null||G.call(k,{reason:H,replacedTransaction:h,transaction:j,transactionReceipt:d}),k.resolve(d)})}catch($){O(()=>k.reject($))}}else O(()=>k.reject(N))}}})}),S}function vx(t,{blockTag:e=t.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:s,onError:i,includeTransactions:o,poll:a,pollingInterval:c=t.pollingInterval}){const u=typeof a<"u"?a:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),l=o??!1;let f;return u?(()=>{const p=Ye(["watchBlocks",t.uid,e,r,n,l,c]);return Pn(p,{onBlock:s,onError:i},m=>Xi(async()=>{var v;try{const S=await ne(t,Sr,"getBlock")({blockTag:e,includeTransactions:l});if(S.number!==null&&(f==null?void 0:f.number)!=null){if(S.number===f.number)return;if(S.number-f.number>1&&r)for(let T=(f==null?void 0:f.number)+1n;T<S.number;T++){const g=await ne(t,Sr,"getBlock")({blockNumber:T,includeTransactions:l});m.onBlock(g,f),f=g}}((f==null?void 0:f.number)==null||e==="pending"&&(S==null?void 0:S.number)==null||S.number!==null&&S.number>f.number)&&(m.onBlock(S,f),f=S)}catch(S){(v=m.onError)==null||v.call(m,S)}},{emitOnBegin:n,interval:c}))})():(()=>{let p=!0,m=!0,v=()=>p=!1;return(async()=>{try{n&&ne(t,Sr,"getBlock")({blockTag:e,includeTransactions:l}).then(g=>{p&&m&&(s(g,void 0),m=!1)}).catch(i);const S=(()=>{if(t.transport.type==="fallback"){const g=t.transport.transports.find(w=>w.config.type==="webSocket"||w.config.type==="ipc");return g?g.value:t.transport}return t.transport})(),{unsubscribe:T}=await S.subscribe({params:["newHeads"],async onData(g){var k;if(!p)return;const w=await ne(t,Sr,"getBlock")({blockNumber:(k=g.result)==null?void 0:k.number,includeTransactions:l}).catch(()=>{});p&&(s(w,f),m=!1,f=w)},onError(g){i==null||i(g)}});v=T,p||v()}catch(S){i==null||i(S)}})(),()=>v()})()}function Ex(t,{address:e,args:r,batch:n=!0,event:s,events:i,fromBlock:o,onError:a,onLogs:c,poll:u,pollingInterval:l=t.pollingInterval,strict:f}){const h=typeof u<"u"?u:typeof o=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),d=f??!1;return h?(()=>{const v=Ye(["watchEvent",e,r,n,t.uid,s,l,o]);return Pn(v,{onLogs:c,onError:a},S=>{let T;o!==void 0&&(T=o-1n);let g,w=!1;const k=Xi(async()=>{var _;if(!w){try{g=await ne(t,Tg,"createEventFilter")({address:e,args:r,event:s,events:i,strict:d,fromBlock:o})}catch{}w=!0;return}try{let O;if(g)O=await ne(t,tu,"getFilterChanges")({filter:g});else{const B=await ne(t,ka,"getBlockNumber")({});T&&T!==B?O=await ne(t,hh,"getLogs")({address:e,args:r,event:s,events:i,fromBlock:T+1n,toBlock:B}):O=[],T=B}if(O.length===0)return;if(n)S.onLogs(O);else for(const B of O)S.onLogs([B])}catch(O){g&&O instanceof as&&(w=!1),(_=S.onError)==null||_.call(S,O)}},{emitOnBegin:!0,interval:l});return async()=>{g&&await ne(t,ru,"uninstallFilter")({filter:g}),k()}})})():(()=>{let v=!0,S=()=>v=!1;return(async()=>{try{const T=(()=>{if(t.transport.type==="fallback"){const _=t.transport.transports.find(O=>O.config.type==="webSocket"||O.config.type==="ipc");return _?_.value:t.transport}return t.transport})(),g=i??(s?[s]:void 0);let w=[];g&&(w=[g.flatMap(O=>pa({abi:[O],eventName:O.name,args:r}))],s&&(w=w[0]));const{unsubscribe:k}=await T.subscribe({params:["logs",{address:e,topics:w}],onData(_){var B;if(!v)return;const O=_.result;try{const{eventName:N,args:$}=Ec({abi:g??[],data:O.data,topics:O.topics,strict:d}),j=_n(O,{args:$,eventName:N});c([j])}catch(N){let $,j;if(N instanceof vc||N instanceof Hd){if(f)return;$=N.abiItem.name,j=(B=N.abiItem.inputs)==null?void 0:B.some(G=>!("name"in G&&G.name))}const H=_n(O,{args:j?[]:{},eventName:$});c([H])}},onError(_){a==null||a(_)}});S=k,v||S()}catch(T){a==null||a(T)}})(),()=>S()})()}function Sx(t,{batch:e=!0,onError:r,onTransactions:n,poll:s,pollingInterval:i=t.pollingInterval}){return(typeof s<"u"?s:t.transport.type!=="webSocket"&&t.transport.type!=="ipc")?(()=>{const u=Ye(["watchPendingTransactions",t.uid,e,i]);return Pn(u,{onTransactions:n,onError:r},l=>{let f;const h=Xi(async()=>{var d;try{if(!f)try{f=await ne(t,_g,"createPendingTransactionFilter")({});return}catch(m){throw h(),m}const p=await ne(t,tu,"getFilterChanges")({filter:f});if(p.length===0)return;if(e)l.onTransactions(p);else for(const m of p)l.onTransactions([m])}catch(p){(d=l.onError)==null||d.call(l,p)}},{emitOnBegin:!0,interval:i});return async()=>{f&&await ne(t,ru,"uninstallFilter")({filter:f}),h()}})})():(()=>{let u=!0,l=()=>u=!1;return(async()=>{try{const{unsubscribe:f}=await t.transport.subscribe({params:["newPendingTransactions"],onData(h){if(!u)return;const d=h.result;n([d])},onError(h){r==null||r(h)}});l=f,u||l()}catch(f){r==null||r(f)}})(),()=>l()})()}function Ax(t){var f,h,d;const{scheme:e,statement:r,...n}=((f=t.match(kx))==null?void 0:f.groups)??{},{chainId:s,expirationTime:i,issuedAt:o,notBefore:a,requestId:c,...u}=((h=t.match(xx))==null?void 0:h.groups)??{},l=(d=t.split("Resources:")[1])==null?void 0:d.split(`
44
+ - `).slice(1);return{...n,...u,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...l?{resources:l}:{},...e?{scheme:e}:{},...r?{statement:r}:{}}}const kx=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,xx=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;function Tx(t){const{address:e,domain:r,message:n,nonce:s,scheme:i,time:o=new Date}=t;if(r&&n.domain!==r||s&&n.nonce!==s||i&&n.scheme!==i||n.expirationTime&&o>=n.expirationTime||n.notBefore&&o<n.notBefore)return!1;try{if(!n.address||!st(n.address,{strict:!1})||e&&!Wi(n.address,e))return!1}catch{return!1}return!0}async function _x(t,e){const{address:r,domain:n,message:s,nonce:i,scheme:o,signature:a,time:c=new Date,...u}=e,l=Ax(s);if(!l.address||!Tx({address:r,domain:n,message:l,nonce:i,scheme:o,time:c}))return!1;const h=Rg(s);return au(t,{address:l.address,hash:h,signature:a,...u})}async function $h(t,{serializedTransaction:e,throwOnReceiptRevert:r,timeout:n}){var a,c,u;const s=await t.request({method:"eth_sendRawTransactionSync",params:n?[e,J(n)]:[e]},{retryCount:0}),o=(((u=(c=(a=t.chain)==null?void 0:a.formatters)==null?void 0:c.transactionReceipt)==null?void 0:u.format)||kh)(s);if(o.status==="reverted"&&r)throw new gb({receipt:o});return o}function Px(t){return{call:e=>Aa(t,e),createAccessList:e=>xg(t,e),createBlockFilter:()=>jS(t),createContractEventFilter:e=>Xd(t,e),createEventFilter:e=>Tg(t,e),createPendingTransactionFilter:()=>_g(t),estimateContractGas:e=>$b(t,e),estimateGas:e=>fh(t,e),getBalance:e=>US(t,e),getBlobBaseFee:()=>FS(t),getBlock:e=>Sr(t,e),getBlockNumber:e=>ka(t,e),getBlockTransactionCount:e=>$S(t,e),getBytecode:e=>nd(t,e),getChainId:()=>hs(t),getCode:e=>nd(t,e),getContractEvents:e=>ph(t,e),getEip712Domain:e=>DS(t,e),getEnsAddress:e=>vS(t,e),getEnsAvatar:e=>NS(t,e),getEnsName:e=>RS(t,e),getEnsResolver:e=>MS(t,e),getEnsText:e=>kg(t,e),getFeeHistory:e=>VS(t,e),estimateFeesPerGas:e=>tE(t,e),getFilterChanges:e=>tu(t,e),getFilterLogs:e=>GS(t,e),getGasPrice:()=>nh(t),getLogs:e=>hh(t,e),getProof:e=>Yk(t,e),estimateMaxPriorityFeePerGas:e=>eE(t,e),fillTransaction:e=>uh(t,e),getStorageAt:e=>Jk(t,e),getTransaction:e=>Fh(t,e),getTransactionConfirmations:e=>Zk(t,e),getTransactionCount:e=>sh(t,e),getTransactionReceipt:e=>oc(t,e),multicall:e=>Qk(t,e),prepareTransactionRequest:e=>wa(t,e),readContract:e=>hr(t,e),sendRawTransaction:e=>Sh(t,e),sendRawTransactionSync:e=>$h(t,e),simulate:e=>fd(t,e),simulateBlocks:e=>fd(t,e),simulateCalls:e=>ux(t,e),simulateContract:e=>lg(t,e),verifyHash:e=>au(t,e),verifyMessage:e=>gx(t,e),verifySiweMessage:e=>_x(t,e),verifyTypedData:e=>wx(t,e),uninstallFilter:e=>ru(t,e),waitForTransactionReceipt:e=>mw(t,e),watchBlocks:e=>vx(t,e),watchBlockNumber:e=>yw(t,e),watchContractEvent:e=>fg(t,e),watchEvent:e=>Ex(t,e),watchPendingTransactions:e=>Sx(t,e)}}function Ox(t){const{key:e="public",name:r="Public Client"}=t;return wg({...t,key:e,name:r,type:"publicClient"}).extend(Px)}async function Ix(t,{chain:e}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:o}=e;await t.request({method:"wallet_addEthereumChain",params:[{chainId:J(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function Bx(t,e){const{abi:r,args:n,bytecode:s,...i}=e,o=eu({abi:r,args:n,bytecode:s});return nu(t,{...i,...i.authorizationList?{to:null}:{},data:o})}async function Cx(t){var r;return((r=t.account)==null?void 0:r.type)==="local"?[t.account.address]:(await t.request({method:"eth_accounts"},{dedupe:!0})).map(n=>da(n))}async function Nx(t,e={}){const{account:r=t.account,chainId:n}=e,s=r?Fe(r):void 0,i=n?[s==null?void 0:s.address,[J(n)]]:[s==null?void 0:s.address],o=await t.request({method:"wallet_getCapabilities",params:i}),a={};for(const[c,u]of Object.entries(o)){a[Number(c)]={};for(let[l,f]of Object.entries(u))l==="addSubAccount"&&(l="unstable_addSubAccount"),a[Number(c)][l]=f}return typeof n=="number"?a[n]:a}async function Rx(t){return await t.request({method:"wallet_getPermissions"},{dedupe:!0})}async function bw(t,e){var c;const{account:r=t.account,chainId:n,nonce:s}=e;if(!r)throw new ps({docsPath:"/docs/eip7702/prepareAuthorization"});const i=Fe(r),o=(()=>{if(e.executor)return e.executor==="self"?e.executor:Fe(e.executor)})(),a={address:e.contractAddress??e.address,chainId:n,nonce:s};return typeof a.chainId>"u"&&(a.chainId=((c=t.chain)==null?void 0:c.id)??await ne(t,hs,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await ne(t,sh,"getTransactionCount")({address:i.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&Wi(o.address,i.address))&&(a.nonce+=1)),a}async function Mx(t){return(await t.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Gd(r))}async function jx(t,e){return t.request({method:"wallet_requestPermissions",params:[e]},{retryCount:0})}async function Ux(t,e){const{chain:r=t.chain}=e,n=e.timeout??Math.max(((r==null?void 0:r.blockTime)??0)*3,5e3),s=await yg(t,e);return await bg(t,{...e,id:s.id,timeout:n})}const rl=new Gi(128);async function gw(t,e){var k,_,O,B;const{account:r=t.account,chain:n=t.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,pollingInterval:p,throwOnReceiptRevert:m,type:v,value:S,...T}=e,g=e.timeout??Math.max(((n==null?void 0:n.blockTime)??0)*3,5e3);if(typeof r>"u")throw new ps({docsPath:"/docs/actions/wallet/sendTransactionSync"});const w=r?Fe(r):null;try{Nn(e);const N=await(async()=>{if(e.to)return e.to;if(e.to!==null&&i&&i.length>0)return await qc({authorization:i[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`.")})})();if((w==null?void 0:w.type)==="json-rpc"||w===null){let $;n!==null&&($=await ne(t,hs,"getChainId")({}),Eh({currentChainId:$,chain:n}));const j=(O=(_=(k=t.chain)==null?void 0:k.formatters)==null?void 0:_.transactionRequest)==null?void 0:O.format,G=(j||ds)({...qi(T,{format:j}),accessList:s,account:w,authorizationList:i,blobs:o,chainId:$,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,to:N,type:v,value:S},"sendTransaction"),ee=rl.get(t.uid),U=ee?"wallet_sendTransaction":"eth_sendTransaction",X=await(async()=>{try{return await t.request({method:U,params:[G]},{retryCount:0})}catch(W){if(ee===!1)throw W;const C=W;if(C.name==="InvalidInputRpcError"||C.name==="InvalidParamsRpcError"||C.name==="MethodNotFoundRpcError"||C.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[G]},{retryCount:0}).then(D=>(rl.set(t.uid,!0),D)).catch(D=>{const Z=D;throw Z.name==="MethodNotFoundRpcError"||Z.name==="MethodNotSupportedRpcError"?(rl.set(t.uid,!1),C):Z});throw C}})(),te=await ne(t,mw,"waitForTransactionReceipt")({checkReplacement:!1,hash:X,pollingInterval:p,timeout:g});if(m&&te.status==="reverted")throw new gb({receipt:te});return te}if((w==null?void 0:w.type)==="local"){const $=await ne(t,wa,"prepareTransactionRequest")({account:w,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,nonceManager:w.nonceManager,parameters:[...lh,"sidecars"],type:v,value:S,...T,to:N}),j=(B=n==null?void 0:n.serializers)==null?void 0:B.transaction,H=await w.signTransaction($,{serializer:j});return await ne(t,$h,"sendRawTransactionSync")({serializedTransaction:H,throwOnReceiptRevert:m})}throw(w==null?void 0:w.type)==="smart"?new Cs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Cs({docsPath:"/docs/actions/wallet/sendTransactionSync",type:w==null?void 0:w.type})}catch(N){throw N instanceof Cs?N:Xc(N,{...e,account:w,chain:e.chain||void 0})}}async function Fx(t,e){const{id:r}=e;await t.request({method:"wallet_showCallsStatus",params:[r]})}async function $x(t,e){const{account:r=t.account}=e;if(!r)throw new ps({docsPath:"/docs/eip7702/signAuthorization"});const n=Fe(r);if(!n.signAuthorization)throw new Cs({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await bw(t,e);return n.signAuthorization(s)}async function Lx(t,{account:e=t.account,message:r}){if(!e)throw new ps({docsPath:"/docs/actions/wallet/signMessage"});const n=Fe(e);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?Bi(r):r.raw instanceof Uint8Array?Ot(r.raw):r.raw;return t.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function Dx(t,e){var u,l,f,h;const{account:r=t.account,chain:n=t.chain,...s}=e;if(!r)throw new ps({docsPath:"/docs/actions/wallet/signTransaction"});const i=Fe(r);Nn({account:i,...e});const o=await ne(t,hs,"getChainId")({});n!==null&&Eh({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((u=t.chain)==null?void 0:u.formatters),c=((l=a==null?void 0:a.transactionRequest)==null?void 0:l.format)||ds;return i.signTransaction?i.signTransaction({...s,chainId:o},{serializer:(h=(f=t.chain)==null?void 0:f.serializers)==null?void 0:h.transaction}):await t.request({method:"eth_signTransaction",params:[{...c({...s,account:i},"signTransaction"),chainId:J(o),from:i.address}]},{retryCount:0})}async function Hx(t,e){const{account:r=t.account,domain:n,message:s,primaryType:i}=e;if(!r)throw new ps({docsPath:"/docs/actions/wallet/signTypedData"});const o=Fe(r),a={EIP712Domain:jg({domain:n}),...e.types};if(Mg({domain:n,message:s,primaryType:i,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:s,primaryType:i,types:a});const c=xA({domain:n,message:s,primaryType:i,types:a});return t.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function zx(t,{id:e}){await t.request({method:"wallet_switchEthereumChain",params:[{chainId:J(e)}]},{retryCount:0})}async function Vx(t,e){return await t.request({method:"wallet_watchAsset",params:e},{retryCount:0})}async function Gx(t,e){return Mi.internal(t,gw,"sendTransactionSync",e)}function qx(t){return{addChain:e=>Ix(t,e),deployContract:e=>Bx(t,e),fillTransaction:e=>uh(t,e),getAddresses:()=>Cx(t),getCallsStatus:e=>mg(t,e),getCapabilities:e=>Nx(t,e),getChainId:()=>hs(t),getPermissions:()=>Rx(t),prepareAuthorization:e=>bw(t,e),prepareTransactionRequest:e=>wa(t,e),requestAddresses:()=>Mx(t),requestPermissions:e=>jx(t,e),sendCalls:e=>yg(t,e),sendCallsSync:e=>Ux(t,e),sendRawTransaction:e=>Sh(t,e),sendRawTransactionSync:e=>$h(t,e),sendTransaction:e=>nu(t,e),sendTransactionSync:e=>gw(t,e),showCallsStatus:e=>Fx(t,e),signAuthorization:e=>$x(t,e),signMessage:e=>Lx(t,e),signTransaction:e=>Dx(t,e),signTypedData:e=>Hx(t,e),switchChain:e=>zx(t,e),waitForCallsStatus:e=>bg(t,e),watchAsset:e=>Vx(t,e),writeContract:e=>Mi(t,e),writeContractSync:e=>Gx(t,e)}}function nl(t){const{key:e="wallet",name:r="Wallet Client",transport:n}=t;return wg({...t,key:e,name:r,transport:n,type:"walletClient"}).extend(qx)}function ww({key:t,methods:e,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const u=gg();return{config:{key:t,methods:e,name:r,request:n,retryCount:s,retryDelay:i,timeout:o,type:a},request:iA(n,{methods:e,retryCount:s,retryDelay:i,uid:u}),value:c}}function w0(t,e={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=e;return({retryCount:o})=>ww({key:r,methods:n,name:s,request:t.request.bind(t),retryCount:e.retryCount??o,retryDelay:i,type:"custom"})}class Wx extends q{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function vw(t,e={}){const{batch:r,fetchFn:n,fetchOptions:s,key:i="http",methods:o,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:l,raw:f}=e;return({chain:h,retryCount:d,timeout:p})=>{const{batchSize:m=1e3,wait:v=0}=typeof r=="object"?r:{},S=e.retryCount??d,T=p??e.timeout??1e4,g=h==null?void 0:h.rpcUrls.default.http[0];if(!g)throw new Wx;const w=wA(g,{fetchFn:n,fetchOptions:s,onRequest:c,onResponse:u,timeout:T});return ww({key:i,methods:o,name:a,async request({method:k,params:_}){const O={method:k,params:_},{schedule:B}=cg({id:g,wait:v,shouldSplitBatch(H){return H.length>m},fn:H=>w.request({body:H}),sort:(H,G)=>H.id-G.id}),N=async H=>r?B(H):[await w.request({body:H})],[{error:$,result:j}]=await N(O);if(f)return{error:$,result:j};if($)throw new Zd({body:O,error:$,url:g});return j},retryCount:S,retryDelay:l,timeout:T,type:"http"},{fetchOptions:s,url:g})}}const ac={mainnet:{baseurl:"https://api.garden.finance",auth:"https://api.garden.finance/auth",relayer:"https://relayer.garden.finance"},testnet:{baseurl:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",relayer:"https://testnet.api.garden.finance/relayer"},localnet:{baseurl:"",auth:"",relayer:""}},Qo={[E.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://rpc.starknet.lava.build"},[E.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia-rpc.publicnode.com"},[E.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Ew={[E.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[E.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[E.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},pd={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},yd={[E.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[E.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[E.Network.LOCALNET]:{packageId:"",moduleName:""}},Sw={[E.Network.MAINNET]:"https://api.trongrid.io",[E.Network.TESTNET]:"https://api.shasta.trongrid.io",[E.Network.LOCALNET]:""},Aw={[E.Network.MAINNET]:"wss://s.altnet.rippletest.net:51233",[E.Network.TESTNET]:"wss://s.altnet.rippletest.net:51233",[E.Network.LOCALNET]:""},Kx={asset:V.ChainAsset.from(V.Assets.base.cBBTC)};var wo=(t=>(t.orderCreated="orderCreated",t.orderInitiating="orderInitiating",t.orderInitiated="orderInitiated",t))(wo||{}),ki=(t=>(t.SLOW="SLOW",t.MEDIUM="MEDIUM",t.FAST="FAST",t))(ki||{}),xr=(t=>(t.Mainnet="Mainnet",t.Testnet="Testnet",t.Regtest="Regtest",t))(xr||{}),cc=(t=>(t.ALL="ALL",t.IN="IN",t.OUT="OUT",t))(cc||{});const Xx={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function md(t){const e=typeof t=="string"?t:t.network,r=e===E.Network.MAINNET?ac.mainnet:E.Network.TESTNET?ac.testnet:ac.localnet;return{api:typeof t=="string"?r:{...r,...t},network:e}}function Yx(t){return typeof t=="string"&&(t=Buffer.from(t,"hex")),t.length===32?t:t.subarray(1,33)}function v0(t,e){if(!t)throw new Error(e)}function Jx(t){return Buffer.concat([Uint8Array.from([192]),Zx(t)])}function Zx(t){const e=Sp.encodingLength(t.length),r=Buffer.allocUnsafe(e);return Sp.encode(t.length,r),Buffer.concat([r,t])}function Qx(t,e){if(t.compare(e)>0){const r=t;t=e,e=r}return[t,e]}const $e=t=>t.length===64?t:t.slice(2),eT=t=>{if(!t)return!1;try{const e=Buffer.from(t,"hex");return lr.isPoint(e)}catch{return!1}},tT=(t,e,r,n)=>t+":"+e.toLowerCase()+"::"+r+":"+n.toLowerCase();function rT(t,e){if(!t)return!1;const r=e===E.Environment.MAINNET?Ae.networks.bitcoin:e===E.Environment.TESTNET?Ae.networks.testnet:Ae.networks.regtest;if(!r)return!1;Ae.initEccLib(lr);try{return Ae.address.toOutputScript(t,r),!0}catch{return!1}}function nT(t,e){if(!t)return!1;let r;if(e===E.Environment.MAINNET?r=Ma.Networks.livenet:(E.Environment.TESTNET,r=Ma.Networks.testnet),!r)return!1;try{return Ma.Address.fromString(t,r),!0}catch{return!1}}function ro(t,e){const r=[];for(let n=0;n<e;n++)r.push(t);return r}const sT=t=>{switch(t){case E.Network.MAINNET:return xr.Mainnet;case E.Network.TESTNET:return xr.Testnet;case E.Network.LOCALNET:return xr.Regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},iT=t=>{switch(t){case E.Network.MAINNET:return Ae.networks.bitcoin;case E.Network.TESTNET:return Ae.networks.testnet;case E.Network.LOCALNET:return Ae.networks.regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},oT=t=>{const e=t.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(e)},E0=t=>{if(typeof t=="object"&&"r"in t&&"s"in t)return E.Ok([t.r.toString(),t.s.toString()]);if(Array.isArray(t)){const e=t.map(r=>typeof r=="string"&&r.startsWith("0x")&&oT(r)?BigInt(r).toString():r);return E.Ok(e.join(","))}return E.Err("Invalid signature format")};function bd(t){return Buffer.from(t,"hex").reverse()}function gd(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}const Va=async(t,e)=>{const r=Date.now(),n=3e4,s=2e3;for(;Date.now()-r<n;){const i=await t.getLatestBlockhash(),o=await t.confirmTransaction({signature:e,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed");if(o.value&&o.value.err==null)return console.log("Tx Confirmed ✅",e),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(a=>setTimeout(a,s))}return!1},ji=async(t,e)=>{var a,c;const r=await E.Fetcher.get(e+"/v2/assets");if(r.error)return E.Err("Failed to fetch asset info: "+r.error);const s=(r.result||[]).find(u=>u.id===t);if(!s)return E.Err(`Asset info not found for asset id: ${t}`);const i=((a=s.htlc)==null?void 0:a.address)||"",o=((c=s.token)==null?void 0:c.address)||"";return E.Ok({htlcAddress:i,tokenAddress:o})},S0=t=>{if(t==null||t.includes("."))return E.Err("Invalid amount ",t);const e=new Cf.BigNumber(t);return!e.isInteger()||e.isNaN()||e.lt(0)||e.isLessThanOrEqualTo(0)?E.Err("Invalid amount ",t):E.Ok(e)},aT=async(t,e)=>{const r={[V.BlockchainType.evm]:{htlc:e.evm,name:"EVM"},[V.BlockchainType.solana]:{htlc:e.solana,name:"Solana"},[V.BlockchainType.starknet]:{htlc:e.starknet,name:"Starknet"},[V.BlockchainType.sui]:{htlc:e.sui,name:"Sui"},[V.BlockchainType.bitcoin]:{htlc:e.bitcoin,name:"Bitcoin"},[V.BlockchainType.tron]:{htlc:e.tron,name:"Tron"},[V.BlockchainType.litecoin]:{htlc:e.litecoin,name:"Litecoin"},[V.BlockchainType.alpen_signet]:{htlc:e.alpen_signet,name:"Alpen Signet"},[V.BlockchainType.xrpl]:{htlc:e.xrpl,name:"XRPL"}};if(t===V.BlockchainType.bitcoin||t===V.BlockchainType.litecoin||t===V.BlockchainType.alpen_signet)return E.Ok(void 0);const n=r[t];return n?n.htlc?E.Ok(void 0):E.Err(`${n.name} HTLC is required for swap initiation. Please provide ${n.name.toLowerCase()}HTLC when initializing garden.`):E.Err(`Unsupported blockchain type for swap initiation: ${t}`)},cT=["0x90c06174","0xee1b963b"],uT=t=>{if(!t)return"";if(typeof t=="string")return t;if(t instanceof Error)return[t.message,t.shortMessage,t.reason,t.signature,t.stack].filter(Boolean).join(" | ");if(typeof t=="object"){const e=t.message;if(typeof e=="string")return e;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)},Lh=t=>{const e=uT(t).toLowerCase();return cT.some(r=>e.includes(r.toLowerCase()))},lT=t=>t.toLowerCase().includes("not supported for initiations"),kw=async({attempt:t,wallet:e,maxAttempts:r=1,baseDelayMs:n=1e3})=>{var s;for(let i=0;i<r;i++){const o=await t();if(o.error&&lT(o.error))break;if(o.ok){const a=await E.waitForTransactionReceipt(e,o.val);if(!a.ok){if(i<r-1){await E.sleep(n*2**i);continue}break}if(((s=a.val)==null?void 0:s.status)==="success")return o.val}i<r-1&&await E.sleep(n*2**i)}return null},fT=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),dT=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),hT=Buffer.concat([fT,dT]),pT=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),A0={failedToCreateInternalPubkey:"failed to create internal pubkey"};function k0(){const t=pe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),e=lr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),hT]),t);if(!e)throw new Error(A0.failedToCreateInternalPubkey);const r=lr.pointAdd(pT,e);if(!r)throw new Error(A0.failedToCreateInternalPubkey);return Yx(Buffer.from(r))}var Br=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function xw(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}var Le={},gt={},Zs={},cu={};cu.byteLength=bT;cu.toByteArray=wT;cu.fromByteArray=ST;var Xr=[],ar=[],yT=typeof Uint8Array<"u"?Uint8Array:Array,sl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var oi=0,mT=sl.length;oi<mT;++oi)Xr[oi]=sl[oi],ar[sl.charCodeAt(oi)]=oi;ar[45]=62;ar[95]=63;function Tw(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function bT(t){var e=Tw(t),r=e[0],n=e[1];return(r+n)*3/4-n}function gT(t,e,r){return(e+r)*3/4-r}function wT(t){var e,r=Tw(t),n=r[0],s=r[1],i=new yT(gT(t,n,s)),o=0,a=s>0?n-4:n,c;for(c=0;c<a;c+=4)e=ar[t.charCodeAt(c)]<<18|ar[t.charCodeAt(c+1)]<<12|ar[t.charCodeAt(c+2)]<<6|ar[t.charCodeAt(c+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=ar[t.charCodeAt(c)]<<2|ar[t.charCodeAt(c+1)]>>4,i[o++]=e&255),s===1&&(e=ar[t.charCodeAt(c)]<<10|ar[t.charCodeAt(c+1)]<<4|ar[t.charCodeAt(c+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function vT(t){return Xr[t>>18&63]+Xr[t>>12&63]+Xr[t>>6&63]+Xr[t&63]}function ET(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(vT(n));return s.join("")}function ST(t){for(var e,r=t.length,n=r%3,s=[],i=16383,o=0,a=r-n;o<a;o+=i)s.push(ET(t,o,o+i>a?a:o+i));return n===1?(e=t[r-1],s.push(Xr[e>>2]+Xr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Xr[e>>10]+Xr[e>>4&63]+Xr[e<<2&63]+"=")),s.join("")}var Dh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Dh.read=function(t,e,r,n,s){var i,o,a=s*8-n-1,c=(1<<a)-1,u=c>>1,l=-7,f=r?s-1:0,h=r?-1:1,d=t[e+f];for(f+=h,i=d&(1<<-l)-1,d>>=-l,l+=a;l>0;i=i*256+t[e+f],f+=h,l-=8);for(o=i&(1<<-l)-1,i>>=-l,l+=n;l>0;o=o*256+t[e+f],f+=h,l-=8);if(i===0)i=1-u;else{if(i===c)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,n),i=i-u}return(d?-1:1)*o*Math.pow(2,i-n)};Dh.write=function(t,e,r,n,s,i){var o,a,c,u=i*8-s-1,l=(1<<u)-1,f=l>>1,h=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,p=n?1:-1,m=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+f>=1?e+=h/c:e+=h*Math.pow(2,1-f),e*c>=2&&(o++,c/=2),o+f>=l?(a=0,o=l):o+f>=1?(a=(e*c-1)*Math.pow(2,s),o=o+f):(a=e*Math.pow(2,f-1)*Math.pow(2,s),o=0));s>=8;t[r+d]=a&255,d+=p,a/=256,s-=8);for(o=o<<s|a,u+=s;u>0;t[r+d]=o&255,d+=p,o/=256,u-=8);t[r+d-p]|=m*128};/*!
45
+ * The buffer module from node.js, for the browser.
46
+ *
47
+ * @author Feross Aboukhadijeh <https://feross.org>
48
+ * @license MIT
49
+ */(function(t){const e=cu,r=Dh,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=a,t.SlowBuffer=T,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s,a.TYPED_ARRAY_SUPPORT=i(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const x=new Uint8Array(1),y={foo:function(){return 42}};return Object.setPrototypeOf(y,Uint8Array.prototype),Object.setPrototypeOf(x,y),x.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(x){if(x>s)throw new RangeError('The value "'+x+'" is invalid for option "size"');const y=new Uint8Array(x);return Object.setPrototypeOf(y,a.prototype),y}function a(x,y,b){if(typeof x=="number"){if(typeof y=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(x)}return c(x,y,b)}a.poolSize=8192;function c(x,y,b){if(typeof x=="string")return h(x,y);if(ArrayBuffer.isView(x))return p(x);if(x==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof x);if(Et(x,ArrayBuffer)||x&&Et(x.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Et(x,SharedArrayBuffer)||x&&Et(x.buffer,SharedArrayBuffer)))return m(x,y,b);if(typeof x=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const P=x.valueOf&&x.valueOf();if(P!=null&&P!==x)return a.from(P,y,b);const M=v(x);if(M)return M;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof x[Symbol.toPrimitive]=="function")return a.from(x[Symbol.toPrimitive]("string"),y,b);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof x)}a.from=function(x,y,b){return c(x,y,b)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function u(x){if(typeof x!="number")throw new TypeError('"size" argument must be of type number');if(x<0)throw new RangeError('The value "'+x+'" is invalid for option "size"')}function l(x,y,b){return u(x),x<=0?o(x):y!==void 0?typeof b=="string"?o(x).fill(y,b):o(x).fill(y):o(x)}a.alloc=function(x,y,b){return l(x,y,b)};function f(x){return u(x),o(x<0?0:S(x)|0)}a.allocUnsafe=function(x){return f(x)},a.allocUnsafeSlow=function(x){return f(x)};function h(x,y){if((typeof y!="string"||y==="")&&(y="utf8"),!a.isEncoding(y))throw new TypeError("Unknown encoding: "+y);const b=g(x,y)|0;let P=o(b);const M=P.write(x,y);return M!==b&&(P=P.slice(0,M)),P}function d(x){const y=x.length<0?0:S(x.length)|0,b=o(y);for(let P=0;P<y;P+=1)b[P]=x[P]&255;return b}function p(x){if(Et(x,Uint8Array)){const y=new Uint8Array(x);return m(y.buffer,y.byteOffset,y.byteLength)}return d(x)}function m(x,y,b){if(y<0||x.byteLength<y)throw new RangeError('"offset" is outside of buffer bounds');if(x.byteLength<y+(b||0))throw new RangeError('"length" is outside of buffer bounds');let P;return y===void 0&&b===void 0?P=new Uint8Array(x):b===void 0?P=new Uint8Array(x,y):P=new Uint8Array(x,y,b),Object.setPrototypeOf(P,a.prototype),P}function v(x){if(a.isBuffer(x)){const y=S(x.length)|0,b=o(y);return b.length===0||x.copy(b,0,0,y),b}if(x.length!==void 0)return typeof x.length!="number"||Rn(x.length)?o(0):d(x);if(x.type==="Buffer"&&Array.isArray(x.data))return d(x.data)}function S(x){if(x>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return x|0}function T(x){return+x!=x&&(x=0),a.alloc(+x)}a.isBuffer=function(y){return y!=null&&y._isBuffer===!0&&y!==a.prototype},a.compare=function(y,b){if(Et(y,Uint8Array)&&(y=a.from(y,y.offset,y.byteLength)),Et(b,Uint8Array)&&(b=a.from(b,b.offset,b.byteLength)),!a.isBuffer(y)||!a.isBuffer(b))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(y===b)return 0;let P=y.length,M=b.length;for(let L=0,K=Math.min(P,M);L<K;++L)if(y[L]!==b[L]){P=y[L],M=b[L];break}return P<M?-1:M<P?1:0},a.isEncoding=function(y){switch(String(y).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(y,b){if(!Array.isArray(y))throw new TypeError('"list" argument must be an Array of Buffers');if(y.length===0)return a.alloc(0);let P;if(b===void 0)for(b=0,P=0;P<y.length;++P)b+=y[P].length;const M=a.allocUnsafe(b);let L=0;for(P=0;P<y.length;++P){let K=y[P];if(Et(K,Uint8Array))L+K.length>M.length?(a.isBuffer(K)||(K=a.from(K)),K.copy(M,L)):Uint8Array.prototype.set.call(M,K,L);else if(a.isBuffer(K))K.copy(M,L);else throw new TypeError('"list" argument must be an Array of Buffers');L+=K.length}return M};function g(x,y){if(a.isBuffer(x))return x.length;if(ArrayBuffer.isView(x)||Et(x,ArrayBuffer))return x.byteLength;if(typeof x!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof x);const b=x.length,P=arguments.length>2&&arguments[2]===!0;if(!P&&b===0)return 0;let M=!1;for(;;)switch(y){case"ascii":case"latin1":case"binary":return b;case"utf8":case"utf-8":return Mr(x).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b*2;case"hex":return b>>>1;case"base64":return jr(x).length;default:if(M)return P?-1:Mr(x).length;y=(""+y).toLowerCase(),M=!0}}a.byteLength=g;function w(x,y,b){let P=!1;if((y===void 0||y<0)&&(y=0),y>this.length||((b===void 0||b>this.length)&&(b=this.length),b<=0)||(b>>>=0,y>>>=0,b<=y))return"";for(x||(x="utf8");;)switch(x){case"hex":return C(this,y,b);case"utf8":case"utf-8":return ee(this,y,b);case"ascii":return te(this,y,b);case"latin1":case"binary":return W(this,y,b);case"base64":return G(this,y,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,y,b);default:if(P)throw new TypeError("Unknown encoding: "+x);x=(x+"").toLowerCase(),P=!0}}a.prototype._isBuffer=!0;function k(x,y,b){const P=x[y];x[y]=x[b],x[b]=P}a.prototype.swap16=function(){const y=this.length;if(y%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let b=0;b<y;b+=2)k(this,b,b+1);return this},a.prototype.swap32=function(){const y=this.length;if(y%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let b=0;b<y;b+=4)k(this,b,b+3),k(this,b+1,b+2);return this},a.prototype.swap64=function(){const y=this.length;if(y%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let b=0;b<y;b+=8)k(this,b,b+7),k(this,b+1,b+6),k(this,b+2,b+5),k(this,b+3,b+4);return this},a.prototype.toString=function(){const y=this.length;return y===0?"":arguments.length===0?ee(this,0,y):w.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(y){if(!a.isBuffer(y))throw new TypeError("Argument must be a Buffer");return this===y?!0:a.compare(this,y)===0},a.prototype.inspect=function(){let y="";const b=t.INSPECT_MAX_BYTES;return y=this.toString("hex",0,b).replace(/(.{2})/g,"$1 ").trim(),this.length>b&&(y+=" ... "),"<Buffer "+y+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(y,b,P,M,L){if(Et(y,Uint8Array)&&(y=a.from(y,y.offset,y.byteLength)),!a.isBuffer(y))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof y);if(b===void 0&&(b=0),P===void 0&&(P=y?y.length:0),M===void 0&&(M=0),L===void 0&&(L=this.length),b<0||P>y.length||M<0||L>this.length)throw new RangeError("out of range index");if(M>=L&&b>=P)return 0;if(M>=L)return-1;if(b>=P)return 1;if(b>>>=0,P>>>=0,M>>>=0,L>>>=0,this===y)return 0;let K=L-M,be=P-b;const ze=Math.min(K,be),je=this.slice(M,L),Ve=y.slice(b,P);for(let Te=0;Te<ze;++Te)if(je[Te]!==Ve[Te]){K=je[Te],be=Ve[Te];break}return K<be?-1:be<K?1:0};function _(x,y,b,P,M){if(x.length===0)return-1;if(typeof b=="string"?(P=b,b=0):b>2147483647?b=2147483647:b<-2147483648&&(b=-2147483648),b=+b,Rn(b)&&(b=M?0:x.length-1),b<0&&(b=x.length+b),b>=x.length){if(M)return-1;b=x.length-1}else if(b<0)if(M)b=0;else return-1;if(typeof y=="string"&&(y=a.from(y,P)),a.isBuffer(y))return y.length===0?-1:O(x,y,b,P,M);if(typeof y=="number")return y=y&255,typeof Uint8Array.prototype.indexOf=="function"?M?Uint8Array.prototype.indexOf.call(x,y,b):Uint8Array.prototype.lastIndexOf.call(x,y,b):O(x,[y],b,P,M);throw new TypeError("val must be string, number or Buffer")}function O(x,y,b,P,M){let L=1,K=x.length,be=y.length;if(P!==void 0&&(P=String(P).toLowerCase(),P==="ucs2"||P==="ucs-2"||P==="utf16le"||P==="utf-16le")){if(x.length<2||y.length<2)return-1;L=2,K/=2,be/=2,b/=2}function ze(Ve,Te){return L===1?Ve[Te]:Ve.readUInt16BE(Te*L)}let je;if(M){let Ve=-1;for(je=b;je<K;je++)if(ze(x,je)===ze(y,Ve===-1?0:je-Ve)){if(Ve===-1&&(Ve=je),je-Ve+1===be)return Ve*L}else Ve!==-1&&(je-=je-Ve),Ve=-1}else for(b+be>K&&(b=K-be),je=b;je>=0;je--){let Ve=!0;for(let Te=0;Te<be;Te++)if(ze(x,je+Te)!==ze(y,Te)){Ve=!1;break}if(Ve)return je}return-1}a.prototype.includes=function(y,b,P){return this.indexOf(y,b,P)!==-1},a.prototype.indexOf=function(y,b,P){return _(this,y,b,P,!0)},a.prototype.lastIndexOf=function(y,b,P){return _(this,y,b,P,!1)};function B(x,y,b,P){b=Number(b)||0;const M=x.length-b;P?(P=Number(P),P>M&&(P=M)):P=M;const L=y.length;P>L/2&&(P=L/2);let K;for(K=0;K<P;++K){const be=parseInt(y.substr(K*2,2),16);if(Rn(be))return K;x[b+K]=be}return K}function N(x,y,b,P){return vt(Mr(y,x.length-b),x,b,P)}function $(x,y,b,P){return vt(ms(y),x,b,P)}function j(x,y,b,P){return vt(jr(y),x,b,P)}function H(x,y,b,P){return vt(Y(y,x.length-b),x,b,P)}a.prototype.write=function(y,b,P,M){if(b===void 0)M="utf8",P=this.length,b=0;else if(P===void 0&&typeof b=="string")M=b,P=this.length,b=0;else if(isFinite(b))b=b>>>0,isFinite(P)?(P=P>>>0,M===void 0&&(M="utf8")):(M=P,P=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const L=this.length-b;if((P===void 0||P>L)&&(P=L),y.length>0&&(P<0||b<0)||b>this.length)throw new RangeError("Attempt to write outside buffer bounds");M||(M="utf8");let K=!1;for(;;)switch(M){case"hex":return B(this,y,b,P);case"utf8":case"utf-8":return N(this,y,b,P);case"ascii":case"latin1":case"binary":return $(this,y,b,P);case"base64":return j(this,y,b,P);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,y,b,P);default:if(K)throw new TypeError("Unknown encoding: "+M);M=(""+M).toLowerCase(),K=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function G(x,y,b){return y===0&&b===x.length?e.fromByteArray(x):e.fromByteArray(x.slice(y,b))}function ee(x,y,b){b=Math.min(x.length,b);const P=[];let M=y;for(;M<b;){const L=x[M];let K=null,be=L>239?4:L>223?3:L>191?2:1;if(M+be<=b){let ze,je,Ve,Te;switch(be){case 1:L<128&&(K=L);break;case 2:ze=x[M+1],(ze&192)===128&&(Te=(L&31)<<6|ze&63,Te>127&&(K=Te));break;case 3:ze=x[M+1],je=x[M+2],(ze&192)===128&&(je&192)===128&&(Te=(L&15)<<12|(ze&63)<<6|je&63,Te>2047&&(Te<55296||Te>57343)&&(K=Te));break;case 4:ze=x[M+1],je=x[M+2],Ve=x[M+3],(ze&192)===128&&(je&192)===128&&(Ve&192)===128&&(Te=(L&15)<<18|(ze&63)<<12|(je&63)<<6|Ve&63,Te>65535&&Te<1114112&&(K=Te))}}K===null?(K=65533,be=1):K>65535&&(K-=65536,P.push(K>>>10&1023|55296),K=56320|K&1023),P.push(K),M+=be}return X(P)}const U=4096;function X(x){const y=x.length;if(y<=U)return String.fromCharCode.apply(String,x);let b="",P=0;for(;P<y;)b+=String.fromCharCode.apply(String,x.slice(P,P+=U));return b}function te(x,y,b){let P="";b=Math.min(x.length,b);for(let M=y;M<b;++M)P+=String.fromCharCode(x[M]&127);return P}function W(x,y,b){let P="";b=Math.min(x.length,b);for(let M=y;M<b;++M)P+=String.fromCharCode(x[M]);return P}function C(x,y,b){const P=x.length;(!y||y<0)&&(y=0),(!b||b<0||b>P)&&(b=P);let M="";for(let L=y;L<b;++L)M+=ni[x[L]];return M}function D(x,y,b){const P=x.slice(y,b);let M="";for(let L=0;L<P.length-1;L+=2)M+=String.fromCharCode(P[L]+P[L+1]*256);return M}a.prototype.slice=function(y,b){const P=this.length;y=~~y,b=b===void 0?P:~~b,y<0?(y+=P,y<0&&(y=0)):y>P&&(y=P),b<0?(b+=P,b<0&&(b=0)):b>P&&(b=P),b<y&&(b=y);const M=this.subarray(y,b);return Object.setPrototypeOf(M,a.prototype),M};function Z(x,y,b){if(x%1!==0||x<0)throw new RangeError("offset is not uint");if(x+y>b)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(y,b,P){y=y>>>0,b=b>>>0,P||Z(y,b,this.length);let M=this[y],L=1,K=0;for(;++K<b&&(L*=256);)M+=this[y+K]*L;return M},a.prototype.readUintBE=a.prototype.readUIntBE=function(y,b,P){y=y>>>0,b=b>>>0,P||Z(y,b,this.length);let M=this[y+--b],L=1;for(;b>0&&(L*=256);)M+=this[y+--b]*L;return M},a.prototype.readUint8=a.prototype.readUInt8=function(y,b){return y=y>>>0,b||Z(y,1,this.length),this[y]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(y,b){return y=y>>>0,b||Z(y,2,this.length),this[y]|this[y+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(y,b){return y=y>>>0,b||Z(y,2,this.length),this[y]<<8|this[y+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(y,b){return y=y>>>0,b||Z(y,4,this.length),(this[y]|this[y+1]<<8|this[y+2]<<16)+this[y+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(y,b){return y=y>>>0,b||Z(y,4,this.length),this[y]*16777216+(this[y+1]<<16|this[y+2]<<8|this[y+3])},a.prototype.readBigUInt64LE=Mn(function(y){y=y>>>0,ve(y,"offset");const b=this[y],P=this[y+7];(b===void 0||P===void 0)&&ke(y,this.length-8);const M=b+this[++y]*2**8+this[++y]*2**16+this[++y]*2**24,L=this[++y]+this[++y]*2**8+this[++y]*2**16+P*2**24;return BigInt(M)+(BigInt(L)<<BigInt(32))}),a.prototype.readBigUInt64BE=Mn(function(y){y=y>>>0,ve(y,"offset");const b=this[y],P=this[y+7];(b===void 0||P===void 0)&&ke(y,this.length-8);const M=b*2**24+this[++y]*2**16+this[++y]*2**8+this[++y],L=this[++y]*2**24+this[++y]*2**16+this[++y]*2**8+P;return(BigInt(M)<<BigInt(32))+BigInt(L)}),a.prototype.readIntLE=function(y,b,P){y=y>>>0,b=b>>>0,P||Z(y,b,this.length);let M=this[y],L=1,K=0;for(;++K<b&&(L*=256);)M+=this[y+K]*L;return L*=128,M>=L&&(M-=Math.pow(2,8*b)),M},a.prototype.readIntBE=function(y,b,P){y=y>>>0,b=b>>>0,P||Z(y,b,this.length);let M=b,L=1,K=this[y+--M];for(;M>0&&(L*=256);)K+=this[y+--M]*L;return L*=128,K>=L&&(K-=Math.pow(2,8*b)),K},a.prototype.readInt8=function(y,b){return y=y>>>0,b||Z(y,1,this.length),this[y]&128?(255-this[y]+1)*-1:this[y]},a.prototype.readInt16LE=function(y,b){y=y>>>0,b||Z(y,2,this.length);const P=this[y]|this[y+1]<<8;return P&32768?P|4294901760:P},a.prototype.readInt16BE=function(y,b){y=y>>>0,b||Z(y,2,this.length);const P=this[y+1]|this[y]<<8;return P&32768?P|4294901760:P},a.prototype.readInt32LE=function(y,b){return y=y>>>0,b||Z(y,4,this.length),this[y]|this[y+1]<<8|this[y+2]<<16|this[y+3]<<24},a.prototype.readInt32BE=function(y,b){return y=y>>>0,b||Z(y,4,this.length),this[y]<<24|this[y+1]<<16|this[y+2]<<8|this[y+3]},a.prototype.readBigInt64LE=Mn(function(y){y=y>>>0,ve(y,"offset");const b=this[y],P=this[y+7];(b===void 0||P===void 0)&&ke(y,this.length-8);const M=this[y+4]+this[y+5]*2**8+this[y+6]*2**16+(P<<24);return(BigInt(M)<<BigInt(32))+BigInt(b+this[++y]*2**8+this[++y]*2**16+this[++y]*2**24)}),a.prototype.readBigInt64BE=Mn(function(y){y=y>>>0,ve(y,"offset");const b=this[y],P=this[y+7];(b===void 0||P===void 0)&&ke(y,this.length-8);const M=(b<<24)+this[++y]*2**16+this[++y]*2**8+this[++y];return(BigInt(M)<<BigInt(32))+BigInt(this[++y]*2**24+this[++y]*2**16+this[++y]*2**8+P)}),a.prototype.readFloatLE=function(y,b){return y=y>>>0,b||Z(y,4,this.length),r.read(this,y,!0,23,4)},a.prototype.readFloatBE=function(y,b){return y=y>>>0,b||Z(y,4,this.length),r.read(this,y,!1,23,4)},a.prototype.readDoubleLE=function(y,b){return y=y>>>0,b||Z(y,8,this.length),r.read(this,y,!0,52,8)},a.prototype.readDoubleBE=function(y,b){return y=y>>>0,b||Z(y,8,this.length),r.read(this,y,!1,52,8)};function R(x,y,b,P,M,L){if(!a.isBuffer(x))throw new TypeError('"buffer" argument must be a Buffer instance');if(y>M||y<L)throw new RangeError('"value" argument is out of bounds');if(b+P>x.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(y,b,P,M){if(y=+y,b=b>>>0,P=P>>>0,!M){const be=Math.pow(2,8*P)-1;R(this,y,b,P,be,0)}let L=1,K=0;for(this[b]=y&255;++K<P&&(L*=256);)this[b+K]=y/L&255;return b+P},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(y,b,P,M){if(y=+y,b=b>>>0,P=P>>>0,!M){const be=Math.pow(2,8*P)-1;R(this,y,b,P,be,0)}let L=P-1,K=1;for(this[b+L]=y&255;--L>=0&&(K*=256);)this[b+L]=y/K&255;return b+P},a.prototype.writeUint8=a.prototype.writeUInt8=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,1,255,0),this[b]=y&255,b+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,2,65535,0),this[b]=y&255,this[b+1]=y>>>8,b+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,2,65535,0),this[b]=y>>>8,this[b+1]=y&255,b+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,4,4294967295,0),this[b+3]=y>>>24,this[b+2]=y>>>16,this[b+1]=y>>>8,this[b]=y&255,b+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,4,4294967295,0),this[b]=y>>>24,this[b+1]=y>>>16,this[b+2]=y>>>8,this[b+3]=y&255,b+4};function F(x,y,b,P,M){me(y,P,M,x,b,7);let L=Number(y&BigInt(4294967295));x[b++]=L,L=L>>8,x[b++]=L,L=L>>8,x[b++]=L,L=L>>8,x[b++]=L;let K=Number(y>>BigInt(32)&BigInt(4294967295));return x[b++]=K,K=K>>8,x[b++]=K,K=K>>8,x[b++]=K,K=K>>8,x[b++]=K,b}function z(x,y,b,P,M){me(y,P,M,x,b,7);let L=Number(y&BigInt(4294967295));x[b+7]=L,L=L>>8,x[b+6]=L,L=L>>8,x[b+5]=L,L=L>>8,x[b+4]=L;let K=Number(y>>BigInt(32)&BigInt(4294967295));return x[b+3]=K,K=K>>8,x[b+2]=K,K=K>>8,x[b+1]=K,K=K>>8,x[b]=K,b+8}a.prototype.writeBigUInt64LE=Mn(function(y,b=0){return F(this,y,b,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Mn(function(y,b=0){return z(this,y,b,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(y,b,P,M){if(y=+y,b=b>>>0,!M){const ze=Math.pow(2,8*P-1);R(this,y,b,P,ze-1,-ze)}let L=0,K=1,be=0;for(this[b]=y&255;++L<P&&(K*=256);)y<0&&be===0&&this[b+L-1]!==0&&(be=1),this[b+L]=(y/K>>0)-be&255;return b+P},a.prototype.writeIntBE=function(y,b,P,M){if(y=+y,b=b>>>0,!M){const ze=Math.pow(2,8*P-1);R(this,y,b,P,ze-1,-ze)}let L=P-1,K=1,be=0;for(this[b+L]=y&255;--L>=0&&(K*=256);)y<0&&be===0&&this[b+L+1]!==0&&(be=1),this[b+L]=(y/K>>0)-be&255;return b+P},a.prototype.writeInt8=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,1,127,-128),y<0&&(y=255+y+1),this[b]=y&255,b+1},a.prototype.writeInt16LE=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,2,32767,-32768),this[b]=y&255,this[b+1]=y>>>8,b+2},a.prototype.writeInt16BE=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,2,32767,-32768),this[b]=y>>>8,this[b+1]=y&255,b+2},a.prototype.writeInt32LE=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,4,2147483647,-2147483648),this[b]=y&255,this[b+1]=y>>>8,this[b+2]=y>>>16,this[b+3]=y>>>24,b+4},a.prototype.writeInt32BE=function(y,b,P){return y=+y,b=b>>>0,P||R(this,y,b,4,2147483647,-2147483648),y<0&&(y=4294967295+y+1),this[b]=y>>>24,this[b+1]=y>>>16,this[b+2]=y>>>8,this[b+3]=y&255,b+4},a.prototype.writeBigInt64LE=Mn(function(y,b=0){return F(this,y,b,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Mn(function(y,b=0){return z(this,y,b,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function se(x,y,b,P,M,L){if(b+P>x.length)throw new RangeError("Index out of range");if(b<0)throw new RangeError("Index out of range")}function ae(x,y,b,P,M){return y=+y,b=b>>>0,M||se(x,y,b,4),r.write(x,y,b,P,23,4),b+4}a.prototype.writeFloatLE=function(y,b,P){return ae(this,y,b,!0,P)},a.prototype.writeFloatBE=function(y,b,P){return ae(this,y,b,!1,P)};function fe(x,y,b,P,M){return y=+y,b=b>>>0,M||se(x,y,b,8),r.write(x,y,b,P,52,8),b+8}a.prototype.writeDoubleLE=function(y,b,P){return fe(this,y,b,!0,P)},a.prototype.writeDoubleBE=function(y,b,P){return fe(this,y,b,!1,P)},a.prototype.copy=function(y,b,P,M){if(!a.isBuffer(y))throw new TypeError("argument should be a Buffer");if(P||(P=0),!M&&M!==0&&(M=this.length),b>=y.length&&(b=y.length),b||(b=0),M>0&&M<P&&(M=P),M===P||y.length===0||this.length===0)return 0;if(b<0)throw new RangeError("targetStart out of bounds");if(P<0||P>=this.length)throw new RangeError("Index out of range");if(M<0)throw new RangeError("sourceEnd out of bounds");M>this.length&&(M=this.length),y.length-b<M-P&&(M=y.length-b+P);const L=M-P;return this===y&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(b,P,M):Uint8Array.prototype.set.call(y,this.subarray(P,M),b),L},a.prototype.fill=function(y,b,P,M){if(typeof y=="string"){if(typeof b=="string"?(M=b,b=0,P=this.length):typeof P=="string"&&(M=P,P=this.length),M!==void 0&&typeof M!="string")throw new TypeError("encoding must be a string");if(typeof M=="string"&&!a.isEncoding(M))throw new TypeError("Unknown encoding: "+M);if(y.length===1){const K=y.charCodeAt(0);(M==="utf8"&&K<128||M==="latin1")&&(y=K)}}else typeof y=="number"?y=y&255:typeof y=="boolean"&&(y=Number(y));if(b<0||this.length<b||this.length<P)throw new RangeError("Out of range index");if(P<=b)return this;b=b>>>0,P=P===void 0?this.length:P>>>0,y||(y=0);let L;if(typeof y=="number")for(L=b;L<P;++L)this[L]=y;else{const K=a.isBuffer(y)?y:a.from(y,M),be=K.length;if(be===0)throw new TypeError('The value "'+y+'" is invalid for argument "value"');for(L=0;L<P-b;++L)this[L+b]=K[L%be]}return this};const ue={};function oe(x,y,b){ue[x]=class extends b{constructor(){super(),Object.defineProperty(this,"message",{value:y.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${x}]`,this.stack,delete this.name}get code(){return x}set code(M){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:M,writable:!0})}toString(){return`${this.name} [${x}]: ${this.message}`}}}oe("ERR_BUFFER_OUT_OF_BOUNDS",function(x){return x?`${x} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),oe("ERR_INVALID_ARG_TYPE",function(x,y){return`The "${x}" argument must be of type number. Received type ${typeof y}`},TypeError),oe("ERR_OUT_OF_RANGE",function(x,y,b){let P=`The value of "${x}" is out of range.`,M=b;return Number.isInteger(b)&&Math.abs(b)>2**32?M=ie(String(b)):typeof b=="bigint"&&(M=String(b),(b>BigInt(2)**BigInt(32)||b<-(BigInt(2)**BigInt(32)))&&(M=ie(M)),M+="n"),P+=` It must be ${y}. Received ${M}`,P},RangeError);function ie(x){let y="",b=x.length;const P=x[0]==="-"?1:0;for(;b>=P+4;b-=3)y=`_${x.slice(b-3,b)}${y}`;return`${x.slice(0,b)}${y}`}function ye(x,y,b){ve(y,"offset"),(x[y]===void 0||x[y+b]===void 0)&&ke(y,x.length-(b+1))}function me(x,y,b,P,M,L){if(x>b||x<y){const K=typeof y=="bigint"?"n":"";let be;throw y===0||y===BigInt(0)?be=`>= 0${K} and < 2${K} ** ${(L+1)*8}${K}`:be=`>= -(2${K} ** ${(L+1)*8-1}${K}) and < 2 ** ${(L+1)*8-1}${K}`,new ue.ERR_OUT_OF_RANGE("value",be,x)}ye(P,M,L)}function ve(x,y){if(typeof x!="number")throw new ue.ERR_INVALID_ARG_TYPE(y,"number",x)}function ke(x,y,b){throw Math.floor(x)!==x?(ve(x,b),new ue.ERR_OUT_OF_RANGE("offset","an integer",x)):y<0?new ue.ERR_BUFFER_OUT_OF_BOUNDS:new ue.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${y}`,x)}const Ze=/[^+/0-9A-Za-z-_]/g;function Ie(x){if(x=x.split("=")[0],x=x.trim().replace(Ze,""),x.length<2)return"";for(;x.length%4!==0;)x=x+"=";return x}function Mr(x,y){y=y||1/0;let b;const P=x.length;let M=null;const L=[];for(let K=0;K<P;++K){if(b=x.charCodeAt(K),b>55295&&b<57344){if(!M){if(b>56319){(y-=3)>-1&&L.push(239,191,189);continue}else if(K+1===P){(y-=3)>-1&&L.push(239,191,189);continue}M=b;continue}if(b<56320){(y-=3)>-1&&L.push(239,191,189),M=b;continue}b=(M-55296<<10|b-56320)+65536}else M&&(y-=3)>-1&&L.push(239,191,189);if(M=null,b<128){if((y-=1)<0)break;L.push(b)}else if(b<2048){if((y-=2)<0)break;L.push(b>>6|192,b&63|128)}else if(b<65536){if((y-=3)<0)break;L.push(b>>12|224,b>>6&63|128,b&63|128)}else if(b<1114112){if((y-=4)<0)break;L.push(b>>18|240,b>>12&63|128,b>>6&63|128,b&63|128)}else throw new Error("Invalid code point")}return L}function ms(x){const y=[];for(let b=0;b<x.length;++b)y.push(x.charCodeAt(b)&255);return y}function Y(x,y){let b,P,M;const L=[];for(let K=0;K<x.length&&!((y-=2)<0);++K)b=x.charCodeAt(K),P=b>>8,M=b%256,L.push(M),L.push(P);return L}function jr(x){return e.toByteArray(Ie(x))}function vt(x,y,b,P){let M;for(M=0;M<P&&!(M+b>=y.length||M>=x.length);++M)y[M+b]=x[M];return M}function Et(x,y){return x instanceof y||x!=null&&x.constructor!=null&&x.constructor.name!=null&&x.constructor.name===y.name}function Rn(x){return x!==x}const ni=function(){const x="0123456789abcdef",y=new Array(256);for(let b=0;b<16;++b){const P=b*16;for(let M=0;M<16;++M)y[P+M]=x[b]+x[M]}return y}();function Mn(x){return typeof BigInt>"u"?n2:x}function n2(){throw new Error("BigInt not supported")}})(Zs);var ea={Array:function(t){return t!=null&&t.constructor===Array},Boolean:function(t){return typeof t=="boolean"},Function:function(t){return typeof t=="function"},Nil:function(t){return t==null},Number:function(t){return typeof t=="number"},Object:function(t){return typeof t=="object"},String:function(t){return typeof t=="string"},"":function(){return!0}};ea.Null=ea.Nil;for(var x0 in ea)ea[x0].toJSON=(function(t){return t}).bind(null,x0);var Hh=ea,Ns=Hh;function _w(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function zh(t){return Ns.Nil(t)?"":_w(t.constructor)}function AT(t){return Ns.Function(t)?"":Ns.String(t)?JSON.stringify(t):t&&Ns.Object(t)?"":t}function Vh(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function _c(t){return Ns.Function(t)?t.toJSON?t.toJSON():_w(t):Ns.Array(t)?"Array":t&&Ns.Object(t)?"Object":t!==void 0?t:""}function Pw(t,e,r){var n=AT(e);return"Expected "+_c(t)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function On(t,e,r){r=r||zh(e),this.message=Pw(t,e,r),Vh(this,On),this.__type=t,this.__value=e,this.__valueTypeName=r}On.prototype=Object.create(Error.prototype);On.prototype.constructor=On;function kT(t,e,r,n,s){var i='" of type ';return e==="key"&&(i='" with key type '),Pw('property "'+_c(r)+i+_c(t),n,s)}function xi(t,e,r,n,s){t?(s=s||zh(n),this.message=kT(t,r,e,n,s)):this.message='Unexpected property "'+e+'"',Vh(this,On),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=s}xi.prototype=Object.create(Error.prototype);xi.prototype.constructor=On;function xT(t,e){return new On(t,{},e)}function TT(t,e,r){return t instanceof xi?(e=e+"."+t.__property,t=new xi(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof On&&(t=new xi(t.__type,e,r,t.__value,t.__valueTypeName)),Vh(t),t}var Ow={TfTypeError:On,TfPropertyTypeError:xi,tfCustomError:xT,tfSubError:TT,tfJSON:_c,getValueTypeName:zh},il,T0;function _T(){if(T0)return il;T0=1;var t=Hh,e=Ow;function r(_){return Buffer.isBuffer(_)}function n(_){return typeof _=="string"&&/^([0-9a-f]{2})+$/i.test(_)}function s(_,O){var B=_.toJSON();function N($){if(!_($))return!1;if($.length===O)return!0;throw e.tfCustomError(B+"(Length: "+O+")",B+"(Length: "+$.length+")")}return N.toJSON=function(){return B},N}var i=s.bind(null,t.Array),o=s.bind(null,r),a=s.bind(null,n),c=s.bind(null,t.String);function u(_,O,B){B=B||t.Number;function N($,j){return B($,j)&&$>_&&$<O}return N.toJSON=function(){return`${B.toJSON()} between [${_}, ${O}]`},N}var l=Math.pow(2,53)-1;function f(_){return typeof _=="number"&&isFinite(_)}function h(_){return _<<24>>24===_}function d(_){return _<<16>>16===_}function p(_){return(_|0)===_}function m(_){return typeof _=="number"&&_>=-l&&_<=l&&Math.floor(_)===_}function v(_){return(_&255)===_}function S(_){return(_&65535)===_}function T(_){return _>>>0===_}function g(_){return typeof _=="number"&&_>=0&&_<=l&&Math.floor(_)===_}var w={ArrayN:i,Buffer:r,BufferN:o,Finite:f,Hex:n,HexN:a,Int8:h,Int16:d,Int32:p,Int53:m,Range:u,StringN:c,UInt8:v,UInt16:S,UInt32:T,UInt53:g};for(var k in w)w[k].toJSON=(function(_){return _}).bind(null,k);return il=w,il}var _a=Ow,ct=Hh,an=_a.tfJSON,Iw=_a.TfTypeError,Bw=_a.TfPropertyTypeError,no=_a.tfSubError,PT=_a.getValueTypeName,vn={arrayOf:function(e,r){e=Wr(e),r=r||{};function n(s,i){return!ct.Array(s)||ct.Nil(s)||r.minLength!==void 0&&s.length<r.minLength||r.maxLength!==void 0&&s.length>r.maxLength||r.length!==void 0&&s.length!==r.length?!1:s.every(function(o,a){try{return Tt(e,o,i)}catch(c){throw no(c,a)}})}return n.toJSON=function(){var s="["+an(e)+"]";return r.length!==void 0?s+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(s+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),s},n},maybe:function t(e){e=Wr(e);function r(n,s){return ct.Nil(n)||e(n,s,t)}return r.toJSON=function(){return"?"+an(e)},r},map:function(e,r){e=Wr(e),r&&(r=Wr(r));function n(s,i){if(!ct.Object(s)||ct.Nil(s))return!1;for(var o in s){try{r&&Tt(r,o,i)}catch(c){throw no(c,o,"key")}try{var a=s[o];Tt(e,a,i)}catch(c){throw no(c,o)}}return!0}return r?n.toJSON=function(){return"{"+an(r)+": "+an(e)+"}"}:n.toJSON=function(){return"{"+an(e)+"}"},n},object:function(e){var r={};for(var n in e)r[n]=Wr(e[n]);function s(i,o){if(!ct.Object(i)||ct.Nil(i))return!1;var a;try{for(a in r){var c=r[a],u=i[a];Tt(c,u,o)}}catch(l){throw no(l,a)}if(o){for(a in i)if(!r[a])throw new Bw(void 0,a)}return!0}return s.toJSON=function(){return an(r)},s},anyOf:function(){var e=[].slice.call(arguments).map(Wr);function r(n,s){return e.some(function(i){try{return Tt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(an).join("|")},r},allOf:function(){var e=[].slice.call(arguments).map(Wr);function r(n,s){return e.every(function(i){try{return Tt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(an).join(" & ")},r},quacksLike:function(e){function r(n){return e===PT(n)}return r.toJSON=function(){return e},r},tuple:function(){var e=[].slice.call(arguments).map(Wr);function r(n,s){return ct.Nil(n)||ct.Nil(n.length)||s&&n.length!==e.length?!1:e.every(function(i,o){try{return Tt(i,n[o],s)}catch(a){throw no(a,o)}})}return r.toJSON=function(){return"("+e.map(an).join(", ")+")"},r},value:function(e){function r(n){return n===e}return r.toJSON=function(){return e},r}};vn.oneOf=vn.anyOf;function Wr(t){if(ct.String(t))return t[0]==="?"?vn.maybe(t.slice(1)):ct[t]||vn.quacksLike(t);if(t&&ct.Object(t)){if(ct.Array(t)){if(t.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return vn.arrayOf(t[0])}return vn.object(t)}else if(ct.Function(t))return t;return vn.value(t)}function Tt(t,e,r,n){if(ct.Function(t)){if(t(e,r))return!0;throw new Iw(n||t,e)}return Tt(Wr(t),e,r)}for(var rs in ct)Tt[rs]=ct[rs];for(rs in vn)Tt[rs]=vn[rs];var _0=_T();for(rs in _0)Tt[rs]=_0[rs];Tt.compile=Wr;Tt.TfTypeError=Iw;Tt.TfPropertyTypeError=Bw;var OT=Tt;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.oneOf=t.Null=t.BufferN=t.Function=t.UInt32=t.UInt8=t.tuple=t.maybe=t.Hex=t.Buffer=t.String=t.Boolean=t.Array=t.Number=t.Hash256bit=t.Hash160bit=t.Buffer256bit=t.isTaptree=t.isTapleaf=t.TAPLEAF_VERSION_MASK=t.Satoshi=t.isPoint=t.stacksEqual=t.typeforce=void 0;const e=Zs;t.typeforce=OT;const r=e.Buffer.alloc(32,0),n=e.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(l,f){return l.length!==f.length?!1:l.every((h,d)=>h.equals(f[d]))}t.stacksEqual=s;function i(l){if(!e.Buffer.isBuffer(l)||l.length<33)return!1;const f=l[0],h=l.slice(1,33);if(h.compare(r)===0||h.compare(n)>=0)return!1;if((f===2||f===3)&&l.length===33)return!0;const d=l.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:f===4&&l.length===65}t.isPoint=i;const o=21*1e14;function a(l){return t.typeforce.UInt53(l)&&l<=o}t.Satoshi=a,t.TAPLEAF_VERSION_MASK=254;function c(l){return!l||!("output"in l)||!e.Buffer.isBuffer(l.output)?!1:l.version!==void 0?(l.version&t.TAPLEAF_VERSION_MASK)===l.version:!0}t.isTapleaf=c;function u(l){return(0,t.Array)(l)?l.length!==2?!1:l.every(f=>u(f)):c(l)}t.isTaptree=u,t.Buffer256bit=t.typeforce.BufferN(32),t.Hash160bit=t.typeforce.BufferN(20),t.Hash256bit=t.typeforce.BufferN(32),t.Number=t.typeforce.Number,t.Array=t.typeforce.Array,t.Boolean=t.typeforce.Boolean,t.String=t.typeforce.String,t.Buffer=t.typeforce.Buffer,t.Hex=t.typeforce.Hex,t.maybe=t.typeforce.maybe,t.tuple=t.typeforce.tuple,t.UInt8=t.typeforce.UInt8,t.UInt32=t.typeforce.UInt32,t.Function=t.typeforce.Function,t.BufferN=t.typeforce.BufferN,t.Null=t.typeforce.Null,t.oneOf=t.typeforce.oneOf})(gt);var Pa={},ut={};Object.defineProperty(ut,"__esModule",{value:!0});ut.BufferReader=ut.BufferWriter=ut.cloneBuffer=ut.reverseBuffer=ut.writeUInt64LE=ut.readUInt64LE=ut.varuint=void 0;const Rs=gt,{typeforce:Cw}=Rs,ta=Am;ut.varuint=ta;function Nw(t,e){if(typeof t!="number")throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function Rw(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Nw(n+r,9007199254740991),n+r}ut.readUInt64LE=Rw;function Mw(t,e,r){return Nw(e,9007199254740991),t.writeInt32LE(e&-1,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}ut.writeUInt64LE=Mw;function IT(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n<t.length/2;n++)r=t[n],t[n]=t[e],t[e]=r,e--;return t}ut.reverseBuffer=IT;function BT(t){const e=Buffer.allocUnsafe(t.length);return t.copy(e),e}ut.cloneBuffer=BT;class Gh{static withCapacity(e){return new Gh(Buffer.alloc(e))}constructor(e,r=0){this.buffer=e,this.offset=r,Cw(Rs.tuple(Rs.Buffer,Rs.UInt32),[e,r])}writeUInt8(e){this.offset=this.buffer.writeUInt8(e,this.offset)}writeInt32(e){this.offset=this.buffer.writeInt32LE(e,this.offset)}writeUInt32(e){this.offset=this.buffer.writeUInt32LE(e,this.offset)}writeUInt64(e){this.offset=Mw(this.buffer,e,this.offset)}writeVarInt(e){ta.encode(e,this.buffer,this.offset),this.offset+=ta.encode.bytes}writeSlice(e){if(this.buffer.length<this.offset+e.length)throw new Error("Cannot write slice out of bounds");this.offset+=e.copy(this.buffer,this.offset)}writeVarSlice(e){this.writeVarInt(e.length),this.writeSlice(e)}writeVector(e){this.writeVarInt(e.length),e.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}ut.BufferWriter=Gh;class CT{constructor(e,r=0){this.buffer=e,this.offset=r,Cw(Rs.tuple(Rs.Buffer,Rs.UInt32),[e,r])}readUInt8(){const e=this.buffer.readUInt8(this.offset);return this.offset++,e}readInt32(){const e=this.buffer.readInt32LE(this.offset);return this.offset+=4,e}readUInt32(){const e=this.buffer.readUInt32LE(this.offset);return this.offset+=4,e}readUInt64(){const e=Rw(this.buffer,this.offset);return this.offset+=8,e}readVarInt(){const e=ta.decode(this.buffer,this.offset);return this.offset+=ta.decode.bytes,e}readSlice(e){if(this.buffer.length<this.offset+e)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const e=this.readVarInt(),r=[];for(let n=0;n<e;n++)r.push(this.readVarSlice());return r}}ut.BufferReader=CT;var ys={};const NT=xw(mA);var Ui={},Rt={},Pt={},qh={},uu={};Object.defineProperty(uu,"__esModule",{value:!0});uu.crypto=void 0;uu.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(t){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(t,"__esModule",{value:!0}),t.wrapXOFConstructorWithOpts=t.wrapConstructorWithOpts=t.wrapConstructor=t.Hash=t.nextTick=t.swap32IfBE=t.byteSwapIfBE=t.swap8IfBE=t.isLE=void 0,t.isBytes=r,t.anumber=n,t.abytes=s,t.ahash=i,t.aexists=o,t.aoutput=a,t.u8=c,t.u32=u,t.clean=l,t.createView=f,t.rotr=h,t.rotl=d,t.byteSwap=p,t.byteSwap32=m,t.bytesToHex=T,t.hexToBytes=k,t.asyncLoop=O,t.utf8ToBytes=B,t.bytesToUtf8=N,t.toBytes=$,t.kdfInputToBytes=j,t.concatBytes=H,t.checkOpts=G,t.createHasher=U,t.createOptHasher=X,t.createXOFer=te,t.randomBytes=W;const e=uu;function r(C){return C instanceof Uint8Array||ArrayBuffer.isView(C)&&C.constructor.name==="Uint8Array"}function n(C){if(!Number.isSafeInteger(C)||C<0)throw new Error("positive integer expected, got "+C)}function s(C,...D){if(!r(C))throw new Error("Uint8Array expected");if(D.length>0&&!D.includes(C.length))throw new Error("Uint8Array expected of length "+D+", got length="+C.length)}function i(C){if(typeof C!="function"||typeof C.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(C.outputLen),n(C.blockLen)}function o(C,D=!0){if(C.destroyed)throw new Error("Hash instance has been destroyed");if(D&&C.finished)throw new Error("Hash#digest() has already been called")}function a(C,D){s(C);const Z=D.outputLen;if(C.length<Z)throw new Error("digestInto() expects output buffer of length at least "+Z)}function c(C){return new Uint8Array(C.buffer,C.byteOffset,C.byteLength)}function u(C){return new Uint32Array(C.buffer,C.byteOffset,Math.floor(C.byteLength/4))}function l(...C){for(let D=0;D<C.length;D++)C[D].fill(0)}function f(C){return new DataView(C.buffer,C.byteOffset,C.byteLength)}function h(C,D){return C<<32-D|C>>>D}function d(C,D){return C<<D|C>>>32-D>>>0}t.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function p(C){return C<<24&4278190080|C<<8&16711680|C>>>8&65280|C>>>24&255}t.swap8IfBE=t.isLE?C=>C:C=>p(C),t.byteSwapIfBE=t.swap8IfBE;function m(C){for(let D=0;D<C.length;D++)C[D]=p(C[D]);return C}t.swap32IfBE=t.isLE?C=>C:m;const v=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(C,D)=>D.toString(16).padStart(2,"0"));function T(C){if(s(C),v)return C.toHex();let D="";for(let Z=0;Z<C.length;Z++)D+=S[C[Z]];return D}const g={_0:48,_9:57,A:65,F:70,a:97,f:102};function w(C){if(C>=g._0&&C<=g._9)return C-g._0;if(C>=g.A&&C<=g.F)return C-(g.A-10);if(C>=g.a&&C<=g.f)return C-(g.a-10)}function k(C){if(typeof C!="string")throw new Error("hex string expected, got "+typeof C);if(v)return Uint8Array.fromHex(C);const D=C.length,Z=D/2;if(D%2)throw new Error("hex string expected, got unpadded hex of length "+D);const R=new Uint8Array(Z);for(let F=0,z=0;F<Z;F++,z+=2){const se=w(C.charCodeAt(z)),ae=w(C.charCodeAt(z+1));if(se===void 0||ae===void 0){const fe=C[z]+C[z+1];throw new Error('hex string expected, got non-hex character "'+fe+'" at index '+z)}R[F]=se*16+ae}return R}const _=async()=>{};t.nextTick=_;async function O(C,D,Z){let R=Date.now();for(let F=0;F<C;F++){Z(F);const z=Date.now()-R;z>=0&&z<D||(await(0,t.nextTick)(),R+=z)}}function B(C){if(typeof C!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(C))}function N(C){return new TextDecoder().decode(C)}function $(C){return typeof C=="string"&&(C=B(C)),s(C),C}function j(C){return typeof C=="string"&&(C=B(C)),s(C),C}function H(...C){let D=0;for(let R=0;R<C.length;R++){const F=C[R];s(F),D+=F.length}const Z=new Uint8Array(D);for(let R=0,F=0;R<C.length;R++){const z=C[R];Z.set(z,F),F+=z.length}return Z}function G(C,D){if(D!==void 0&&{}.toString.call(D)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(C,D)}class ee{}t.Hash=ee;function U(C){const D=R=>C().update($(R)).digest(),Z=C();return D.outputLen=Z.outputLen,D.blockLen=Z.blockLen,D.create=()=>C(),D}function X(C){const D=(R,F)=>C(F).update($(R)).digest(),Z=C({});return D.outputLen=Z.outputLen,D.blockLen=Z.blockLen,D.create=R=>C(R),D}function te(C){const D=(R,F)=>C(F).update($(R)).digest(),Z=C({});return D.outputLen=Z.outputLen,D.blockLen=Z.blockLen,D.create=R=>C(R),D}t.wrapConstructor=U,t.wrapConstructorWithOpts=X,t.wrapXOFConstructorWithOpts=te;function W(C=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(C));if(e.crypto&&typeof e.crypto.randomBytes=="function")return Uint8Array.from(e.crypto.randomBytes(C));throw new Error("crypto.getRandomValues must be defined")}})(qh);Object.defineProperty(Pt,"__esModule",{value:!0});Pt.SHA512_IV=Pt.SHA384_IV=Pt.SHA224_IV=Pt.SHA256_IV=Pt.HashMD=void 0;Pt.setBigUint64=jw;Pt.Chi=RT;Pt.Maj=MT;const Lr=qh;function jw(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function RT(t,e,r){return t&e^~t&r}function MT(t,e,r){return t&e^t&r^e&r}class jT extends Lr.Hash{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=(0,Lr.createView)(this.buffer)}update(e){(0,Lr.aexists)(this),e=(0,Lr.toBytes)(e),(0,Lr.abytes)(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=(0,Lr.createView)(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,Lr.aexists)(this),(0,Lr.aoutput)(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,(0,Lr.clean)(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)r[f]=0;jw(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=(0,Lr.createView)(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}Pt.HashMD=jT;Pt.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Pt.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Pt.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Pt.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Rt,"__esModule",{value:!0});Rt.ripemd160=Rt.RIPEMD160=Rt.md5=Rt.MD5=Rt.sha1=Rt.SHA1=void 0;const Ms=Pt,lt=qh,ui=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),$n=new Uint32Array(80);class Uw extends Ms.HashMD{constructor(){super(64,20,8,!1),this.A=ui[0]|0,this.B=ui[1]|0,this.C=ui[2]|0,this.D=ui[3]|0,this.E=ui[4]|0}get(){const{A:e,B:r,C:n,D:s,E:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0}process(e,r){for(let c=0;c<16;c++,r+=4)$n[c]=e.getUint32(r,!1);for(let c=16;c<80;c++)$n[c]=(0,lt.rotl)($n[c-3]^$n[c-8]^$n[c-14]^$n[c-16],1);let{A:n,B:s,C:i,D:o,E:a}=this;for(let c=0;c<80;c++){let u,l;c<20?(u=(0,Ms.Chi)(s,i,o),l=1518500249):c<40?(u=s^i^o,l=1859775393):c<60?(u=(0,Ms.Maj)(s,i,o),l=2400959708):(u=s^i^o,l=3395469782);const f=(0,lt.rotl)(n,5)+u+a+l+$n[c]|0;a=o,o=i,i=(0,lt.rotl)(s,30),s=n,n=f}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,s,i,o,a)}roundClean(){(0,lt.clean)($n)}destroy(){this.set(0,0,0,0,0),(0,lt.clean)(this.buffer)}}Rt.SHA1=Uw;Rt.sha1=(0,lt.createHasher)(()=>new Uw);const UT=Math.pow(2,32),FT=Array.from({length:64},(t,e)=>Math.floor(UT*Math.abs(Math.sin(e+1)))),Ga=ui.slice(0,4),ol=new Uint32Array(16);class Fw extends Ms.HashMD{constructor(){super(64,16,8,!0),this.A=Ga[0]|0,this.B=Ga[1]|0,this.C=Ga[2]|0,this.D=Ga[3]|0}get(){const{A:e,B:r,C:n,D:s}=this;return[e,r,n,s]}set(e,r,n,s){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0}process(e,r){for(let a=0;a<16;a++,r+=4)ol[a]=e.getUint32(r,!0);let{A:n,B:s,C:i,D:o}=this;for(let a=0;a<64;a++){let c,u,l;a<16?(c=(0,Ms.Chi)(s,i,o),u=a,l=[7,12,17,22]):a<32?(c=(0,Ms.Chi)(o,s,i),u=(5*a+1)%16,l=[5,9,14,20]):a<48?(c=s^i^o,u=(3*a+5)%16,l=[4,11,16,23]):(c=i^(s|~o),u=7*a%16,l=[6,10,15,21]),c=c+n+FT[a]+ol[u],n=o,o=i,i=s,s=s+(0,lt.rotl)(c,l[a%4])}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,this.set(n,s,i,o)}roundClean(){(0,lt.clean)(ol)}destroy(){this.set(0,0,0,0),(0,lt.clean)(this.buffer)}}Rt.MD5=Fw;Rt.md5=(0,lt.createHasher)(()=>new Fw);const $T=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),$w=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),LT=$w.map(t=>(9*t+5)%16),Lw=(()=>{const r=[[$w],[LT]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>$T[i]));return r})(),Dw=Lw[0],Hw=Lw[1],zw=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),DT=Dw.map((t,e)=>t.map(r=>zw[e][r])),HT=Hw.map((t,e)=>t.map(r=>zw[e][r])),zT=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),VT=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function P0(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const qa=new Uint32Array(16);class Vw extends Ms.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let d=0;d<16;d++,r+=4)qa[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,u=this.h3|0,l=u,f=this.h4|0,h=f;for(let d=0;d<5;d++){const p=4-d,m=zT[d],v=VT[d],S=Dw[d],T=Hw[d],g=DT[d],w=HT[d];for(let k=0;k<16;k++){const _=(0,lt.rotl)(n+P0(d,i,a,u)+qa[S[k]]+m,g[k])+f|0;n=f,f=u,u=(0,lt.rotl)(a,10)|0,a=i,i=_}for(let k=0;k<16;k++){const _=(0,lt.rotl)(s+P0(p,o,c,l)+qa[T[k]]+v,w[k])+h|0;s=h,h=l,l=(0,lt.rotl)(c,10)|0,c=o,o=_}}this.set(this.h1+a+l|0,this.h2+u+h|0,this.h3+f+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){(0,lt.clean)(qa)}destroy(){this.destroyed=!0,(0,lt.clean)(this.buffer),this.set(0,0,0,0,0)}}Rt.RIPEMD160=Vw;Rt.ripemd160=(0,lt.createHasher)(()=>new Vw);Object.defineProperty(Ui,"__esModule",{value:!0});Ui.sha1=Ui.SHA1=void 0;const Gw=Rt;Ui.SHA1=Gw.SHA1;Ui.sha1=Gw.sha1;const qw=xw(lE);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.taggedHash=t.TAGGED_HASH_PREFIXES=t.TAGS=t.hash256=t.hash160=t.sha256=t.sha1=t.ripemd160=void 0;const e=NT,r=Ui,n=qw;function s(l){return Buffer.from((0,e.ripemd160)(Uint8Array.from(l)))}t.ripemd160=s;function i(l){return Buffer.from((0,r.sha1)(Uint8Array.from(l)))}t.sha1=i;function o(l){return Buffer.from((0,n.sha256)(Uint8Array.from(l)))}t.sha256=o;function a(l){return Buffer.from((0,e.ripemd160)((0,n.sha256)(Uint8Array.from(l))))}t.hash160=a;function c(l){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(l))))}t.hash256=c,t.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],t.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function u(l,f){return o(Buffer.concat([t.TAGGED_HASH_PREFIXES[l],f]))}t.taggedHash=u})(ys);var al={},xn={};Object.defineProperty(xn,"__esModule",{value:!0});xn.encode=xn.decode=xn.check=void 0;function GT(t){if(t.length<8||t.length>72||t[0]!==48||t[1]!==t.length-2||t[2]!==2)return!1;const e=t[3];if(e===0||5+e>=t.length||t[4+e]!==2)return!1;const r=t[5+e];return!(r===0||6+e+r!==t.length||t[4]&128||e>1&&t[4]===0&&!(t[5]&128)||t[e+6]&128||r>1&&t[e+6]===0&&!(t[e+7]&128))}xn.check=GT;function qT(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(t[0]!==48)throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(t[2]!==2)throw new Error("Expected DER integer");const e=t[3];if(e===0)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(t[4+e]!==2)throw new Error("Expected DER integer (2)");const r=t[5+e];if(r===0)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(t[4]&128)throw new Error("R value is negative");if(e>1&&t[4]===0&&!(t[5]&128))throw new Error("R value excessively padded");if(t[e+6]&128)throw new Error("S value is negative");if(r>1&&t[e+6]===0&&!(t[e+7]&128))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}}xn.decode=qT;function WT(t,e){const r=t.length,n=e.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(t[0]&128)throw new Error("R value is negative");if(e[0]&128)throw new Error("S value is negative");if(r>1&&t[0]===0&&!(t[1]&128))throw new Error("R value excessively padded");if(n>1&&e[0]===0&&!(e[1]&128))throw new Error("S value excessively padded");const s=Buffer.allocUnsafe(6+r+n);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=t.length,t.copy(s,4),s[4+r]=2,s[5+r]=e.length,e.copy(s,6+r),s}xn.encode=WT;var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});Gs.REVERSE_OPS=Gs.OPS=void 0;const wd={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};Gs.OPS=wd;const Ww={};Gs.REVERSE_OPS=Ww;for(const t of Object.keys(wd)){const e=wd[t];Ww[e]=t}var ns={};Object.defineProperty(ns,"__esModule",{value:!0});ns.decode=ns.encode=ns.encodingLength=void 0;const Qn=Gs;function Kw(t){return t<Qn.OPS.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}ns.encodingLength=Kw;function KT(t,e,r){const n=Kw(e);return n===1?t.writeUInt8(e,r):n===2?(t.writeUInt8(Qn.OPS.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):n===3?(t.writeUInt8(Qn.OPS.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(Qn.OPS.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n}ns.encode=KT;function XT(t,e){const r=t.readUInt8(e);let n,s;if(r<Qn.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===Qn.OPS.OP_PUSHDATA1){if(e+2>t.length)return null;n=t.readUInt8(e+1),s=2}else if(r===Qn.OPS.OP_PUSHDATA2){if(e+3>t.length)return null;n=t.readUInt16LE(e+1),s=3}else{if(e+5>t.length)return null;if(r!==Qn.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=t.readUInt32LE(e+1),s=5}return{opcode:r,number:n,size:s}}ns.decode=XT;var Fi={};Object.defineProperty(Fi,"__esModule",{value:!0});Fi.encode=Fi.decode=void 0;function YT(t,e,r){e=e||4,r=r===void 0?!0:r;const n=t.length;if(n===0)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&!(t[n-1]&127)&&(n<=1||!(t[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const i=t.readUInt32LE(0),o=t.readUInt8(4);return o&128?-((o&-129)*4294967296+i):o*4294967296+i}let s=0;for(let i=0;i<n;++i)s|=t[i]<<8*i;return t[n-1]&128?-(s&~(128<<8*(n-1))):s}Fi.decode=YT;function JT(t){return t>2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}function ZT(t){let e=Math.abs(t);const r=JT(e),n=Buffer.allocUnsafe(r),s=t<0;for(let i=0;i<r;++i)n.writeUInt8(e&255,i),e>>=8;return n[r-1]&128?n.writeUInt8(s?128:0,r-1):s&&(n[r-1]|=128),n}Fi.encode=ZT;var gs={},O0;function QT(){if(O0)return gs;O0=1,Object.defineProperty(gs,"__esModule",{value:!0}),gs.encode=gs.decode=void 0;const t=xn,e=rr(),r=gt,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(u){let l=0;for(;u[l]===0;)++l;return l===u.length?s:(u=u.slice(l),u[0]&128?Buffer.concat([s,u],1+u.length):u)}function o(u){u[0]===0&&(u=u.slice(1));const l=Buffer.alloc(32,0),f=Math.max(0,32-u.length);return u.copy(l,f),l}function a(u){const l=u.readUInt8(u.length-1);if(!(0,e.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const f=t.decode(u.slice(0,-1)),h=o(f.r),d=o(f.s);return{signature:Buffer.concat([h,d],64),hashType:l}}gs.decode=a;function c(u,l){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:u,hashType:l}),!(0,e.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const f=Buffer.allocUnsafe(1);f.writeUInt8(l,0);const h=i(u.slice(0,32)),d=i(u.slice(32,64));return Buffer.concat([t.encode(h,d),f])}return gs.encode=c,gs}var I0;function rr(){return I0||(I0=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.signature=t.number=t.isCanonicalScriptSignature=t.isDefinedHashType=t.isCanonicalPubKey=t.toStack=t.fromASM=t.toASM=t.decompile=t.compile=t.countNonPushOnlyOPs=t.isPushOnly=t.OPS=void 0;const e=xn,r=Gs;Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=ns,s=Fi,i=QT(),o=gt,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function u(N){return o.Number(N)&&(N===r.OPS.OP_0||N>=r.OPS.OP_1&&N<=r.OPS.OP_16||N===r.OPS.OP_1NEGATE)}function l(N){return o.Buffer(N)||u(N)}function f(N){return o.Array(N)&&N.every(l)}t.isPushOnly=f;function h(N){return N.length-N.filter(l).length}t.countNonPushOnlyOPs=h;function d(N){if(N.length===0)return r.OPS.OP_0;if(N.length===1){if(N[0]>=1&&N[0]<=16)return c+N[0];if(N[0]===129)return r.OPS.OP_1NEGATE}}function p(N){return Buffer.isBuffer(N)}function m(N){return o.Array(N)}function v(N){return Buffer.isBuffer(N)}function S(N){if(p(N))return N;a(o.Array,N);const $=N.reduce((G,ee)=>v(ee)?ee.length===1&&d(ee)!==void 0?G+1:G+n.encodingLength(ee.length)+ee.length:G+1,0),j=Buffer.allocUnsafe($);let H=0;if(N.forEach(G=>{if(v(G)){const ee=d(G);if(ee!==void 0){j.writeUInt8(ee,H),H+=1;return}H+=n.encode(j,G.length,H),G.copy(j,H),H+=G.length}else j.writeUInt8(G,H),H+=1}),H!==j.length)throw new Error("Could not decode chunks");return j}t.compile=S;function T(N){if(m(N))return N;a(o.Buffer,N);const $=[];let j=0;for(;j<N.length;){const H=N[j];if(H>r.OPS.OP_0&&H<=r.OPS.OP_PUSHDATA4){const G=n.decode(N,j);if(G===null||(j+=G.size,j+G.number>N.length))return null;const ee=N.slice(j,j+G.number);j+=G.number;const U=d(ee);U!==void 0?$.push(U):$.push(ee)}else $.push(H),j+=1}return $}t.decompile=T;function g(N){if(p(N)&&(N=T(N)),!N)throw new Error("Could not convert invalid chunks to ASM");return N.map($=>{if(v($)){const j=d($);if(j===void 0)return $.toString("hex");$=j}return r.REVERSE_OPS[$]}).join(" ")}t.toASM=g;function w(N){return a(o.String,N),S(N.split(" ").map($=>r.OPS[$]!==void 0?r.OPS[$]:(a(o.Hex,$),Buffer.from($,"hex"))))}t.fromASM=w;function k(N){return N=T(N),a(f,N),N.map($=>v($)?$:$===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode($-c))}t.toStack=k;function _(N){return o.isPoint(N)}t.isCanonicalPubKey=_;function O(N){const $=N&-129;return $>0&&$<4}t.isDefinedHashType=O;function B(N){return!Buffer.isBuffer(N)||!O(N[N.length-1])?!1:e.check(N.slice(0,-1))}t.isCanonicalScriptSignature=B,t.number=s,t.signature=i}(al)),al}Object.defineProperty(Pa,"__esModule",{value:!0});Pa.Transaction=void 0;const Ke=ut,St=ys,B0=rr(),e_=rr(),Ee=gt,{typeforce:Dr}=Ee;function Gr(t){const e=t.length;return Ke.varuint.encodingLength(e)+e}function t_(t){const e=t.length;return Ke.varuint.encodingLength(e)+t.reduce((r,n)=>r+Gr(n),0)}const Gn=Buffer.allocUnsafe(0),cl=[],ul=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),C0=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),r_=Buffer.from("ffffffffffffffff","hex"),n_={script:Gn,valueBuffer:r_};function s_(t){return t.value!==void 0}let Rr=class _e{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(e,r){const n=new Ke.BufferReader(e),s=new _e;s.version=n.readInt32();const i=n.readUInt8(),o=n.readUInt8();let a=!1;i===_e.ADVANCED_TRANSACTION_MARKER&&o===_e.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let l=0;l<c;++l)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:cl});const u=n.readVarInt();for(let l=0;l<u;++l)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let l=0;l<c;++l)s.ins[l].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==e.length)throw new Error("Transaction has unexpected data");return s}static fromHex(e){return _e.fromBuffer(Buffer.from(e,"hex"),!1)}static isCoinbaseHash(e){Dr(Ee.Hash256bit,e);for(let r=0;r<32;++r)if(e[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&_e.isCoinbaseHash(this.ins[0].hash)}addInput(e,r,n,s){return Dr(Ee.tuple(Ee.Hash256bit,Ee.UInt32,Ee.maybe(Ee.UInt32),Ee.maybe(Ee.Buffer)),arguments),Ee.Null(n)&&(n=_e.DEFAULT_SEQUENCE),this.ins.push({hash:e,index:r,script:s||Gn,sequence:n,witness:cl})-1}addOutput(e,r){return Dr(Ee.tuple(Ee.Buffer,Ee.Satoshi),arguments),this.outs.push({script:e,value:r})-1}hasWitnesses(){return this.ins.some(e=>e.witness.length!==0)}stripWitnesses(){this.ins.forEach(e=>{e.witness=cl})}weight(){const e=this.byteLength(!1),r=this.byteLength(!0);return e*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(e=!0){const r=e&&this.hasWitnesses();return(r?10:8)+Ke.varuint.encodingLength(this.ins.length)+Ke.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+Gr(s.script),0)+this.outs.reduce((n,s)=>n+8+Gr(s.script),0)+(r?this.ins.reduce((n,s)=>n+t_(s.witness),0):0)}clone(){const e=new _e;return e.version=this.version,e.locktime=this.locktime,e.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),e.outs=this.outs.map(r=>({script:r.script,value:r.value})),e}hashForSignature(e,r,n){if(Dr(Ee.tuple(Ee.UInt32,Ee.Buffer,Ee.Number),arguments),e>=this.ins.length)return C0;const s=B0.compile(B0.decompile(r).filter(a=>a!==e_.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===_e.SIGHASH_NONE)i.outs=[],i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)});else if((n&31)===_e.SIGHASH_SINGLE){if(e>=this.outs.length)return C0;i.outs.length=e+1;for(let a=0;a<e;a++)i.outs[a]=n_;i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)})}n&_e.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[e]],i.ins[0].script=s):(i.ins.forEach(a=>{a.script=Gn}),i.ins[e].script=s);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),i.__toBuffer(o,0,!1),St.hash256(o)}hashForWitnessV1(e,r,n,s,i,o){if(Dr(Ee.tuple(Ee.UInt32,Dr.arrayOf(Ee.Buffer),Dr.arrayOf(Ee.Satoshi),Ee.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const a=s===_e.SIGHASH_DEFAULT?_e.SIGHASH_ALL:s&_e.SIGHASH_OUTPUT_MASK,u=(s&_e.SIGHASH_INPUT_MASK)===_e.SIGHASH_ANYONECANPAY,l=a===_e.SIGHASH_NONE,f=a===_e.SIGHASH_SINGLE;let h=Gn,d=Gn,p=Gn,m=Gn,v=Gn;if(!u){let w=Ke.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(k=>{w.writeSlice(k.hash),w.writeUInt32(k.index)}),h=St.sha256(w.end()),w=Ke.BufferWriter.withCapacity(8*this.ins.length),n.forEach(k=>w.writeUInt64(k)),d=St.sha256(w.end()),w=Ke.BufferWriter.withCapacity(r.map(Gr).reduce((k,_)=>k+_)),r.forEach(k=>w.writeVarSlice(k)),p=St.sha256(w.end()),w=Ke.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(k=>w.writeUInt32(k.sequence)),m=St.sha256(w.end())}if(l||f){if(f&&e<this.outs.length){const w=this.outs[e],k=Ke.BufferWriter.withCapacity(8+Gr(w.script));k.writeUInt64(w.value),k.writeVarSlice(w.script),v=St.sha256(k.end())}}else{const w=this.outs.map(_=>8+Gr(_.script)).reduce((_,O)=>_+O),k=Ke.BufferWriter.withCapacity(w);this.outs.forEach(_=>{k.writeUInt64(_.value),k.writeVarSlice(_.script)}),v=St.sha256(k.end())}const S=(i?2:0)+(o?1:0),T=174-(u?49:0)-(l?32:0)+(o?32:0)+(i?37:0),g=Ke.BufferWriter.withCapacity(T);if(g.writeUInt8(s),g.writeInt32(this.version),g.writeUInt32(this.locktime),g.writeSlice(h),g.writeSlice(d),g.writeSlice(p),g.writeSlice(m),l||f||g.writeSlice(v),g.writeUInt8(S),u){const w=this.ins[e];g.writeSlice(w.hash),g.writeUInt32(w.index),g.writeUInt64(n[e]),g.writeVarSlice(r[e]),g.writeUInt32(w.sequence)}else g.writeUInt32(e);if(o){const w=Ke.BufferWriter.withCapacity(Gr(o));w.writeVarSlice(o),g.writeSlice(St.sha256(w.end()))}return f&&g.writeSlice(v),i&&(g.writeSlice(i),g.writeUInt8(0),g.writeUInt32(4294967295)),St.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),g.end()]))}hashForWitnessV0(e,r,n,s){Dr(Ee.tuple(Ee.UInt32,Ee.Buffer,Ee.Satoshi,Ee.UInt32),arguments);let i=Buffer.from([]),o,a=ul,c=ul,u=ul;if(s&_e.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),o=new Ke.BufferWriter(i,0),this.ins.forEach(f=>{o.writeSlice(f.hash),o.writeUInt32(f.index)}),c=St.hash256(i)),!(s&_e.SIGHASH_ANYONECANPAY)&&(s&31)!==_e.SIGHASH_SINGLE&&(s&31)!==_e.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),o=new Ke.BufferWriter(i,0),this.ins.forEach(f=>{o.writeUInt32(f.sequence)}),u=St.hash256(i)),(s&31)!==_e.SIGHASH_SINGLE&&(s&31)!==_e.SIGHASH_NONE){const f=this.outs.reduce((h,d)=>h+8+Gr(d.script),0);i=Buffer.allocUnsafe(f),o=new Ke.BufferWriter(i,0),this.outs.forEach(h=>{o.writeUInt64(h.value),o.writeVarSlice(h.script)}),a=St.hash256(i)}else if((s&31)===_e.SIGHASH_SINGLE&&e<this.outs.length){const f=this.outs[e];i=Buffer.allocUnsafe(8+Gr(f.script)),o=new Ke.BufferWriter(i,0),o.writeUInt64(f.value),o.writeVarSlice(f.script),a=St.hash256(i)}i=Buffer.allocUnsafe(156+Gr(r)),o=new Ke.BufferWriter(i,0);const l=this.ins[e];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(u),o.writeSlice(l.hash),o.writeUInt32(l.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(l.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(s),St.hash256(i)}getHash(e){return e&&this.isCoinbase()?Buffer.alloc(32,0):St.hash256(this.__toBuffer(void 0,void 0,e))}getId(){return(0,Ke.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(e,r){return this.__toBuffer(e,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(e,r){Dr(Ee.tuple(Ee.Number,Ee.Buffer),arguments),this.ins[e].script=r}setWitness(e,r){Dr(Ee.tuple(Ee.Number,[Ee.Buffer]),arguments),this.ins[e].witness=r}__toBuffer(e,r,n=!1){e||(e=Buffer.allocUnsafe(this.byteLength(n)));const s=new Ke.BufferWriter(e,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(_e.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(_e.ADVANCED_TRANSACTION_FLAG)),s.writeVarInt(this.ins.length),this.ins.forEach(o=>{s.writeSlice(o.hash),s.writeUInt32(o.index),s.writeVarSlice(o.script),s.writeUInt32(o.sequence)}),s.writeVarInt(this.outs.length),this.outs.forEach(o=>{s_(o)?s.writeUInt64(o.value):s.writeSlice(o.valueBuffer),s.writeVarSlice(o.script)}),i&&this.ins.forEach(o=>{s.writeVector(o.witness)}),s.writeUInt32(this.locktime),r!==void 0?e.slice(r,s.offset):e}};Pa.Transaction=Rr;Rr.DEFAULT_SEQUENCE=4294967295;Rr.SIGHASH_DEFAULT=0;Rr.SIGHASH_ALL=1;Rr.SIGHASH_NONE=2;Rr.SIGHASH_SINGLE=3;Rr.SIGHASH_ANYONECANPAY=128;Rr.SIGHASH_OUTPUT_MASK=3;Rr.SIGHASH_INPUT_MASK=128;Rr.ADVANCED_TRANSACTION_MARKER=0;Rr.ADVANCED_TRANSACTION_FLAG=1;var Oe={},Oa={};Object.defineProperty(Oa,"__esModule",{value:!0});const i_=9007199254740991;function Wh(t){if(t<0||t>i_||t%1!==0)throw new RangeError("value out of range")}function ho(t,e,r){if(Wh(t),e||(e=Buffer.allocUnsafe(Xw(t))),!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),t<253?(e.writeUInt8(t,r),Object.assign(ho,{bytes:1})):t<=65535?(e.writeUInt8(253,r),e.writeUInt16LE(t,r+1),Object.assign(ho,{bytes:3})):t<=4294967295?(e.writeUInt8(254,r),e.writeUInt32LE(t,r+1),Object.assign(ho,{bytes:5})):(e.writeUInt8(255,r),e.writeUInt32LE(t>>>0,r+1),e.writeUInt32LE(t/4294967296|0,r+5),Object.assign(ho,{bytes:9})),e}Oa.encode=ho;function po(t,e){if(!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");e||(e=0);const r=t.readUInt8(e);if(r<253)return Object.assign(po,{bytes:1}),r;if(r===253)return Object.assign(po,{bytes:3}),t.readUInt16LE(e+1);if(r===254)return Object.assign(po,{bytes:5}),t.readUInt32LE(e+1);{Object.assign(po,{bytes:9});const n=t.readUInt32LE(e+1),i=t.readUInt32LE(e+5)*4294967296+n;return Wh(i),i}}Oa.decode=po;function Xw(t){return Wh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}Oa.encodingLength=Xw;var ll={},lu={},bt={};Object.defineProperty(bt,"__esModule",{value:!0});bt.testnet=bt.regtest=bt.bitcoin=void 0;bt.bitcoin={messagePrefix:`Bitcoin Signed Message:
50
+ `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};bt.regtest={messagePrefix:`Bitcoin Signed Message:
51
+ `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};bt.testnet={messagePrefix:`Bitcoin Signed Message:
52
+ `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Qt={};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.value=Qt.prop=void 0;function o_(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[e]=n,n},set(n){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}Qt.prop=o_;function a_(t){let e;return()=>(e!==void 0||(e=t()),e)}Qt.value=a_;Object.defineProperty(lu,"__esModule",{value:!0});lu.p2data=void 0;const c_=bt,uc=rr(),Hr=gt,N0=Qt,R0=uc.OPS;function u_(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Hr.typeforce)({network:Hr.typeforce.maybe(Hr.typeforce.Object),output:Hr.typeforce.maybe(Hr.typeforce.Buffer),data:Hr.typeforce.maybe(Hr.typeforce.arrayOf(Hr.typeforce.Buffer))},t);const n={name:"embed",network:t.network||c_.bitcoin};if(N0.prop(n,"output",()=>{if(t.data)return uc.compile([R0.OP_RETURN].concat(t.data))}),N0.prop(n,"data",()=>{if(t.output)return uc.decompile(t.output).slice(1)}),e.validate&&t.output){const s=uc.decompile(t.output);if(s[0]!==R0.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(Hr.typeforce.Buffer))throw new TypeError("Output is invalid");if(t.data&&!(0,Hr.stacksEqual)(t.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,t)}lu.p2data=u_;var fu={};Object.defineProperty(fu,"__esModule",{value:!0});fu.p2ms=void 0;const l_=bt,li=rr(),qe=gt,Ln=Qt,fi=li.OPS,Wa=fi.OP_RESERVED;function f_(t,e){if(!t.input&&!t.output&&!(t.pubkeys&&t.m!==void 0)&&!t.signatures)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{});function r(c){return li.isCanonicalScriptSignature(c)||(e.allowIncomplete&&c===fi.OP_0)!==void 0}(0,qe.typeforce)({network:qe.typeforce.maybe(qe.typeforce.Object),m:qe.typeforce.maybe(qe.typeforce.Number),n:qe.typeforce.maybe(qe.typeforce.Number),output:qe.typeforce.maybe(qe.typeforce.Buffer),pubkeys:qe.typeforce.maybe(qe.typeforce.arrayOf(qe.isPoint)),signatures:qe.typeforce.maybe(qe.typeforce.arrayOf(r)),input:qe.typeforce.maybe(qe.typeforce.Buffer)},t);const s={network:t.network||l_.bitcoin};let i=[],o=!1;function a(c){o||(o=!0,i=li.decompile(c),s.m=i[0]-Wa,s.n=i[i.length-2]-Wa,s.pubkeys=i.slice(1,-2))}if(Ln.prop(s,"output",()=>{if(t.m&&s.n&&t.pubkeys)return li.compile([].concat(Wa+t.m,t.pubkeys,Wa+s.n,fi.OP_CHECKMULTISIG))}),Ln.prop(s,"m",()=>{if(s.output)return a(s.output),s.m}),Ln.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),Ln.prop(s,"pubkeys",()=>{if(t.output)return a(t.output),s.pubkeys}),Ln.prop(s,"signatures",()=>{if(t.input)return li.decompile(t.input).slice(1)}),Ln.prop(s,"input",()=>{if(t.signatures)return li.compile([fi.OP_0].concat(t.signatures))}),Ln.prop(s,"witness",()=>{if(s.input)return[]}),Ln.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),e.validate){if(t.output){if(a(t.output),!qe.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!qe.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==fi.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(s.m<=0||s.n>16||s.m>s.n||s.n!==i.length-3)throw new TypeError("Output is invalid");if(!s.pubkeys.every(c=>(0,qe.isPoint)(c)))throw new TypeError("Output is invalid");if(t.m!==void 0&&t.m!==s.m)throw new TypeError("m mismatch");if(t.n!==void 0&&t.n!==s.n)throw new TypeError("n mismatch");if(t.pubkeys&&!(0,qe.stacksEqual)(t.pubkeys,s.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(t.n!==void 0&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(s.n=t.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(t.signatures){if(t.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(t.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==fi.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!(0,qe.stacksEqual)(t.signatures,s.signatures))throw new TypeError("Signature mismatch");if(t.m!==void 0&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(s,t)}fu.p2ms=f_;var du={};Object.defineProperty(du,"__esModule",{value:!0});du.p2pk=void 0;const d_=bt,di=rr(),pr=gt,ai=Qt,M0=di.OPS;function h_(t,e){if(!t.input&&!t.output&&!t.pubkey&&!t.input&&!t.signature)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,pr.typeforce)({network:pr.typeforce.maybe(pr.typeforce.Object),output:pr.typeforce.maybe(pr.typeforce.Buffer),pubkey:pr.typeforce.maybe(pr.isPoint),signature:pr.typeforce.maybe(di.isCanonicalScriptSignature),input:pr.typeforce.maybe(pr.typeforce.Buffer)},t);const r=ai.value(()=>di.decompile(t.input)),s={name:"p2pk",network:t.network||d_.bitcoin};if(ai.prop(s,"output",()=>{if(t.pubkey)return di.compile([t.pubkey,M0.OP_CHECKSIG])}),ai.prop(s,"pubkey",()=>{if(t.output)return t.output.slice(1,-1)}),ai.prop(s,"signature",()=>{if(t.input)return r()[0]}),ai.prop(s,"input",()=>{if(t.signature)return di.compile([t.signature])}),ai.prop(s,"witness",()=>{if(s.input)return[]}),e.validate){if(t.output){if(t.output[t.output.length-1]!==M0.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,pr.isPoint)(s.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(s.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(s.input))throw new TypeError("Signature mismatch");if(t.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!di.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,t)}du.p2pk=h_;var hu={};function p_(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var o=t.length,a=t.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var p=0,m=0,v=0,S=d.length;v!==S&&d[v]===0;)v++,p++;for(var T=(S-v)*u+1>>>0,g=new Uint8Array(T);v!==S;){for(var w=d[v],k=0,_=T-1;(w!==0||k<m)&&_!==-1;_--,k++)w+=256*g[_]>>>0,g[_]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");m=k,v++}for(var O=T-m;O!==T&&g[O]===0;)O++;for(var B=a.repeat(p);O<T;++O)B+=t.charAt(g[O]);return B}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var p=0,m=0,v=0;d[p]===a;)m++,p++;for(var S=(d.length-p)*c+1>>>0,T=new Uint8Array(S);d[p];){var g=d.charCodeAt(p);if(g>255)return;var w=e[g];if(w===255)return;for(var k=0,_=S-1;(w!==0||k<v)&&_!==-1;_--,k++)w+=o*T[_]>>>0,T[_]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");v=k,p++}for(var O=S-v;O!==S&&T[O]===0;)O++;for(var B=new Uint8Array(m+(S-O)),N=m;O!==S;)B[N++]=T[O++];return B}function h(d){var p=f(d);if(p)return p;throw new Error("Non-base"+o+" character")}return{encode:l,decodeUnsafe:f,decode:h}}var y_=p_;const m_=y_,b_="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var g_=m_(b_),fl=g_,w_=function(t){function e(i){var o=Uint8Array.from(i),a=t(o),c=o.length+4,u=new Uint8Array(c);return u.set(o,0),u.set(a.subarray(0,4),o.length),fl.encode(u,c)}function r(i){var o=i.slice(0,-4),a=i.slice(-4),c=t(o);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return o}function n(i){var o=fl.decodeUnsafe(i);if(o)return r(o)}function s(i){var o=fl.decode(i),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:e,decode:s,decodeUnsafe:n}},{sha256:j0}=qw,v_=w_;function E_(t){return j0(j0(t))}var Kh=v_(E_);Object.defineProperty(hu,"__esModule",{value:!0});hu.p2pkh=void 0;const dl=ys,S_=bt,hi=rr(),At=gt,cn=Qt,U0=Kh,Dn=hi.OPS;function A_(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,At.typeforce)({network:At.typeforce.maybe(At.typeforce.Object),address:At.typeforce.maybe(At.typeforce.String),hash:At.typeforce.maybe(At.typeforce.BufferN(20)),output:At.typeforce.maybe(At.typeforce.BufferN(25)),pubkey:At.typeforce.maybe(At.isPoint),signature:At.typeforce.maybe(hi.isCanonicalScriptSignature),input:At.typeforce.maybe(At.typeforce.Buffer)},t);const r=cn.value(()=>{const o=Buffer.from(U0.decode(t.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=cn.value(()=>hi.decompile(t.input)),s=t.network||S_.bitcoin,i={name:"p2pkh",network:s};if(cn.prop(i,"address",()=>{if(!i.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(s.pubKeyHash,0),i.hash.copy(o,1),U0.encode(o)}),cn.prop(i,"hash",()=>{if(t.output)return t.output.slice(3,23);if(t.address)return r().hash;if(t.pubkey||i.pubkey)return dl.hash160(t.pubkey||i.pubkey)}),cn.prop(i,"output",()=>{if(i.hash)return hi.compile([Dn.OP_DUP,Dn.OP_HASH160,i.hash,Dn.OP_EQUALVERIFY,Dn.OP_CHECKSIG])}),cn.prop(i,"pubkey",()=>{if(t.input)return n()[1]}),cn.prop(i,"signature",()=>{if(t.input)return n()[0]}),cn.prop(i,"input",()=>{if(t.pubkey&&t.signature)return hi.compile([t.signature,t.pubkey])}),cn.prop(i,"witness",()=>{if(i.input)return[]}),e.validate){let o=Buffer.from([]);if(t.address){if(r().version!==s.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().hash}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==25||t.output[0]!==Dn.OP_DUP||t.output[1]!==Dn.OP_HASH160||t.output[2]!==20||t.output[23]!==Dn.OP_EQUALVERIFY||t.output[24]!==Dn.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=t.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.pubkey){const a=dl.hash160(t.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!hi.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,At.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=dl.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)}hu.p2pkh=A_;var pu={};Object.defineProperty(pu,"__esModule",{value:!0});pu.p2sh=void 0;const F0=ys,k_=bt,qr=rr(),Ne=gt,zr=Qt,$0=Kh,so=qr.OPS;function x_(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Ne.typeforce)({network:Ne.typeforce.maybe(Ne.typeforce.Object),address:Ne.typeforce.maybe(Ne.typeforce.String),hash:Ne.typeforce.maybe(Ne.typeforce.BufferN(20)),output:Ne.typeforce.maybe(Ne.typeforce.BufferN(23)),redeem:Ne.typeforce.maybe({network:Ne.typeforce.maybe(Ne.typeforce.Object),output:Ne.typeforce.maybe(Ne.typeforce.Buffer),input:Ne.typeforce.maybe(Ne.typeforce.Buffer),witness:Ne.typeforce.maybe(Ne.typeforce.arrayOf(Ne.typeforce.Buffer))}),input:Ne.typeforce.maybe(Ne.typeforce.Buffer),witness:Ne.typeforce.maybe(Ne.typeforce.arrayOf(Ne.typeforce.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||k_.bitcoin);const n={network:r},s=zr.value(()=>{const a=Buffer.from($0.decode(t.address)),c=a.readUInt8(0),u=a.slice(1);return{version:c,hash:u}}),i=zr.value(()=>qr.decompile(t.input)),o=zr.value(()=>{const a=i(),c=a[a.length-1];return{network:r,output:c===so.OP_FALSE?Buffer.from([]):c,input:qr.compile(a.slice(0,-1)),witness:t.witness||[]}});if(zr.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),$0.encode(a)}),zr.prop(n,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return s().hash;if(n.redeem&&n.redeem.output)return F0.hash160(n.redeem.output)}),zr.prop(n,"output",()=>{if(n.hash)return qr.compile([so.OP_HASH160,n.hash,so.OP_EQUAL])}),zr.prop(n,"redeem",()=>{if(t.input)return o()}),zr.prop(n,"input",()=>{if(!(!t.redeem||!t.redeem.input||!t.redeem.output))return qr.compile([].concat(qr.decompile(t.redeem.input),t.redeem.output))}),zr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),zr.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),e.validate){let a=Buffer.from([]);if(t.address){if(s().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(s().hash.length!==20)throw new TypeError("Invalid address");a=s().hash}if(t.hash){if(a.length>0&&!a.equals(t.hash))throw new TypeError("Hash mismatch");a=t.hash}if(t.output){if(t.output.length!==23||t.output[0]!==so.OP_HASH160||t.output[1]!==20||t.output[22]!==so.OP_EQUAL)throw new TypeError("Output is invalid");const u=t.output.slice(2,22);if(a.length>0&&!a.equals(u))throw new TypeError("Hash mismatch");a=u}const c=u=>{if(u.output){const l=qr.decompile(u.output);if(!l||l.length<1)throw new TypeError("Redeem.output too short");if(u.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(qr.countNonPushOnlyOPs(l)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const f=F0.hash160(u.output);if(a.length>0&&!a.equals(f))throw new TypeError("Hash mismatch");a=f}if(u.input){const l=u.input.length>0,f=u.witness&&u.witness.length>0;if(!l&&!f)throw new TypeError("Empty input");if(l&&f)throw new TypeError("Input and witness provided");if(l){const h=qr.decompile(u.input);if(!qr.isPushOnly(h))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const u=i();if(!u||u.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const u=o();if(t.redeem.output&&!t.redeem.output.equals(u.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(u.input))throw new TypeError("Redeem.input mismatch")}c(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!(0,Ne.stacksEqual)(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)}pu.p2sh=x_;var yu={},In={};Object.defineProperty(In,"__esModule",{value:!0});In.bech32m=In.bech32=void 0;const Pc="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Yw={};for(let t=0;t<Pc.length;t++){const e=Pc.charAt(t);Yw[e]=t}function Ti(t){const e=t>>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function L0(t){let e=1;for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+t+")";e=Ti(e)^n>>5}e=Ti(e);for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);e=Ti(e)^n&31}return e}function Xh(t,e,r,n){let s=0,i=0;const o=(1<<r)-1,a=[];for(let c=0;c<t.length;++c)for(s=s<<e|t[c],i+=e;i>=r;)i-=r,a.push(s>>i&o);if(n)i>0&&a.push(s<<r-i&o);else{if(i>=e)return"Excess padding";if(s<<r-i&o)return"Non-zero padding"}return a}function T_(t){return Xh(t,8,5,!0)}function __(t){const e=Xh(t,5,8,!1);if(Array.isArray(e))return e}function P_(t){const e=Xh(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}function Jw(t){let e;t==="bech32"?e=1:e=734539939;function r(o,a,c){if(c=c||90,o.length+7+a.length>c)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let u=L0(o);if(typeof u=="string")throw new Error(u);let l=o+"1";for(let f=0;f<a.length;++f){const h=a[f];if(h>>5)throw new Error("Non 5-bit word");u=Ti(u)^h,l+=Pc.charAt(h)}for(let f=0;f<6;++f)u=Ti(u);u^=e;for(let f=0;f<6;++f){const h=u>>(5-f)*5&31;l+=Pc.charAt(h)}return l}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";const c=o.toLowerCase(),u=o.toUpperCase();if(o!==c&&o!==u)return"Mixed-case string "+o;o=c;const l=o.lastIndexOf("1");if(l===-1)return"No separator character for "+o;if(l===0)return"Missing prefix for "+o;const f=o.slice(0,l),h=o.slice(l+1);if(h.length<6)return"Data too short";let d=L0(f);if(typeof d=="string")return d;const p=[];for(let m=0;m<h.length;++m){const v=h.charAt(m),S=Yw[v];if(S===void 0)return"Unknown character "+v;d=Ti(d)^S,!(m+6>=h.length)&&p.push(S)}return d!==e?"Invalid checksum for "+o:{prefix:f,words:p}}function s(o,a){const c=n(o,a);if(typeof c=="object")return c}function i(o,a){const c=n(o,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:s,decode:i,encode:r,toWords:T_,fromWordsUnsafe:__,fromWords:P_}}In.bech32=Jw("bech32");In.bech32m=Jw("bech32m");Object.defineProperty(yu,"__esModule",{value:!0});yu.p2wpkh=void 0;const hl=ys,O_=bt,lc=rr(),Qe=gt,Hn=Qt,Ka=In,D0=lc.OPS,I_=Buffer.alloc(0);function B_(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Qe.typeforce)({address:Qe.typeforce.maybe(Qe.typeforce.String),hash:Qe.typeforce.maybe(Qe.typeforce.BufferN(20)),input:Qe.typeforce.maybe(Qe.typeforce.BufferN(0)),network:Qe.typeforce.maybe(Qe.typeforce.Object),output:Qe.typeforce.maybe(Qe.typeforce.BufferN(22)),pubkey:Qe.typeforce.maybe(Qe.isPoint),signature:Qe.typeforce.maybe(lc.isCanonicalScriptSignature),witness:Qe.typeforce.maybe(Qe.typeforce.arrayOf(Qe.typeforce.Buffer))},t);const r=Hn.value(()=>{const i=Ka.bech32.decode(t.address),o=i.words.shift(),a=Ka.bech32.fromWords(i.words);return{version:o,prefix:i.prefix,data:Buffer.from(a)}}),n=t.network||O_.bitcoin,s={name:"p2wpkh",network:n};if(Hn.prop(s,"address",()=>{if(!s.hash)return;const i=Ka.bech32.toWords(s.hash);return i.unshift(0),Ka.bech32.encode(n.bech32,i)}),Hn.prop(s,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return r().data;if(t.pubkey||s.pubkey)return hl.hash160(t.pubkey||s.pubkey)}),Hn.prop(s,"output",()=>{if(s.hash)return lc.compile([D0.OP_0,s.hash])}),Hn.prop(s,"pubkey",()=>{if(t.pubkey)return t.pubkey;if(t.witness)return t.witness[1]}),Hn.prop(s,"signature",()=>{if(t.witness)return t.witness[0]}),Hn.prop(s,"input",()=>{if(s.witness)return I_}),Hn.prop(s,"witness",()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]}),e.validate){let i=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");i=r().data}if(t.hash){if(i.length>0&&!i.equals(t.hash))throw new TypeError("Hash mismatch");i=t.hash}if(t.output){if(t.output.length!==22||t.output[0]!==D0.OP_0||t.output[1]!==20)throw new TypeError("Output is invalid");if(i.length>0&&!i.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");i=t.output.slice(2)}if(t.pubkey){const o=hl.hash160(t.pubkey);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch");if(i=o,!(0,Qe.isPoint)(t.pubkey)||t.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(t.witness.length!==2)throw new TypeError("Witness is invalid");if(!lc.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,Qe.isPoint)(t.witness[1])||t.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const o=hl.hash160(t.witness[1]);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(s,t)}yu.p2wpkh=B_;var mu={};Object.defineProperty(mu,"__esModule",{value:!0});mu.p2wsh=void 0;const H0=ys,C_=bt,yn=rr(),Be=gt,un=Qt,Xa=In,z0=yn.OPS,pl=Buffer.alloc(0);function Ya(t){return!!(Buffer.isBuffer(t)&&t.length===65&&t[0]===4&&(0,Be.isPoint)(t))}function N_(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Be.typeforce)({network:Be.typeforce.maybe(Be.typeforce.Object),address:Be.typeforce.maybe(Be.typeforce.String),hash:Be.typeforce.maybe(Be.typeforce.BufferN(32)),output:Be.typeforce.maybe(Be.typeforce.BufferN(34)),redeem:Be.typeforce.maybe({input:Be.typeforce.maybe(Be.typeforce.Buffer),network:Be.typeforce.maybe(Be.typeforce.Object),output:Be.typeforce.maybe(Be.typeforce.Buffer),witness:Be.typeforce.maybe(Be.typeforce.arrayOf(Be.typeforce.Buffer))}),input:Be.typeforce.maybe(Be.typeforce.BufferN(0)),witness:Be.typeforce.maybe(Be.typeforce.arrayOf(Be.typeforce.Buffer))},t);const r=un.value(()=>{const o=Xa.bech32.decode(t.address),a=o.words.shift(),c=Xa.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=un.value(()=>yn.decompile(t.redeem.input));let s=t.network;s||(s=t.redeem&&t.redeem.network||C_.bitcoin);const i={network:s};if(un.prop(i,"address",()=>{if(!i.hash)return;const o=Xa.bech32.toWords(i.hash);return o.unshift(0),Xa.bech32.encode(s.bech32,o)}),un.prop(i,"hash",()=>{if(t.output)return t.output.slice(2);if(t.address)return r().data;if(i.redeem&&i.redeem.output)return H0.sha256(i.redeem.output)}),un.prop(i,"output",()=>{if(i.hash)return yn.compile([z0.OP_0,i.hash])}),un.prop(i,"redeem",()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:pl,witness:t.witness.slice(0,-1)}}),un.prop(i,"input",()=>{if(i.witness)return pl}),un.prop(i,"witness",()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const o=yn.toStack(n());return i.redeem=Object.assign({witness:o},t.redeem),i.redeem.input=pl,[].concat(o,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)}),un.prop(i,"name",()=>{const o=["p2wsh"];return i.redeem!==void 0&&i.redeem.name!==void 0&&o.push(i.redeem.name),o.join("-")}),e.validate){let o=Buffer.from([]);if(t.address){if(r().prefix!==s.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");o=r().data}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==34||t.output[0]!==z0.OP_0||t.output[1]!==32)throw new TypeError("Output is invalid");const a=t.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.redeem){if(t.redeem.network&&t.redeem.network!==s)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){const a=yn.decompile(t.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(t.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(yn.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=H0.sha256(t.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(t.redeem.input&&!yn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!(0,Be.stacksEqual)(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Ya)||t.redeem.output&&(yn.decompile(t.redeem.output)||[]).some(Ya))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const a=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Ya)||(yn.decompile(a)||[]).some(Ya))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,t)}mu.p2wsh=N_;var io={},qs={};Object.defineProperty(qs,"__esModule",{value:!0});qs.getEccLib=qs.initEccLib=void 0;const vo={};function R_(t,e){t?t!==vo.eccLib&&(e!=null&&e.DANGER_DO_NOT_VERIFY_ECCLIB||j_(t),vo.eccLib=t):vo.eccLib=t}qs.initEccLib=R_;function M_(){if(!vo.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return vo.eccLib}qs.getEccLib=M_;const ln=t=>Buffer.from(t,"hex");function j_(t){sr(typeof t.isXOnlyPoint=="function"),sr(t.isXOnlyPoint(ln("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),sr(t.isXOnlyPoint(ln("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),sr(t.isXOnlyPoint(ln("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),sr(t.isXOnlyPoint(ln("0000000000000000000000000000000000000000000000000000000000000001"))),sr(!t.isXOnlyPoint(ln("0000000000000000000000000000000000000000000000000000000000000000"))),sr(!t.isXOnlyPoint(ln("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),sr(typeof t.xOnlyPointAddTweak=="function"),U_.forEach(e=>{const r=t.xOnlyPointAddTweak(ln(e.pubkey),ln(e.tweak));e.result===null?sr(r===null):(sr(r!==null),sr(r.parity===e.parity),sr(Buffer.from(r.xOnlyPubkey).equals(ln(e.result))))})}function sr(t){if(!t)throw new Error("ecc library invalid")}const U_=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];var Yh={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.tweakKey=t.tapTweakHash=t.tapleafHash=t.findScriptPath=t.toHashTree=t.rootHashFromPath=t.MAX_TAPTREE_DEPTH=t.LEAF_VERSION_TAPSCRIPT=void 0;const e=Zs,r=qs,n=ys,s=ut,i=gt;t.LEAF_VERSION_TAPSCRIPT=192,t.MAX_TAPTREE_DEPTH=128;const o=m=>"left"in m&&"right"in m;function a(m,v){if(m.length<33)throw new TypeError(`The control-block length is too small. Got ${m.length}, expected min 33.`);const S=(m.length-33)/32;let T=v;for(let g=0;g<S;g++){const w=m.slice(33+32*g,65+32*g);T.compare(w)<0?T=d(T,w):T=d(w,T)}return T}t.rootHashFromPath=a;function c(m){if((0,i.isTapleaf)(m))return{hash:l(m)};const v=[c(m[0]),c(m[1])];v.sort((g,w)=>g.hash.compare(w.hash));const[S,T]=v;return{hash:d(S.hash,T.hash),left:S,right:T}}t.toHashTree=c;function u(m,v){if(o(m)){const S=u(m.left,v);if(S!==void 0)return[...S,m.right.hash];const T=u(m.right,v);if(T!==void 0)return[...T,m.left.hash]}else if(m.hash.equals(v))return[]}t.findScriptPath=u;function l(m){const v=m.version||t.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",e.Buffer.concat([e.Buffer.from([v]),p(m.output)]))}t.tapleafHash=l;function f(m,v){return n.taggedHash("TapTweak",e.Buffer.concat(v?[m,v]:[m]))}t.tapTweakHash=f;function h(m,v){if(!e.Buffer.isBuffer(m)||m.length!==32||v&&v.length!==32)return null;const S=f(m,v),T=(0,r.getEccLib)().xOnlyPointAddTweak(m,S);return!T||T.xOnlyPubkey===null?null:{parity:T.parity,x:e.Buffer.from(T.xOnlyPubkey)}}t.tweakKey=h;function d(m,v){return n.taggedHash("TapBranch",e.Buffer.concat([m,v]))}function p(m){const v=s.varuint.encodingLength(m.length),S=e.Buffer.allocUnsafe(v);return s.varuint.encode(m.length,S),e.Buffer.concat([S,m])}})(Yh);var kt={},V0;function F_(){if(V0)return kt;V0=1,Object.defineProperty(kt,"__esModule",{value:!0}),kt.toOutputScript=kt.fromOutputScript=kt.toBech32=kt.toBase58Check=kt.fromBech32=kt.fromBase58Check=void 0;const t=bt,e=Jh(),r=rr(),n=gt,s=In,i=Kh,o=40,a=2,c=16,u=2,l=80,f="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function h(g,w){const k=g.slice(2);if(k.length<a||k.length>o)throw new TypeError("Invalid program length for segwit address");const _=g[0]-l;if(_<u||_>c)throw new TypeError("Invalid version for segwit address");if(g[1]!==k.length)throw new TypeError("Invalid script for segwit address");return console.warn(f),v(k,_,w.bech32)}function d(g){const w=Buffer.from(i.decode(g));if(w.length<21)throw new TypeError(g+" is too short");if(w.length>21)throw new TypeError(g+" is too long");const k=w.readUInt8(0),_=w.slice(1);return{version:k,hash:_}}kt.fromBase58Check=d;function p(g){let w,k;try{w=s.bech32.decode(g)}catch{}if(w){if(k=w.words[0],k!==0)throw new TypeError(g+" uses wrong encoding")}else if(w=s.bech32m.decode(g),k=w.words[0],k===0)throw new TypeError(g+" uses wrong encoding");const _=s.bech32.fromWords(w.words.slice(1));return{version:k,prefix:w.prefix,data:Buffer.from(_)}}kt.fromBech32=p;function m(g,w){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const k=Buffer.allocUnsafe(21);return k.writeUInt8(w,0),g.copy(k,1),i.encode(k)}kt.toBase58Check=m;function v(g,w,k){const _=s.bech32.toWords(g);return _.unshift(w),w===0?s.bech32.encode(k,_):s.bech32m.encode(k,_)}kt.toBech32=v;function S(g,w){w=w||t.bitcoin;try{return e.p2pkh({output:g,network:w}).address}catch{}try{return e.p2sh({output:g,network:w}).address}catch{}try{return e.p2wpkh({output:g,network:w}).address}catch{}try{return e.p2wsh({output:g,network:w}).address}catch{}try{return e.p2tr({output:g,network:w}).address}catch{}try{return h(g,w)}catch{}throw new Error(r.toASM(g)+" has no matching Address")}kt.fromOutputScript=S;function T(g,w){w=w||t.bitcoin;let k,_;try{k=d(g)}catch{}if(k){if(k.version===w.pubKeyHash)return e.p2pkh({hash:k.hash}).output;if(k.version===w.scriptHash)return e.p2sh({hash:k.hash}).output}else{try{_=p(g)}catch{}if(_){if(_.prefix!==w.bech32)throw new Error(g+" has an invalid prefix");if(_.version===0){if(_.data.length===20)return e.p2wpkh({hash:_.data}).output;if(_.data.length===32)return e.p2wsh({hash:_.data}).output}else if(_.version===1){if(_.data.length===32)return e.p2tr({pubkey:_.data}).output}else if(_.version>=u&&_.version<=c&&_.data.length>=a&&_.data.length<=o)return console.warn(f),r.compile([_.version+l,_.data])}}throw new Error(g+" has no matching Script")}return kt.toOutputScript=T,kt}var G0;function $_(){if(G0)return io;G0=1,Object.defineProperty(io,"__esModule",{value:!0}),io.p2tr=void 0;const t=Zs,e=bt,r=rr(),n=gt,s=qs,i=Yh,o=Qt,a=In,c=F_(),u=r.OPS,l=1,f=80;function h(d,p){if(!d.address&&!d.output&&!d.pubkey&&!d.internalPubkey&&!(d.witness&&d.witness.length>1))throw new TypeError("Not enough data");p=Object.assign({validate:!0},p||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},d);const m=o.value(()=>(0,c.fromBech32)(d.address)),v=o.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===f?d.witness.slice(0,-1):d.witness.slice()}),S=o.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),T=d.network||e.bitcoin,g={name:"p2tr",network:T};if(o.prop(g,"address",()=>{if(!g.pubkey)return;const w=a.bech32m.toWords(g.pubkey);return w.unshift(l),a.bech32m.encode(T.bech32,w)}),o.prop(g,"hash",()=>{const w=S();if(w)return w.hash;const k=v();if(k&&k.length>1){const _=k[k.length-1],O=_[0]&n.TAPLEAF_VERSION_MASK,B=k[k.length-2],N=(0,i.tapleafHash)({output:B,version:O});return(0,i.rootHashFromPath)(_,N)}return null}),o.prop(g,"output",()=>{if(g.pubkey)return r.compile([u.OP_1,g.pubkey])}),o.prop(g,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),o.prop(g,"redeem",()=>{const w=v();if(!(!w||w.length<2))return{output:w[w.length-2],witness:w.slice(0,-2),redeemVersion:w[w.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(g,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return m().data;if(g.internalPubkey){const w=(0,i.tweakKey)(g.internalPubkey,g.hash);if(w)return w.x}}),o.prop(g,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const w=v();if(w&&w.length>1)return w[w.length-1].slice(1,33)}),o.prop(g,"signature",()=>{if(d.signature)return d.signature;const w=v();if(!(!w||w.length!==1))return w[0]}),o.prop(g,"witness",()=>{if(d.witness)return d.witness;const w=S();if(w&&d.redeem&&d.redeem.output&&d.internalPubkey){const k=(0,i.tapleafHash)({output:d.redeem.output,version:g.redeemVersion}),_=(0,i.findScriptPath)(w,k);if(!_)return;const O=(0,i.tweakKey)(d.internalPubkey,w.hash);if(!O)return;const B=t.Buffer.concat([t.Buffer.from([g.redeemVersion|O.parity]),d.internalPubkey].concat(_));return[d.redeem.output,B]}if(d.signature)return[d.signature]}),p.validate){let w=t.Buffer.from([]);if(d.address){if(T&&T.bech32!==m().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(m().version!==l)throw new TypeError("Invalid address version");if(m().data.length!==32)throw new TypeError("Invalid address data");w=m().data}if(d.pubkey){if(w.length>0&&!w.equals(d.pubkey))throw new TypeError("Pubkey mismatch");w=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==u.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(w.length>0&&!w.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");w=d.output.slice(2)}if(d.internalPubkey){const O=(0,i.tweakKey)(d.internalPubkey,g.hash);if(w.length>0&&!w.equals(O.x))throw new TypeError("Pubkey mismatch");w=O.x}if(w&&w.length&&!(0,s.getEccLib)().isXOnlyPoint(w))throw new TypeError("Invalid pubkey for p2tr");const k=S();if(d.hash&&k&&!d.hash.equals(k.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&k){const O=(0,i.tapleafHash)({output:d.redeem.output,version:g.redeemVersion});if(!(0,i.findScriptPath)(k,O))throw new TypeError("Redeem script not in tree")}const _=v();if(d.redeem&&g.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==g.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(d.redeem.output){if(r.decompile(d.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(g.redeem.output&&!d.redeem.output.equals(g.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&g.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,g.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(_&&_.length)if(_.length===1){if(d.signature&&!d.signature.equals(_[0]))throw new TypeError("Signature mismatch")}else{const O=_[_.length-1];if(O.length<33)throw new TypeError(`The control-block length is too small. Got ${O.length}, expected min 33.`);if((O.length-33)%32!==0)throw new TypeError(`The control-block length of ${O.length} is incorrect!`);const B=(O.length-33)/32;if(B>128)throw new TypeError(`The script path is too long. Got ${B}, expected max 128.`);const N=O.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals(N))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint(N))throw new TypeError("Invalid internalPubkey for p2tr witness");const $=O[0]&n.TAPLEAF_VERSION_MASK,j=_[_.length-2],H=(0,i.tapleafHash)({output:j,version:$}),G=(0,i.rootHashFromPath)(O,H),ee=(0,i.tweakKey)(N,G);if(!ee)throw new TypeError("Invalid outputKey for p2tr witness");if(w.length&&!w.equals(ee.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(ee.parity!==(O[0]&1))throw new Error("Incorrect parity")}}return Object.assign(g,d)}return io.p2tr=h,io}var q0;function Jh(){return q0||(q0=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.p2tr=t.p2wsh=t.p2wpkh=t.p2sh=t.p2pkh=t.p2pk=t.p2ms=t.embed=void 0;const e=lu;Object.defineProperty(t,"embed",{enumerable:!0,get:function(){return e.p2data}});const r=fu;Object.defineProperty(t,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=du;Object.defineProperty(t,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=hu;Object.defineProperty(t,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=pu;Object.defineProperty(t,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const o=yu;Object.defineProperty(t,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=mu;Object.defineProperty(t,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=$_();Object.defineProperty(t,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(ll)),ll}Object.defineProperty(Oe,"__esModule",{value:!0});Oe.signatureBlocksAction=Oe.checkInputForSig=Oe.pubkeyInScript=Oe.pubkeyPositionInScript=Oe.witnessStackToScriptWitness=Oe.isP2TR=Oe.isP2SHScript=Oe.isP2WSHScript=Oe.isP2WPKH=Oe.isP2PKH=Oe.isP2PK=Oe.isP2MS=void 0;const W0=Oa,Eo=rr(),Ja=Pa,L_=ys,Qs=Jh();function ei(t){return e=>{try{return t({output:e}),!0}catch{return!1}}}Oe.isP2MS=ei(Qs.p2ms);Oe.isP2PK=ei(Qs.p2pk);Oe.isP2PKH=ei(Qs.p2pkh);Oe.isP2WPKH=ei(Qs.p2wpkh);Oe.isP2WSHScript=ei(Qs.p2wsh);Oe.isP2SHScript=ei(Qs.p2sh);Oe.isP2TR=ei(Qs.p2tr);function D_(t){let e=Buffer.allocUnsafe(0);function r(o){e=Buffer.concat([e,Buffer.from(o)])}function n(o){const a=e.length,c=W0.encodingLength(o);e=Buffer.concat([e,Buffer.allocUnsafe(c)]),W0.encode(o,e,a)}function s(o){n(o.length),r(o)}function i(o){n(o.length),o.forEach(s)}return i(t),e}Oe.witnessStackToScriptWitness=D_;function Zw(t,e){const r=(0,L_.hash160)(t),n=t.slice(1,33),s=Eo.decompile(e);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(t)||i.equals(r)||i.equals(n))}Oe.pubkeyPositionInScript=Zw;function H_(t,e){return Zw(t,e)!==-1}Oe.pubkeyInScript=H_;function z_(t,e){return V_(t).some(n=>Qw(n,Eo.signature.decode,e))}Oe.checkInputForSig=z_;function Qw(t,e,r){const{hashType:n}=e(t),s=[];switch(n&Ja.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case Ja.Transaction.SIGHASH_ALL:break;case Ja.Transaction.SIGHASH_SINGLE:case Ja.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}Oe.signatureBlocksAction=Qw;function V_(t){let e=[];if((t.partialSig||[]).length===0){if(!t.finalScriptSig&&!t.finalScriptWitness)return[];e=G_(t)}else e=t.partialSig;return e.map(r=>r.signature)}function G_(t){const e=t.finalScriptSig?Eo.decompile(t.finalScriptSig)||[]:[],r=t.finalScriptWitness?Eo.decompile(t.finalScriptWitness)||[]:[];return e.concat(r).filter(n=>Buffer.isBuffer(n)&&Eo.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Le,"__esModule",{value:!0});Le.checkTaprootInputForSigs=Le.tapTreeFromList=Le.tapTreeToList=Le.tweakInternalPubKey=Le.checkTaprootOutputFields=Le.checkTaprootInputFields=Le.isTaprootOutput=Le.isTaprootInput=yo=Le.serializeTaprootSignature=Le.tapScriptFinalizer=Le.toXOnly=void 0;const Zh=gt,q_=Pa,bu=Oe,us=Yh,W_=Jh(),K_=Oe,X_=t=>t.length===32?t:t.slice(1,33);Le.toXOnly=X_;function Y_(t,e,r){const n=p8(e,t,r);try{const i=d8(e,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,bu.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${t}: ${s}`)}}Le.tapScriptFinalizer=Y_;function J_(t,e){const r=e?Buffer.from([e]):Buffer.from([]);return Buffer.concat([t,r])}var yo=Le.serializeTaprootSignature=J_;function fc(t){return t&&!!(t.tapInternalKey||t.tapMerkleRoot||t.tapLeafScript&&t.tapLeafScript.length||t.tapBip32Derivation&&t.tapBip32Derivation.length||t.witnessUtxo&&(0,bu.isP2TR)(t.witnessUtxo.script))}Le.isTaprootInput=fc;function dc(t,e){return t&&!!(t.tapInternalKey||t.tapTree||t.tapBip32Derivation&&t.tapBip32Derivation.length||e&&(0,bu.isP2TR)(e))}Le.isTaprootOutput=dc;function Z_(t,e,r){u8(t,e,r),f8(t,e,r)}Le.checkTaprootInputFields=Z_;function Q_(t,e,r){l8(t,e,r),e8(t,e)}Le.checkTaprootOutputFields=Q_;function e8(t,e){if(!e.tapTree&&!e.tapInternalKey)return;const r=e.tapInternalKey||t.tapInternalKey,n=e.tapTree||t.tapTree;if(r){const{script:s}=t,i=t8(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function t8(t,e){const r=e&&e1(e.leaves),{output:n}=(0,W_.p2tr)({internalPubkey:t,scriptTree:r});return n}function r8(t,e){const r=e.tapInternalKey,n=r&&(0,us.tweakKey)(r,e.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${t}. Public key: ${r&&r.toString("hex")}`);return n.x}Le.tweakInternalPubKey=r8;function n8(t){if(!(0,Zh.isTaptree)(t))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return vd(t)}Le.tapTreeToList=n8;function e1(t=[]){return t.length===1&&t[0].depth===0?{output:t[0].script,version:t[0].leafVersion}:c8(t)}Le.tapTreeFromList=e1;function s8(t,e){return o8(t).some(n=>(0,K_.signatureBlocksAction)(n,i8,e))}Le.checkTaprootInputForSigs=s8;function i8(t){return{signature:t.slice(0,64),hashType:t.slice(64)[0]||q_.Transaction.SIGHASH_DEFAULT}}function o8(t){const e=[];if(t.tapKeySig&&e.push(t.tapKeySig),t.tapScriptSig&&e.push(...t.tapScriptSig.map(r=>r.signature)),!e.length){const r=a8(t.finalScriptWitness);r&&e.push(r)}return e}function a8(t){if(!t)return;const e=t.slice(2);if(e.length===64||e.length===65)return e}function vd(t,e=[],r=0){if(r>us.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return t?(0,Zh.isTapleaf)(t)?(e.push({depth:r,leafVersion:t.version||us.LEAF_VERSION_TAPSCRIPT,script:t.output}),e):(t[0]&&vd(t[0],e,r+1),t[1]&&vd(t[1],e,r+1),e):[]}function c8(t){let e;for(const r of t)if(e=Ed(r,e),!e)throw new Error("No room left to insert tapleaf in tree");return e}function Ed(t,e,r=0){if(r>us.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(t.depth===r)return e?void 0:{output:t.script,version:t.leafVersion};if((0,Zh.isTapleaf)(e))return;const n=Ed(t,e&&e[0],r+1);if(n)return[n,e&&e[1]];const s=Ed(t,e&&e[1],r+1);if(s)return[e&&e[0],s]}function u8(t,e,r){const n=fc(t)&&_i(e),s=_i(t)&&fc(e),i=t===e&&fc(e)&&_i(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function l8(t,e,r){const n=dc(t)&&_i(e),s=_i(t)&&dc(e),i=t===e&&dc(e)&&_i(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function f8(t,e,r){if(e.tapMerkleRoot){const n=(e.tapLeafScript||[]).every(i=>yl(i,e.tapMerkleRoot)),s=(t.tapLeafScript||[]).every(i=>yl(i,e.tapMerkleRoot));if(!n||!s)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(t.tapMerkleRoot&&!(e.tapLeafScript||[]).every(s=>yl(s,t.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function yl(t,e){if(!e)return!0;const r=(0,us.tapleafHash)({output:t.script,version:t.leafVersion});return(0,us.rootHashFromPath)(t.controlBlock,r).equals(e)}function d8(t,e){const r=(0,us.tapleafHash)({output:e.script,version:e.leafVersion});return(t.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>h8(e.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function h8(t,e){return Object.assign({positionInScript:(0,bu.pubkeyPositionInScript)(e.pubkey,t)},e)}function p8(t,e,r){if(!t.tapScriptSig||!t.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${e}. No tapleaf script signature provided.`);const n=(t.tapLeafScript||[]).sort((s,i)=>s.controlBlock.length-i.controlBlock.length).find(s=>y8(s,t.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${e}. Signature for tapleaf script not found.`);return n}function y8(t,e,r){const n=(0,us.tapleafHash)({output:t.script,version:t.leafVersion});return(!r||r.equals(n))&&e.find(i=>i.leafHash.equals(n))!==void 0}function _i(t){return t&&!!(t.redeemScript||t.witnessScript||t.bip32Derivation&&t.bip32Derivation.length)}const ir={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:t=>"counterparty signature not found for utxo "+t,invalidCounterpartySigForUTXO:t=>"invalid counterparty signature for utxo "+t,htlcNotExpired:t=>`HTLC not expired, need more ${t} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},Za=192;Ae.initEccLib(lr);let K0=class{constructor(e,r){this.signer=e,this.internalPubkey=k0(),this.network=iT(r)}address(e,r){const n=this.generateLeaves(e,r),{address:s}=Ae.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:n});if(!s)throw new Error(ir.htlcAddressGenerationFailed);return s}async _buildRawTx(e,r,n,s,i){const o=new Ae.Transaction;o.version=2;const a=this.address(e,n||"redeem"),c=await this.getProvider();let u=[];if(i&&i.length>0)for(const h of i){const d=await c.getTransaction(h);for(let p=0;p<d.vout.length;p++){const m=d.vout[p];m.scriptpubkey_address===a&&u.push({txid:d.txid,vout:p,value:m.value,status:{confirmed:!1}})}}else u=await c.getUTXOs(a);const l=u.reduce((h,d)=>h+d.value,0);if(l===0)throw new Error(`${a} ${ir.notFunded}`);for(let h=0;h<u.length;h++)o.addInput(Buffer.from(u[h].txid,"hex").reverse(),u[h].vout);if(s!=null&&s.vSize){const h=await c.getFeeRates(),d=Math.ceil(h.hourFee*s.vSize),p=l-d;return o.addOutput(Ae.address.toOutputScript(r,this.network),p),{tx:o,usedUtxos:u}}const f=(s==null?void 0:s.fee)??await c.suggestFee(a,l,ki.MEDIUM);return o.addOutput(Ae.address.toOutputScript(r,this.network),l-f),{tx:o,usedUtxos:u,fee:f,balance:l}}getOutputScript(e,r){return Ae.address.toOutputScript(this.address(e,r||"redeem"),this.network)}async initiate(e,r){const n=await this.getProvider(),s=await this.signer.getAddress();let i,o;V.isOrder(e)?(i=e.source_swap.swap_id,o=Number(e.source_swap.amount)):(i=e.to,o=Number(e.amount)),r===void 0&&(r=await n.suggestFee(s,o,ki.MEDIUM));const a=await this.signer.send(i,o,r);return E.Ok(a)}async generateRedeemSACP(e,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(e,e.destination_swap.delegate,"redeem",{fee:n}),o=this.getOutputScript(e,"redeem"),a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1,e),u=i.map(f=>f.value),l=ro(o,i.length);for(let f=0;f<s.ins.length;f++){const h=s.hashForWitnessV1(f,l,u,a,c),d=await this.signer.signSchnorr(h);s.setWitness(f,[yo(d,a),Buffer.from(r,"hex"),this.redeemLeaf(E.trim0x(e.destination_swap.secret_hash),$e(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return s.toHex()}async generateInstantRefundSACP(e){const r=this.getOutputScript(e,"instantRefund"),{tx:n,usedUtxos:s,fee:i}=await this._buildRawTx(e,e.destination_swap.delegate,"instantRefund",{fee:0});n.outs=[];const o=Math.max(...s.map(f=>f.value));s.forEach(({value:f})=>{n.addOutput(r,f-(f===o?i??0:0))});const a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2,e),u=s.map(f=>f.value),l=ro(r,s.length);for(let f=0;f<n.ins.length;f++){const h=n.hashForWitnessV1(f,l,u,a,c),d=await this.signer.signSchnorr(h);n.setWitness(f,[yo(d,a),yo(d,a),this.instantRefundLeaf($e(e.source_swap.initiator),$e(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return n.toHex()}async generateInstantRefundSACPWithHash(e){const r=[],n=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY;for(let s=0;s<e.length;s++){const i=Buffer.from(e[s],"hex"),o=await this.signer.signSchnorr(i);r.push(yo(o,n).toString("hex"))}return E.Ok(r)}async instantRefund(e,r,n){v0(r.length>0,ir.noCounterpartySigs);const{tx:s,usedUtxos:i}=await this._buildRawTx(e,await this.signer.getAddress(),"instantRefund",{fee:n});for(const h of i)if(!r.find(d=>d.utxo===h.txid))throw new Error(ir.counterPartySigNotFound(h.txid));const o=this.getOutputScript(e,"instantRefund"),a=Ae.Transaction.SIGHASH_DEFAULT,c=this.leafHash(2,e),u=i.map(h=>h.value),l=ro(o,i.length);for(let h=0;h<s.ins.length;h++){const d=s.hashForWitnessV1(h,l,u,a,c);if(!lr.verifySchnorr(d,Buffer.from($e(e.destination_swap.delegate),"hex"),Buffer.from(r[h].sig,"hex")))throw new Error(ir.invalidCounterpartySigForUTXO(r[h].utxo));const p=await this.signer.signSchnorr(d),m=Buffer.from(s.ins[h].hash).reverse().toString("hex"),v=r.find(S=>S.utxo===m);if(!v)throw new Error(ir.counterPartySigNotFound(m));s.setWitness(h,[Buffer.from(v.sig,"hex"),p,this.instantRefundLeaf($e(e.source_swap.initiator),$e(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return await(await this.getProvider()).broadcast(s.toHex())}async redeem(e,r,n){const s=await this.getRedeemHex(e,r,n);if(!s.ok)return E.Err(s.error);const o=await(await this.getProvider()).broadcast(s.val);return E.Ok(o)}async getRedeemHex(e,r,n){v0(Ae.crypto.sha256(Buffer.from(r,"hex")).toString("hex")===E.trim0x(e.destination_swap.secret_hash),ir.secretMismatch);const o=(V.isBitcoin(e.source_swap.chain)?e.source_swap.redeemer:e.destination_swap.redeemer)??await this.signer.getAddress(),{tx:a,usedUtxos:c}=await this._buildRawTx(e,o,"redeem",{fee:0},n),u=this.leafHash(1,e),l=c.map(p=>p.value),f=ro(this.getOutputScript(e,"redeem"),c.length),h=Ae.Transaction.SIGHASH_DEFAULT;for(let p=0;p<a.ins.length;p++){const m=a.hashForWitnessV1(p,f,l,h,u),v=await this.signer.signSchnorr(m);a.setWitness(p,[v,Buffer.from(r,"hex"),this.redeemLeaf(E.trim0x(e.destination_swap.secret_hash),$e(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}const{tx:d}=await this._buildRawTx(e,o,"redeem",{vSize:a.virtualSize()},n);for(let p=0;p<d.ins.length;p++){const m=d.hashForWitnessV1(p,f,l,h,u),v=await this.signer.signSchnorr(m);d.setWitness(p,[v,Buffer.from(r,"hex"),this.redeemLeaf(E.trim0x(e.destination_swap.secret_hash),$e(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return E.Ok(d.toHex())}async refund(e,r){const{tx:n,usedUtxos:s}=await this._buildRawTx(e,e.source_swap.delegate??await this.signer.getAddress(),"refund",{fee:r}),[i,o]=await this.canRefund(e,s);if(!i)throw new Error(ir.htlcNotExpired(o));const a=this.leafHash(0,e),c=s.map(d=>d.value),u=ro(this.getOutputScript(e,"refund"),s.length),l=Ae.Transaction.SIGHASH_DEFAULT;for(let d=0;d<n.ins.length;d++){n.ins[d].sequence=e.source_swap.timelock;const p=n.hashForWitnessV1(d,u,c,l,a),m=await this.signer.signSchnorr(p);n.setWitness(d,[m,this.refundLeaf(e.source_swap.timelock,$e(e.source_swap.initiator)),await this.generateControlBlockFor(0,e)])}const h=await(await this.getProvider()).broadcast(n.toHex());return E.Ok(h)}async canRefund(e,r){const s=await(await this.getProvider()).getLatestTip();for(const i of r){let o=0;if(i.status.confirmed&&i.status.block_height+e.source_swap.timelock>s?o=i.status.block_height+e.source_swap.timelock-s+1:i.status.confirmed||(o=e.source_swap.timelock+1),o>0)return[!1,o]}return[!0,0]}async generateControlBlockFor(e,r){let n,s;switch(e){case 1:n=this.redeemLeaf(E.trim0x(r.destination_swap.secret_hash),$e(r.destination_swap.delegate)),s=this.generateLeaves(r,"redeem");break;case 0:n=this.refundLeaf(r.source_swap.timelock,$e(r.source_swap.initiator)),s=this.generateLeaves(r,"refund");break;case 2:n=this.instantRefundLeaf($e(r.source_swap.initiator),$e(r.destination_swap.delegate)),s=this.generateLeaves(r,"instantRefund");break;default:throw new Error(ir.controlBlockGenerationFailed)}const i=await this.signer.getNetwork(),o=Ae.payments.p2tr({internalPubkey:k0(),network:i,scriptTree:s,redeem:{output:n,redeemVersion:Za}});if(!o.witness)throw new Error(ir.controlBlockGenerationFailed);return o.witness[o.witness.length-1]}leafHash(e,r){let n;switch(e){case 1:n=this.redeemLeaf(E.trim0x(r.destination_swap.secret_hash),$e(r.destination_swap.delegate));break;case 0:n=this.refundLeaf(r.source_swap.timelock,$e(r.source_swap.initiator));break;case 2:n=this.instantRefundLeaf($e(r.source_swap.initiator),$e(r.destination_swap.redeemer));break;default:throw new Error(ir.invalidLeaf)}return Ae.crypto.taggedHash("TapLeaf",Jx(n))}refundLeaf(e,r){return Ae.script.fromASM(`
53
+ ${Ae.script.number.encode(e).toString("hex")}
54
+ OP_CHECKSEQUENCEVERIFY
55
+ OP_DROP
56
+ ${r}
57
+ OP_CHECKSIG
58
+ `.trim().replace(/\s+/g," "))}redeemLeaf(e,r){return Ae.script.fromASM(`
59
+ OP_SHA256
60
+ ${e}
61
+ OP_EQUALVERIFY
62
+ ${r}
63
+ OP_CHECKSIG
64
+ `.trim().replace(/\s+/g," "))}instantRefundLeaf(e,r){return Ae.script.fromASM(`
65
+ ${e}
66
+ OP_CHECKSIG
67
+ ${r}
68
+ OP_CHECKSIGADD
69
+ OP_2
70
+ OP_NUMEQUAL
71
+ `.trim().replace(/\s+/g," "))}generateLeaves(e,r){let n,s,i;switch(r){case"redeem":n=e.destination_swap,s=n.delegate,i=n.delegate;break;case"refund":n=e.source_swap,s=n.delegate,i=n.delegate;break;case"instantRefund":n=e.source_swap,s=n.redeemer,i=n.redeemer;break;default:throw new Error("Invalid leaf generation type")}return[{version:Za,output:this.redeemLeaf(n.secret_hash,$e(s))},[{version:Za,output:this.refundLeaf(n.timelock,$e(n.initiator))},{version:Za,output:this.instantRefundLeaf($e(n.initiator),$e(i))}]]}generateMerkleProofFor(e,r){const n=this.leafHash(1,r),s=this.leafHash(2,r),i=this.leafHash(0,r);switch(e){case 1:{const o=Qx(i,s);return[Ae.crypto.taggedHash("TapBranch",Buffer.concat(o))]}case 0:return[s,n];case 2:return[i,n];default:throw new Error(ir.invalidLeaf)}}getProvider(){return this.signer.getProvider()}get getPublicKey(){return this.signer.getPublicKey()}get htlcActorAddress(){return this.signer.getPublicKey()}};class t1{constructor(e,r){this.quoteUrl=new E.Url(e),this.auth=r}async getQuoteFromAssets({fromAsset:e,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const o=V.ChainAsset.from(e),a=V.ChainAsset.from(r);return this.getQuote(o,a,n,s,i)}async getQuote(e,r,n,s=!1,i){try{const o=await this.auth.getAuthHeaders();if(o.error)return E.Err(o.error);const a={from:V.ChainAsset.from(e).toString(),to:V.ChainAsset.from(r).toString(),...s?{to_amount:n.toString()}:{from_amount:n.toString()},...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()}},c=this.quoteUrl.endpoint("/v2/quote").addSearchParams(a),u=await E.Fetcher.get(c,{retryCount:0,...i==null?void 0:i.request,headers:{...o.val,"Content-Type":"application/json"}});return u.error?E.Err(u.error):u.result?E.Ok(u.result):E.Err("GetQuote: Unexpected error, result is undefined")}catch(o){return E.Err("GetQuote:",String(o))}}}class $i extends E.EventBroker{get isInitialized(){return!!this.digestKey}constructor(e,r){super(),this.digestKey=e,this.walletClient=r}static fromDigestKey(e){return new $i(E.trim0x(e))}static fromWalletClient(e){return new $i(void 0,e)}async initialize(){if(this.digestKey)return E.Ok("Already initialized");const e=await this.deriveDigestKeyFromWalletClient();return e.error?E.Err(e.error):(this.emit("initialized",!0),E.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return E.Err("No walletClient found");if(!this.walletClient.account)return E.Err("No account found");try{const e=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=E.trim0x(fo(e)),this.emit("initialized",!0),E.Ok(this.digestKey)}catch(e){return E.Err("Failed to initialize: "+e)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return E.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const e=await this.deriveDigestKeyFromWalletClient();if(e.error)return E.Err(e.error)}return this.digestKey?E.Ok(this.digestKey):E.Err("No private key found")}async generateSecret(e){const r=await this.signMessage(e);if(!r.ok)return E.Err(r.error);const n=fo(E.with0x(r.val)),s=fo(n);return E.Ok({secret:n,secretHash:s})}async signMessage(e){if(!this.digestKey){const u=await this.getDigestKey();if(!u.ok)return E.Err(u.error);this.digestKey=u.val}const r=ic.ECPairFactory(lr),n="Garden.fi"+e.toString(),s=Buffer.from(n,"utf8"),i=fo(s),o=Buffer.from(E.trim0x(this.digestKey),"hex");if(o.length!==32)return E.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(E.trim0x(i),"hex"));return E.Ok(c.toString("hex"))}}const r1=[{inputs:[{internalType:"address",name:"token_",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"initiateWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],internalType:"struct HTLC.InitWithSig[]",name:"inits",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],internalType:"struct HTLC.Redeem[]",name:"redeems",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],internalType:"struct HTLC.Refund[]",name:"refunds",type:"tuple[]"}],name:"multicall",outputs:[{internalType:"bool[]",name:"results",type:"bool[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address",name:"initiator",type:"address"},{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"contract IERC20",name:"",type:"address"}],stateMutability:"view",type:"function"}],m8=[{inputs:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[],name:"NativeHTLC__DuplicateOrder",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectFundsRecieved",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectSecret",type:"error"},{inputs:[],name:"NativeHTLC__InsufficientBalance",type:"error"},{inputs:[],name:"NativeHTLC__InvalidRedeemerSignature",type:"error"},{inputs:[],name:"NativeHTLC__OrderFulfilled",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotExpired",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotInitiated",type:"error"},{inputs:[],name:"NativeHTLC__SameInitiatorAndRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressInitiator",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAmount",type:"error"},{inputs:[],name:"NativeHTLC__ZeroTimelock",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiateOnBehalf",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"instantRefundDigest",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];class ti{constructor(e,r){this.auth=e,this.url=r instanceof E.Url?r:new E.Url(r)}async initiate(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return E.Err(n.error);const s=await E.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:r}),headers:{...n.val,"Content-Type":"application/json"}});return s.error||!s.result?E.Err(s.error||"Initiate failed"):E.Ok(s.result)}catch(n){return E.Err(String(n))}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return E.Err(n.error);const s=await E.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:E.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return s.error?E.Err(s.error):s.result?E.Ok(s.result):E.Err("Redeem: No result found")}catch(n){return E.Err(String(n))}}}const b8=async(t,e)=>{if(!t.account)return E.Err("No account found");try{const n=await Ah({address:E.with0x(e.htlc),abi:m8,client:t}).write.initiate([E.with0x(e.redeemer),e.timelock,e.amount,E.with0x(e.secretHash)],{account:t.account,chain:t.chain,value:e.amount}),s=await E.waitForTransactionReceipt(t,n);return s.ok?!s.val||s.val.status!=="success"?E.Err("Native initiate transaction failed"):E.Ok(n):E.Err(s.error)}catch(r){return Lh(r)?E.Ok("already initiated"):E.Err("Failed to initiate on native HTLC",String(r))}},g8=async(t,e,r,n)=>{if(!t.account)return E.Err("No account found");try{const s=Ah({address:E.with0x(n.htlc),abi:r1,client:t}),i=await E.checkAllowanceAndApprove(Number(n.amount),n.token,n.htlc,t);if(!i.ok)return E.Err(i.error);const o=await s.read.eip712Domain(),a=await t.signTypedData({account:t.account,domain:{name:o[1],version:o[2],chainId:Number(o[3]),verifyingContract:o[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:E.with0x(n.redeemer),timelock:n.timelock,amount:n.amount,secretHash:E.with0x(n.secretHash)}}),c=new ti(r,e),u=await kw({wallet:t,attempt:()=>c.initiate(n.orderId,a)});if(u)return E.Ok(u);const l=await s.write.initiate([E.with0x(n.redeemer),n.timelock,n.amount,E.with0x(n.secretHash)],{account:t.account,chain:t.chain}),f=await E.waitForTransactionReceipt(t,l);return f.ok?!f.val||f.val.status!=="success"?E.Err("Failed to initiate (fallback)"):E.Ok(l):E.Err(f.error)}catch(s){return Lh(s)?E.Ok("already initiated"):E.Err("Failed to initiate on ERC20 HTLC",String(s))}},w8=async(t,e)=>{if(!t.account)return E.Err("No account found");try{const r=await t.sendTransaction({account:t.account,to:E.with0x(e.to),value:BigInt(e.value),data:E.with0x(e.data),gas:BigInt(e.gas_limit),chain:t.chain}),n=await E.waitForTransactionReceipt(t,r);return n.ok?!n.val||n.val.status!=="success"?E.Err("Approval transaction failed"):E.Ok(r):E.Err(n.error)}catch(r){return E.Err("Failed to execute approval: "+String(r))}},v8={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},E8={block:Q5({format(t){var r;return{transactions:(r=t.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=ga(n);return s.typeHex==="0x7e"&&(s.isSystemTx=n.isSystemTx,s.mint=n.mint?ot(n.mint):void 0,s.sourceHash=n.sourceHash,s.type="deposit"),s}),stateRoot:t.stateRoot}}}),transaction:J5({format(t){const e={};return t.type==="0x7e"&&(e.isSystemTx=t.isSystemTx,e.mint=t.mint?ot(t.mint):void 0,e.sourceHash=t.sourceHash,e.type="deposit"),e}}),transactionReceipt:hS({format(t){return{l1GasPrice:t.l1GasPrice?ot(t.l1GasPrice):null,l1GasUsed:t.l1GasUsed?ot(t.l1GasUsed):null,l1Fee:t.l1Fee?ot(t.l1Fee):null,l1FeeScalar:t.l1FeeScalar?Number(t.l1FeeScalar):null}}})};function S8(t,e){return x8(t)?k8(t):YS(t,e)}const A8={transaction:S8};function k8(t){T8(t);const{sourceHash:e,data:r,from:n,gas:s,isSystemTx:i,mint:o,to:a,value:c}=t,u=[e,n,a??"0x",o?Ot(o):"0x",c?Ot(c):"0x",s?Ot(s):"0x",i?"0x1":"0x",r??"0x"];return Nr(["0x7e",cs(u)])}function x8(t){return t.type==="deposit"||typeof t.sourceHash<"u"}function T8(t){const{from:e,to:r}=t;if(e&&!st(e))throw new Bt({address:e});if(r&&!st(r))throw new Bt({address:r})}const Li={blockTime:2e3,contracts:v8,formatters:E8,serializers:A8},_8=ht({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),P8=ht({id:421614,name:"Arbitrum Sepolia",blockTime:250,nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),oo=1,n1=ht({...Li,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...Li.contracts,disputeGameFactory:{[oo]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[oo]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[oo]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[oo]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:oo});({...n1});const ao=11155111,s1=ht({...Li,id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://sepolia.basescan.org",apiUrl:"https://api-sepolia.basescan.org/api"}},contracts:{...Li.contracts,disputeGameFactory:{[ao]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[ao]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[ao]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[ao]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:ao});({...s1});const O8=ht({id:80094,name:"Berachain",blockTime:2e3,nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0x4D41762915F83c76EcaF6776d9b08076aA32b492",blockCreated:9310021}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),I8=ht({id:80084,name:"Berachain bArtio",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:109269},ensRegistry:{address:"0xB0eef18971290b333450586D33dcA6cE122651D2",blockCreated:7736794},ensUniversalResolver:{address:"0x41692Ef1EA0C79E6b73077E4A67572D2BDbD7057",blockCreated:7736795}},ensTlds:[".bera"],rpcUrls:{default:{http:["https://bartio.rpc.berachain.com"]}},blockExplorers:{default:{name:"Berachain bArtio Beratrail",url:"https://bartio.beratrail.io"}},testnet:!0}),B8=ht({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),C8=ht({id:97,name:"BNB Smart Chain Testnet",nativeCurrency:{decimals:18,name:"BNB",symbol:"tBNB"},rpcUrls:{default:{http:["https://data-seed-prebsc-1-s1.bnbchain.org:8545"]}},blockExplorers:{default:{name:"BscScan",url:"https://testnet.bscscan.com",apiUrl:"https://api-testnet.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:17422483}},testnet:!0}),N8=ht({id:5115,name:"Citrea Testnet",nativeCurrency:{name:"cBTC",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.testnet.citrea.xyz",apiUrl:"https://explorer.testnet.citrea.xyz/api"}},testnet:!0}),R8=ht({id:1116,name:"Core Dao",nativeCurrency:{decimals:18,name:"Core",symbol:"CORE"},rpcUrls:{default:{http:["https://rpc.coredao.org"]}},blockExplorers:{default:{name:"CoreDao",url:"https://scan.coredao.org"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:11907934}},testnet:!1}),M8=1,j8=ht({id:21e6,name:"Corn",nativeCurrency:{decimals:18,name:"Bitcorn",symbol:"BTCN"},rpcUrls:{default:{http:["https://21000000.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"Corn Explorer",url:"https://cornscan.io",apiUrl:"https://api.routescan.io/v2/network/mainnet/evm/21000000/etherscan/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:3228}},sourceId:M8}),U8=ht({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),F8=ht({id:10143,name:"Monad Testnet",blockTime:400,nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),$8=ht({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://11155111.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:8928790}},testnet:!0}),Qa=1,L8=ht({...Li,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:1e3,rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...Li.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Qa]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Qa]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Qa]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Qa}),D8={...$8,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},i1={id:3637,name:"Botanix",nativeCurrency:{name:"Botanix",symbol:"BOTX",decimals:18},blockExplorers:{default:{name:"Botanix Explorer",url:"https://botanixscan.io/"}},rpcUrls:{default:{http:["https://rpc.botanixlabs.com/"]}}},o1={id:998,name:"Hyperliquid EVM Testnet",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://testnet.purrsec.com/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid-testnet.xyz/evm"]}}},a1={id:999,name:"HyperEVM",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://hyperscan.gas.zip/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}}},c1={id:8150,name:"Alpen Network",nativeCurrency:{name:"Signet bitcoin",symbol:"sBTC",decimals:18},blockExplorers:{default:{name:"Alpen Explorer",url:"https://explorer.pectra-testnet.alpenlabs.io"}},rpcUrls:{default:{http:["https://rpc.pectra-testnet.alpenlabs.io"]}}},H8={id:143,name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},blockExplorers:{default:{name:"Monad Explorer",url:"https://monadvision.com/"}},rpcUrls:{default:{http:["https://rpc1.monad.xyz"]}}},gu={ethereum:U8,arbitrum:_8,ethereum_sepolia:D8,arbitrum_sepolia:P8,ethereum_localnet:V.EthereumLocalnet,arbitrum_localnet:V.ArbitrumLocalnet,base_sepolia:s1,base:n1,bera_testnet:I8,citrea_testnet:N8,core:R8,bera:O8,monad:H8,monad_testnet:F8,hyperliquid_testnet:o1,hyperliquid:a1,unichain:L8,corn:j8,botanix:i1,bnbchain:B8,bnbchain_testnet:C8,alpen_testnet:c1,hypercore:{},hypercore_testnet:{}},u1=t=>{for(const[e,r]of Object.entries(gu))if(r.id===t)return e;return null},Sd=async(t,e)=>{var s,i,o;const r=gu[t],n=await e.getChainId();if(r)try{if(r.id===n)return E.Ok({message:"Already on the network",walletClient:e});await e.switchChain({id:r.id});const a=nl({account:e.account,chain:r,transport:w0(e.transport)});return E.Ok({message:"Switched chain",walletClient:a})}catch(a){if(z8(a))if(a.code===4902||a.code===-32603)try{await e.addChain({chain:r});const c=nl({account:e.account,chain:r,transport:w0(e.transport)});return E.Ok({message:"Added network",walletClient:c})}catch{return E.Err("Failed to add network")}else if((i=(s=a.body)==null?void 0:s.method)!=null&&i.includes("wallet_switchEthereumChain")||(o=a.message)!=null&&o.includes("wallet_switchEthereumChain")){const c=nl({account:e.account,chain:r,transport:vw()});return E.Ok({message:"Added network",walletClient:c})}else return E.Err("Failed to switch network");else return E.Err("Failed to switch network")}else return E.Err("Chain not supported")},z8=t=>typeof t=="object"&&t!=null&&("code"in t||"message"in t||"body"in t);class l1{constructor(e,r,n){this.wallet=r,this.auth=n,this.url=e instanceof E.Url?e:new E.Url(e),this.relayer=new ti(this.auth,this.url)}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(e){if(V.isEvmOrderResponse(e))return this.initiateFromAPI(e);if(!this.wallet.account)return E.Err("No account found");if(!V.isEVM(e.source_swap.chain))return E.Err("Not an EVM chain");if(this.wallet.account.address.toLowerCase()!==e.source_swap.initiator.toLowerCase())return E.Err("Account address and order initiator mismatch");const r=e.source_swap.chain,n=await Sd(r,this.wallet);if(!n.ok)return E.Err(n.error);this.wallet=n.val.walletClient;const{source_swap:s}=e;if(!s.amount||!s.timelock||!s.redeemer||!s.secret_hash)return E.Err("Invalid order");const i=await ji(s.asset,this.url);if(!i.ok)return E.Err(i.error);const o=V.ChainAsset.fromString(s.asset),a={redeemer:E.with0x(s.redeemer),timelock:BigInt(s.timelock),amount:BigInt(s.amount),secretHash:E.with0x(s.secret_hash)};return V.isEvmNativeToken(o.chain,o.symbol)?b8(this.wallet,{...a,htlc:i.val.htlcAddress}):g8(this.wallet,this.url,this.auth,{...a,htlc:i.val.htlcAddress,token:i.val.tokenAddress,orderId:e.order_id})}async initiateFromAPI(e){const r=u1(e.initiate_transaction.chain_id);if(!r)return E.Err("Unsupported chain");const n=await Sd(r,this.wallet);if(!n.ok)return E.Err(n.error);if(this.wallet=n.val.walletClient,!this.wallet.account)return E.Err("No account found");if(!e.typed_data){const o=e.initiate_transaction,a=await this.wallet.sendTransaction({account:this.wallet.account,chain:this.wallet.chain,to:E.with0x(o.to),value:BigInt(o.value),data:E.with0x(o.data),gas:BigInt(o.gas_limit)}),c=await E.waitForTransactionReceipt(this.wallet,a);return c.ok?!c.val||c.val.status!=="success"?E.Err("Native initiate transaction failed"):E.Ok(a):E.Err(c.error)}if(e.approval_transaction){const o=await w8(this.wallet,e.approval_transaction);if(o.error)return E.Err(`Approval failed: ${o.error}`);console.log("Approval transaction completed:",o.val)}const s=await this.wallet.signTypedData({account:this.wallet.account,...e.typed_data}),i=await kw({wallet:this.wallet,attempt:()=>this.relayer.initiate(e.order_id,s)});if(i)return E.Ok(i);try{const o=Ah({address:E.with0x(e.initiate_transaction.to),abi:r1,client:this.wallet}),a=e.typed_data.message,c=await o.write.initiate([E.with0x(a.redeemer),BigInt(a.timelock),BigInt(a.amount),E.with0x(a.secretHash)],{account:this.wallet.account,chain:this.wallet.chain}),u=await E.waitForTransactionReceipt(this.wallet,c);return u.ok?!u.val||u.val.status!=="success"?E.Err("Failed to initiate via contract"):E.Ok(c):E.Err(u.error)}catch(o){return Lh(o)?E.Ok("already initiated"):E.Err(`Failed to initiate via contract: ${String(o)}`)}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);if(n.error)return E.Err(n.error);try{const s=await this.relayer.redeem(e.order_id,r);if(s.error)return E.Err(s.error);const i=gu[e.destination_swap.chain],a=await Ox({chain:i,transport:vw()}).waitForTransactionReceipt({hash:s.val,confirmations:1,timeout:3e5});return a&&a.status==="success"?E.Ok(s.val?s.val:"Redeem hash not found"):E.Err("Redeem failed: Transaction receipt not successful")}catch(s){return E.Err(String(s))}}async refund(){return E.Err("Refund not supported")}}const f1=[{name:"LockingContract",type:"impl",interface_name:"src::mintable_lock_interface::ILockingContract"},{name:"src::mintable_lock_interface::ILockingContract",type:"interface",items:[{name:"set_locking_contract",type:"function",inputs:[{name:"locking_contract",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"get_locking_contract",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"}]},{name:"LockAndDelegate",type:"impl",interface_name:"src::mintable_lock_interface::ILockAndDelegate"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"src::mintable_lock_interface::ILockAndDelegate",type:"interface",items:[{name:"lock_and_delegate",type:"function",inputs:[{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"lock_and_delegate_by_sig",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"},{name:"nonce",type:"core::felt252"},{name:"expiry",type:"core::integer::u64"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"MintableToken",type:"impl",interface_name:"src::mintable_token_interface::IMintableToken"},{name:"src::mintable_token_interface::IMintableToken",type:"interface",items:[{name:"permissioned_mint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissioned_burn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"MintableTokenCamelImpl",type:"impl",interface_name:"src::mintable_token_interface::IMintableTokenCamel"},{name:"src::mintable_token_interface::IMintableTokenCamel",type:"interface",items:[{name:"permissionedMint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissionedBurn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"Replaceable",type:"impl",interface_name:"src::replaceability_interface::IReplaceable"},{name:"core::array::Span::<core::felt252>",type:"struct",members:[{name:"snapshot",type:"@core::array::Array::<core::felt252>"}]},{name:"src::replaceability_interface::EICData",type:"struct",members:[{name:"eic_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_init_data",type:"core::array::Span::<core::felt252>"}]},{name:"core::option::Option::<src::replaceability_interface::EICData>",type:"enum",variants:[{name:"Some",type:"src::replaceability_interface::EICData"},{name:"None",type:"()"}]},{name:"core::bool",type:"enum",variants:[{name:"False",type:"()"},{name:"True",type:"()"}]},{name:"src::replaceability_interface::ImplementationData",type:"struct",members:[{name:"impl_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_data",type:"core::option::Option::<src::replaceability_interface::EICData>"},{name:"final",type:"core::bool"}]},{name:"src::replaceability_interface::IReplaceable",type:"interface",items:[{name:"get_upgrade_delay",type:"function",inputs:[],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"get_impl_activation_time",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"add_new_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"remove_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"replace_to",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"}]},{name:"AccessControlImplExternal",type:"impl",interface_name:"src::access_control_interface::IAccessControl"},{name:"src::access_control_interface::IAccessControl",type:"interface",items:[{name:"has_role",type:"function",inputs:[{name:"role",type:"core::felt252"},{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"get_role_admin",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[{type:"core::felt252"}],state_mutability:"view"}]},{name:"RolesImpl",type:"impl",interface_name:"src::roles_interface::IMinimalRoles"},{name:"src::roles_interface::IMinimalRoles",type:"interface",items:[{name:"is_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"is_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"register_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"register_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"renounce",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[],state_mutability:"external"}]},{name:"ERC20Impl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20"},{name:"openzeppelin::token::erc20::interface::IERC20",type:"interface",items:[{name:"name",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"symbol",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"decimals",type:"function",inputs:[],outputs:[{type:"core::integer::u8"}],state_mutability:"view"},{name:"total_supply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balance_of",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"allowance",type:"function",inputs:[{name:"owner",type:"core::starknet::contract_address::ContractAddress"},{name:"spender",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transfer",type:"function",inputs:[{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"transfer_from",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"approve",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"ERC20CamelOnlyImpl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20CamelOnly"},{name:"openzeppelin::token::erc20::interface::IERC20CamelOnly",type:"interface",items:[{name:"totalSupply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balanceOf",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transferFrom",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"name",type:"core::felt252"},{name:"symbol",type:"core::felt252"},{name:"decimals",type:"core::integer::u8"},{name:"initial_supply",type:"core::integer::u256"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"permitted_minter",type:"core::starknet::contract_address::ContractAddress"},{name:"provisional_governance_admin",type:"core::starknet::contract_address::ContractAddress"},{name:"upgrade_delay",type:"core::integer::u64"}]},{name:"increase_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"added_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decrease_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtracted_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"increaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"addedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decreaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtractedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Transfer",type:"event",members:[{kind:"data",name:"from",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"to",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Approval",type:"event",members:[{kind:"data",name:"owner",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"spender",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationAdded",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationRemoved",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationReplaced",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationFinalized",type:"event",members:[{kind:"data",name:"impl_hash",type:"core::starknet::class_hash::ClassHash"}]},{kind:"struct",name:"src::access_control_interface::RoleGranted",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleRevoked",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleAdminChanged",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"previous_admin_role",type:"core::felt252"},{kind:"data",name:"new_admin_role",type:"core::felt252"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"enum",name:"src::strk::erc20_lockable::ERC20Lockable::Event",type:"event",variants:[{kind:"nested",name:"Transfer",type:"src::strk::erc20_lockable::ERC20Lockable::Transfer"},{kind:"nested",name:"Approval",type:"src::strk::erc20_lockable::ERC20Lockable::Approval"},{kind:"nested",name:"ImplementationAdded",type:"src::replaceability_interface::ImplementationAdded"},{kind:"nested",name:"ImplementationRemoved",type:"src::replaceability_interface::ImplementationRemoved"},{kind:"nested",name:"ImplementationReplaced",type:"src::replaceability_interface::ImplementationReplaced"},{kind:"nested",name:"ImplementationFinalized",type:"src::replaceability_interface::ImplementationFinalized"},{kind:"nested",name:"RoleGranted",type:"src::access_control_interface::RoleGranted"},{kind:"nested",name:"RoleRevoked",type:"src::access_control_interface::RoleRevoked"},{kind:"nested",name:"RoleAdminChanged",type:"src::access_control_interface::RoleAdminChanged"},{kind:"nested",name:"GovernanceAdminAdded",type:"src::roles_interface::GovernanceAdminAdded"},{kind:"nested",name:"GovernanceAdminRemoved",type:"src::roles_interface::GovernanceAdminRemoved"},{kind:"nested",name:"UpgradeGovernorAdded",type:"src::roles_interface::UpgradeGovernorAdded"},{kind:"nested",name:"UpgradeGovernorRemoved",type:"src::roles_interface::UpgradeGovernorRemoved"}]}],d1=async(t,e,r,n,s)=>{try{const i=await So(t.address,e,r,s);if(!i.ok)return E.Err(i.error);if(i.val>=n)return E.Ok("Allowance already approved");const a=Xe.cairo.uint256(BigInt(n)),c=await t.execute([{contractAddress:E.with0x(e),entrypoint:"approve",calldata:[E.with0x(r),a.low,a.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[Xe.TransactionExecutionStatus.SUCCEEDED]}),await E.sleep(2e3);for(let u=0;u<20;u++){const l=await So(t.address,e,r,s);if(!l.ok)return E.Err(l.error);if(l.val>=n)return E.Ok(c.transaction_hash);await E.sleep(2e3);let f=0n;for(let h=0;h<20;h++){const d=await So(t.address,e,r,s);if(!d.ok)return E.Err(d.error);if(f=d.val,f>=n)break;await E.sleep(2e3)}return f<n?E.Err("Allowance not approved"):E.Ok(c.transaction_hash)}return E.Err("Allowance not approved after transaction.")}catch(i){return E.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},So=async(t,e,r,n)=>{try{const i=await new Xe.Contract({abi:f1,address:E.with0x(e),providerOrAccount:n}).call("allowance",[E.with0x(t),E.with0x(r)]);return E.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return E.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},h1=async(t,e,r,n,s)=>{const i=await So(t,e,r,n);return i.ok?E.Ok(i.val>=s):E.Err(i.error)},p1=[{type:"impl",name:"HTLC",interface_name:"starknet_htlc::interface::IHTLC"},{type:"struct",name:"core::integer::u256",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{type:"struct",name:"starknet_htlc::htlc::HTLC::Order",members:[{name:"fulfilled_at",type:"core::integer::u128"},{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"initiated_at",type:"core::integer::u128"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"}]},{type:"interface",name:"starknet_htlc::interface::IHTLC",items:[{type:"function",name:"token",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{type:"function",name:"get_order",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[{type:"starknet_htlc::htlc::HTLC::Order"}],state_mutability:"view"},{type:"function",name:"initiate",inputs:[{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_with_destination_data",inputs:[{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"destination_data",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_on_behalf",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_on_behalf_with_destination_data",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"destination_data",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_with_signature",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"redeem",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"[core::integer::u32; 8]"}],outputs:[],state_mutability:"external"},{type:"function",name:"refund",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{type:"function",name:"instant_refund",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{type:"constructor",name:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{type:"event",name:"starknet_htlc::interface::events::Initiated",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"amount",type:"core::integer::u256",kind:"data"}]},{type:"event",name:"starknet_htlc::interface::events::Redeemed",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"secret",type:"[core::integer::u32; 8]",kind:"data"}]},{type:"event",name:"starknet_htlc::interface::events::Refunded",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"}]},{type:"event",name:"starknet_htlc::interface::events::InitiatedWithDestinationData",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"amount",type:"core::integer::u256",kind:"data"},{name:"destination_data",type:"core::array::Array::<core::felt252>",kind:"data"}]},{type:"event",name:"starknet_htlc::htlc::HTLC::Event",kind:"enum",variants:[{name:"Initiated",type:"starknet_htlc::interface::events::Initiated",kind:"nested"},{name:"Redeemed",type:"starknet_htlc::interface::events::Redeemed",kind:"nested"},{name:"Refunded",type:"starknet_htlc::interface::events::Refunded",kind:"nested"},{name:"InitiatedWithDestinationData",type:"starknet_htlc::interface::events::InitiatedWithDestinationData",kind:"nested"}]}],V8={StarknetDomain:[{name:"name",type:"shortstring"},{name:"version",type:"shortstring"},{name:"chainId",type:"shortstring"},{name:"revision",type:"shortstring"}],Initiate:[{name:"redeemer",type:"ContractAddress"},{name:"amount",type:"u256"},{name:"timelock",type:"u128"},{name:"secretHash",type:"u128*"},{name:"verifyingContract",type:"ContractAddress"}]};class y1{constructor(e,r,n,s,i){this.url=e instanceof E.Url?e:new E.Url(e),this.starknetProvider=new Xe.RpcProvider({nodeUrl:i||Qo[n].nodeUrl}),this.account=r,this.chainId=Qo[n].chainId,this.auth=s,this.relayer=new ti(this.auth,this.url)}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(e){if(V.isStarknetOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.account.address)return E.Err("No account address");const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!s||!n||!r.secret_hash||!r.timelock)return E.Err("Invalid order");const i=await ji(r.asset,this.url);if(!i.ok)return E.Err(i.error);try{const o=new Xe.Contract({providerOrAccount:this.starknetProvider,abi:p1,address:i.val.htlcAddress}),a=await(o==null?void 0:o.token()),c=Xe.num.toHex(a),u=await h1(this.account.address,c,i.val.htlcAddress,this.starknetProvider,BigInt(r.amount));return u.error?E.Err(u.error):u.val?this.initiateRelay(e):this.approveAndInitiate(c,e)}catch(o){return E.Err(String(o))}}async approveAndInitiate(e,r){const{source_swap:n}=r,{redeemer:s,amount:i}=n,{secret_hash:o,timelock:a}=n,c=n.asset;try{const u=Xe.cairo.uint256(BigInt(i)),l={contractAddress:E.with0x(e),entrypoint:"approve",calldata:[c,u.low,u.high]},f=Xe.cairo.uint256(i),h=E.hexToU128Array(o),d={contractAddress:E.with0x(c),entrypoint:"initiate",calldata:[s,a.toString(),f.low.toString(),f.high.toString(),...h.map(m=>m.toString())]},p=await this.account.execute([l,d]);return await this.starknetProvider.waitForTransaction(p.transaction_hash,{retryInterval:2e3,successStates:[Xe.TransactionExecutionStatus.SUCCEEDED]}),E.Ok(p.transaction_hash)}catch(u){return E.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(e){const{source_swap:r}=e,n=await ji(r.asset,this.url);if(!n.ok)return E.Err(n.error);const{redeemer:s,amount:i}=r;if(!r.secret_hash)return E.Err("Invalid order: secret_hash is undefined");const o=E.with0x(r.secret_hash),a={name:"HTLC",version:Xe.shortString.encodeShortString("2"),chainId:this.chainId,revision:Xe.TypedDataRevision.ACTIVE},c=E.hexToU128Array(o),u={domain:a,primaryType:"Initiate",types:V8,message:{redeemer:s,amount:Xe.cairo.uint256(i),timelock:e.source_swap.timelock.toString(),secretHash:c.map(l=>l.toString()),verifyingContract:n.val.htlcAddress}};try{const l=await this.account.signMessage(u),f=E0(l);if(f.error||!f.val)return E.Err(f.error||"Invalid signature");const h=await this.relayer.initiate(e.order_id,f.val);return h.ok?E.Ok(h.val):E.Err(h.error)}catch(l){return E.Err(`Failed to initiate relayer: ${String(l)}`)}}async redeem(e,r){try{const n=await this.relayer.redeem(e.order_id,r);return n.error?E.Err(n.error):E.Ok(n.val)}catch(n){return E.Err(String(n))}}async executeApprovalTransaction(e){if(!this.account.address)return E.Err("No account address");if(!e.approval_transaction)return E.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.account.execute([{contractAddress:E.with0x(r.to),entrypoint:"approve",calldata:r.calldata}]);return await this.starknetProvider.waitForTransaction(n.transaction_hash,{retryInterval:2e3,successStates:[Xe.TransactionExecutionStatus.SUCCEEDED]}),E.Ok(n.transaction_hash)}catch(r){return console.error("executeApprovalTransaction error:",r),E.Err("Failed to execute approval: "+(r instanceof Error&&(r==null?void 0:r.message)||String(r)))}}async initiateWithCreateOrderResponse(e){const r=await this.auth.getAuthHeaders();if(!r.ok)return E.Err(r.error);if(!this.account.address)return E.Err("No account address");const n=await this.executeApprovalTransaction(e);if(n.error)return E.Err(n.error);const{typed_data:s}=e;if(s===null){const c=e.initiate_transaction;if(!c)return E.Err("No initiate_transaction found for native initiate");const u=await this.account.execute([{contractAddress:E.with0x(c.to),entrypoint:"initiate",calldata:c.calldata}]);return await this.starknetProvider.waitForTransaction(u.transaction_hash,{retryInterval:2e3,successStates:[Xe.TransactionExecutionStatus.SUCCEEDED]}),E.Ok(u.transaction_hash)}const i=await this.account.signMessage(s),o=E0(i);if(o.error)return E.Err(o.error);const a=await E.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:Array.isArray(o.val)?o.val.join(","):o.val}),headers:{...r.val,"Content-Type":"application/json"}});return a.error?E.Err(a.error):E.Ok(a.result)}async refund(){return E.Err("Refund is taken care of by the relayer")}}const G8="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",q8={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},W8=[{name:"initiate",docs:["Initiates the atomic swap. Funds are transferred from the initiator to the token vault.","As such, the initiator's signature is required for this instruction.","A sponsor may be involved, who pays PDA rent and transaction fees in SOL, allowing for the","initiator to participate without holding SOL. As such, the sponsor must also sign this transaction.","`swap_amount` represents the quantity of tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000.","`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed.","`destination_data` can hold optional information regarding the destination chain","in the atomic swap, to be emitted in the logs as-is."],discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"identity_pda",docs:["the token transfers of the `token_vault` PDA.","This PDA will be created during the first most invocation of the `initiate()` function","using the `init_if_needed` attribute, and be reused for all succeeding instructions."],writable:!0,pda:{seeds:[]}},{name:"swap_data",docs:["A PDA that maintains the on-chain state of the atomic swap throughout its lifecycle.","The choice of seeds ensure that any swap with equal `initiator` and","`secret_hash` wont be created until an existing one completes.","This PDA will be deleted upon completion of the swap."],writable:!0,pda:{seeds:[{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"token_vault",docs:["A permanent PDA that is controlled by the program through the `identity_pda`, as implied",'by the value of the `authority` field below. As such, it serves as the "vault" by escrowing tokens',"of type `mint` for the atomic swap.","It is intended to be reused for all swaps involving the same mint.","Just like `identity_pda`, it will be created during the first most invocation of `initiate()`","of every distinct mint using the `init_if_needed` attribute."],writable:!0,pda:{seeds:[{kind:"account",path:"mint"}]}},{name:"initiator",docs:["The initiator of the atomic swap. They must sign this transaction."],signer:!0},{name:"initiator_token_account",docs:["The token account of the initiator"],writable:!0},{name:"mint",docs:["The mint of the tokens involved in this swap. As this is a parameter, this program can thus be reused","for atomic swaps with different mints."]},{name:"sponsor",docs:["Any entity that pays the PDA rent.","Upon completion of the swap, the PDA rent refund resulting from the","deletion of `swap_data` will be refunded to this address."],writable:!0,signer:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"swap_amount",type:"u64"},{name:"destination_data",type:{option:"bytes"}}]},{name:"instant_refund",docs:["Funds are returned to the initiator, with the redeemer's consent.","As such, the redeemer's signature is required for this instruction.","This allows for refunds before the expiry slot."],discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"redeemer",docs:["The redeemer of the atomic swap. They must sign this transaction."],writable:!0,signer:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]},{name:"redeem",docs:["Funds are transferred to the redeemer. This instruction does not require any signatures."],discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"redeemer_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",docs:["Funds are returned to the initiator, given that no redeems have occured","and the expiry slot has been reached.","This instruction does not require any signatures."],discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]}],K8=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],X8=[{name:"Initiated",discriminator:[6,108,212,91,67,60,207,221]},{name:"InstantRefunded",discriminator:[220,50,18,207,183,232,218,25]},{name:"Redeemed",discriminator:[14,29,183,71,31,165,107,38]},{name:"Refunded",discriminator:[35,103,149,246,196,123,221,99]}],Y8=[{code:6e3,name:"InvalidRedeemer",msg:"The provider redeemer is not the original redeemer of this swap"},{code:6001,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash of this swap"},{code:6002,name:"InvalidSponsor",msg:"The provided sponsor is not the original sponsor of this swap"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],J8=[{name:"Initiated",docs:["Represents the initiated state of the swap where the initiator has deposited funds into the vault"],type:{kind:"struct",fields:[{name:"swap_amount",docs:["The quantity of tokens transferred through this atomic swap in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals will be represented as 1,000,000.'],type:"u64"},{name:"expires_in_slots",docs:["`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",type:"pubkey"},{name:"mint",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"destination_data",docs:["Information regarding the destination chain in the atomic swap"],type:{option:"bytes"}}]}},{name:"InstantRefunded",docs:["Represents the instant refund state of the swap, where the initiator has withdrawn funds the vault","with the redeemer's consent"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",docs:["Represents the redeemed state of the swap, where the redeemer has withdrawn funds from the vault"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",docs:["Represents the refund state of the swap, where the initiator has withdrawn funds from the vault past expiry"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",docs:["Stores the state information of the atomic swap on-chain"],type:{kind:"struct",fields:[{name:"expiry_slot",docs:["The exact slot after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",docs:["The initiator of the atomic swap"],type:"pubkey"},{name:"redeemer",docs:["The redeemer of the atomic swap"],type:"pubkey"},{name:"secret_hash",docs:["The secret hash associated with the atomic swap"],type:{array:["u8",32]}},{name:"swap_amount",docs:["The quantity tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000."],type:"u64"},{name:"identity_pda_bump",docs:["The bump associated with the identity pda.","This is needed by the program to authorize token transfers via the token vault."],type:"u8"},{name:"sponsor",docs:["The entity that paid the rent fees for the creation of this PDA.","This will be referenced during the refund of the same upon closing this PDA."],type:"pubkey"}]}}],X0={address:G8,metadata:q8,instructions:W8,accounts:K8,events:X8,errors:Y8,types:J8},Z8="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",Q8={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},eP=[{name:"initiate",discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"swap_account",writable:!0,pda:{seeds:[{kind:"const",value:[115,119,97,112,95,97,99,99,111,117,110,116]},{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"initiator",docs:["Initiator must sign this transaction"],writable:!0,signer:!0},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"amount_lamports",type:"u64"},{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]},{name:"instant_refund",discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"swap_account",writable:!0},{name:"initiator",writable:!0},{name:"redeemer",docs:["Redeemer must sign this transaction"],signer:!0}],args:[]},{name:"redeem",discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"swap_account",writable:!0},{name:"initiator",docs:["This is included here for the PDA rent refund using the `close` attribute above"],writable:!0},{name:"redeemer",writable:!0}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"swap_account",writable:!0},{name:"initiator",writable:!0}],args:[]}],tP=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],rP=[{name:"Initiated",discriminator:[6,108,212,91,67,60,207,221]},{name:"InstantRefunded",discriminator:[220,50,18,207,183,232,218,25]},{name:"Redeemed",discriminator:[14,29,183,71,31,165,107,38]},{name:"Refunded",discriminator:[35,103,149,246,196,123,221,99]}],nP=[{code:6e3,name:"InvalidInitiator",msg:"The provided initiator is not the original initiator of this swap account"},{code:6001,name:"InvalidRedeemer",msg:"The provided redeemer is not the original redeemer of this swap amount"},{code:6002,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash in the swap account"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],sP=[{name:"Initiated",type:{kind:"struct",fields:[{name:"amount_lamports",type:"u64"},{name:"expires_in_slots",type:"u64"},{name:"initiator",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"InstantRefunded",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",type:{kind:"struct",fields:[{name:"amount_lamports",type:"u64"},{name:"expiry_slot",type:"u64"},{name:"initiator",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}}],Ad={address:Z8,metadata:Q8,instructions:eP,accounts:tP,events:rP,errors:nP,types:sP};var En={},wu={};Object.defineProperty(wu,"__esModule",{value:!0});wu.encode=iP;wu.decode=oP;const Y0=Zs;function iP(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"0x")}function oP(t){t.indexOf("0x")===0&&(t=t.substr(2)),t.length%2===1&&(t="0"+t);let e=t.match(/.{2}/g);return e===null?Y0.Buffer.from([]):Y0.Buffer.from(e.map(r=>parseInt(r,16)))}var vu={},Ws={},ml;Object.defineProperty(Ws,"__esModule",{value:!0});Ws.isVersionedTransaction=Ws.isBrowser=void 0;Ws.chunks=aP;Ws.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((ml=window.process)===null||ml===void 0)&&ml.hasOwnProperty("type"));function aP(t,e){return Array.apply(0,new Array(Math.ceil(t.length/e))).map((r,n)=>t.slice(n*e,(n+1)*e))}const cP=t=>"version"in t;Ws.isVersionedTransaction=cP;var bl={},gl={},wl,J0;function m1(){return J0||(J0=1,wl=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var s=42;e[r]=s;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(e,r);if(a.value!==s||a.enumerable!==!0)return!1}return!0}),wl}var vl,Z0;function Eu(){if(Z0)return vl;Z0=1;var t=m1();return vl=function(){return t()&&!!Symbol.toStringTag},vl}var El,Q0;function b1(){return Q0||(Q0=1,El=Object),El}var Sl,ey;function uP(){return ey||(ey=1,Sl=Error),Sl}var Al,ty;function lP(){return ty||(ty=1,Al=EvalError),Al}var kl,ry;function fP(){return ry||(ry=1,kl=RangeError),kl}var xl,ny;function dP(){return ny||(ny=1,xl=ReferenceError),xl}var Tl,sy;function g1(){return sy||(sy=1,Tl=SyntaxError),Tl}var _l,iy;function Ia(){return iy||(iy=1,_l=TypeError),_l}var Pl,oy;function hP(){return oy||(oy=1,Pl=URIError),Pl}var Ol,ay;function pP(){return ay||(ay=1,Ol=Math.abs),Ol}var Il,cy;function yP(){return cy||(cy=1,Il=Math.floor),Il}var Bl,uy;function mP(){return uy||(uy=1,Bl=Math.max),Bl}var Cl,ly;function bP(){return ly||(ly=1,Cl=Math.min),Cl}var Nl,fy;function gP(){return fy||(fy=1,Nl=Math.pow),Nl}var Rl,dy;function wP(){return dy||(dy=1,Rl=Math.round),Rl}var Ml,hy;function vP(){return hy||(hy=1,Ml=Number.isNaN||function(e){return e!==e}),Ml}var jl,py;function EP(){if(py)return jl;py=1;var t=vP();return jl=function(r){return t(r)||r===0?r:r<0?-1:1},jl}var Ul,yy;function SP(){return yy||(yy=1,Ul=Object.getOwnPropertyDescriptor),Ul}var Fl,my;function Yi(){if(my)return Fl;my=1;var t=SP();if(t)try{t([],"length")}catch{t=null}return Fl=t,Fl}var $l,by;function Su(){if(by)return $l;by=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch{t=!1}return $l=t,$l}var Ll,gy;function AP(){if(gy)return Ll;gy=1;var t=typeof Symbol<"u"&&Symbol,e=m1();return Ll=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Ll}var Dl,wy;function w1(){return wy||(wy=1,Dl=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),Dl}var Hl,vy;function v1(){if(vy)return Hl;vy=1;var t=b1();return Hl=t.getPrototypeOf||null,Hl}var zl,Ey;function kP(){if(Ey)return zl;Ey=1;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,u){for(var l=[],f=0;f<c.length;f+=1)l[f]=c[f];for(var h=0;h<u.length;h+=1)l[h+c.length]=u[h];return l},i=function(c,u){for(var l=[],f=u,h=0;f<c.length;f+=1,h+=1)l[h]=c[f];return l},o=function(a,c){for(var u="",l=0;l<a.length;l+=1)u+=a[l],l+1<a.length&&(u+=c);return u};return zl=function(c){var u=this;if(typeof u!="function"||e.apply(u)!==n)throw new TypeError(t+u);for(var l=i(arguments,1),f,h=function(){if(this instanceof f){var S=u.apply(this,s(l,arguments));return Object(S)===S?S:this}return u.apply(c,s(l,arguments))},d=r(0,u.length-l.length),p=[],m=0;m<d;m++)p[m]="$"+m;if(f=Function("binder","return function ("+o(p,",")+"){ return binder.apply(this,arguments); }")(h),u.prototype){var v=function(){};v.prototype=u.prototype,f.prototype=new v,v.prototype=null}return f},zl}var Vl,Sy;function Ba(){if(Sy)return Vl;Sy=1;var t=kP();return Vl=Function.prototype.bind||t,Vl}var Gl,Ay;function Qh(){return Ay||(Ay=1,Gl=Function.prototype.call),Gl}var ql,ky;function ep(){return ky||(ky=1,ql=Function.prototype.apply),ql}var Wl,xy;function xP(){return xy||(xy=1,Wl=typeof Reflect<"u"&&Reflect&&Reflect.apply),Wl}var Kl,Ty;function E1(){if(Ty)return Kl;Ty=1;var t=Ba(),e=ep(),r=Qh(),n=xP();return Kl=n||t.call(r,e),Kl}var Xl,_y;function tp(){if(_y)return Xl;_y=1;var t=Ba(),e=Ia(),r=Qh(),n=E1();return Xl=function(i){if(i.length<1||typeof i[0]!="function")throw new e("a function is required");return n(t,r,i)},Xl}var Yl,Py;function TP(){if(Py)return Yl;Py=1;var t=tp(),e=Yi(),r;try{r=[].__proto__===Array.prototype}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="ERR_PROTO_ACCESS")throw o}var n=!!r&&e&&e(Object.prototype,"__proto__"),s=Object,i=s.getPrototypeOf;return Yl=n&&typeof n.get=="function"?t([n.get]):typeof i=="function"?function(a){return i(a==null?a:s(a))}:!1,Yl}var Jl,Oy;function rp(){if(Oy)return Jl;Oy=1;var t=w1(),e=v1(),r=TP();return Jl=t?function(s){return t(s)}:e?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return e(s)}:r?function(s){return r(s)}:null,Jl}var Zl,Iy;function S1(){if(Iy)return Zl;Iy=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=Ba();return Zl=r.call(t,e),Zl}var Ql,By;function A1(){if(By)return Ql;By=1;var t,e=b1(),r=uP(),n=lP(),s=fP(),i=dP(),o=g1(),a=Ia(),c=hP(),u=pP(),l=yP(),f=mP(),h=bP(),d=gP(),p=wP(),m=EP(),v=Function,S=function(oe){try{return v('"use strict"; return ('+oe+").constructor;")()}catch{}},T=Yi(),g=Su(),w=function(){throw new a},k=T?function(){try{return arguments.callee,w}catch{try{return T(arguments,"callee").get}catch{return w}}}():w,_=AP()(),O=rp(),B=v1(),N=w1(),$=ep(),j=Qh(),H={},G=typeof Uint8Array>"u"||!O?t:O(Uint8Array),ee={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":_&&O?O([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":H,"%AsyncGenerator%":H,"%AsyncGeneratorFunction%":H,"%AsyncIteratorPrototype%":H,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?t:Float16Array,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":H,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_&&O?O(O([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!_||!O?t:O(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":T,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!_||!O?t:O(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_&&O?O(""[Symbol.iterator]()):t,"%Symbol%":_?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":k,"%TypedArray%":G,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet,"%Function.prototype.call%":j,"%Function.prototype.apply%":$,"%Object.defineProperty%":g,"%Object.getPrototypeOf%":B,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":f,"%Math.min%":h,"%Math.pow%":d,"%Math.round%":p,"%Math.sign%":m,"%Reflect.getPrototypeOf%":N};if(O)try{null.error}catch(oe){var U=O(O(oe));ee["%Error.prototype%"]=U}var X=function oe(ie){var ye;if(ie==="%AsyncFunction%")ye=S("async function () {}");else if(ie==="%GeneratorFunction%")ye=S("function* () {}");else if(ie==="%AsyncGeneratorFunction%")ye=S("async function* () {}");else if(ie==="%AsyncGenerator%"){var me=oe("%AsyncGeneratorFunction%");me&&(ye=me.prototype)}else if(ie==="%AsyncIteratorPrototype%"){var ve=oe("%AsyncGenerator%");ve&&O&&(ye=O(ve.prototype))}return ee[ie]=ye,ye},te={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},W=Ba(),C=S1(),D=W.call(j,Array.prototype.concat),Z=W.call($,Array.prototype.splice),R=W.call(j,String.prototype.replace),F=W.call(j,String.prototype.slice),z=W.call(j,RegExp.prototype.exec),se=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ae=/\\(\\)?/g,fe=function(ie){var ye=F(ie,0,1),me=F(ie,-1);if(ye==="%"&&me!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(me==="%"&&ye!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var ve=[];return R(ie,se,function(ke,Ze,Ie,Mr){ve[ve.length]=Ie?R(Mr,ae,"$1"):Ze||ke}),ve},ue=function(ie,ye){var me=ie,ve;if(C(te,me)&&(ve=te[me],me="%"+ve[0]+"%"),C(ee,me)){var ke=ee[me];if(ke===H&&(ke=X(me)),typeof ke>"u"&&!ye)throw new a("intrinsic "+ie+" exists, but is not available. Please file an issue!");return{alias:ve,name:me,value:ke}}throw new o("intrinsic "+ie+" does not exist!")};return Ql=function(ie,ye){if(typeof ie!="string"||ie.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof ye!="boolean")throw new a('"allowMissing" argument must be a boolean');if(z(/^%?[^%]*%?$/,ie)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var me=fe(ie),ve=me.length>0?me[0]:"",ke=ue("%"+ve+"%",ye),Ze=ke.name,Ie=ke.value,Mr=!1,ms=ke.alias;ms&&(ve=ms[0],Z(me,D([0,1],ms)));for(var Y=1,jr=!0;Y<me.length;Y+=1){var vt=me[Y],Et=F(vt,0,1),Rn=F(vt,-1);if((Et==='"'||Et==="'"||Et==="`"||Rn==='"'||Rn==="'"||Rn==="`")&&Et!==Rn)throw new o("property names with quotes must have matching quotes");if((vt==="constructor"||!jr)&&(Mr=!0),ve+="."+vt,Ze="%"+ve+"%",C(ee,Ze))Ie=ee[Ze];else if(Ie!=null){if(!(vt in Ie)){if(!ye)throw new a("base intrinsic for "+ie+" exists, but the property is not available.");return}if(T&&Y+1>=me.length){var ni=T(Ie,vt);jr=!!ni,jr&&"get"in ni&&!("originalValue"in ni.get)?Ie=ni.get:Ie=Ie[vt]}else jr=C(Ie,vt),Ie=Ie[vt];jr&&!Mr&&(ee[Ze]=Ie)}}return Ie},Ql}var ef,Cy;function Ca(){if(Cy)return ef;Cy=1;var t=A1(),e=tp(),r=e([t("%String.prototype.indexOf%")]);return ef=function(s,i){var o=t(s,!!i);return typeof o=="function"&&r(s,".prototype.")>-1?e([o]):o},ef}var tf,Ny;function _P(){if(Ny)return tf;Ny=1;var t=Eu()(),e=Ca(),r=e("Object.prototype.toString"),n=function(a){return t&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:r(a)==="[object Arguments]"},s=function(a){return n(a)?!0:a!==null&&typeof a=="object"&&"length"in a&&typeof a.length=="number"&&a.length>=0&&r(a)!=="[object Array]"&&"callee"in a&&r(a.callee)==="[object Function]"},i=function(){return n(arguments)}();return n.isLegacyArguments=s,tf=i?n:s,tf}var rf,Ry;function PP(){if(Ry)return rf;Ry=1;var t=Ca(),e=Eu()(),r=S1(),n=Yi(),s;if(e){var i=t("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),s=function(h){if(!h||typeof h!="object")return!1;var d=n(h,"lastIndex"),p=d&&r(d,"value");if(!p)return!1;try{i(h,c)}catch(m){return m===o}}}else{var u=t("Object.prototype.toString"),l="[object RegExp]";s=function(h){return!h||typeof h!="object"&&typeof h!="function"?!1:u(h)===l}}return rf=s,rf}var nf,My;function OP(){if(My)return nf;My=1;var t=Ca(),e=PP(),r=t("RegExp.prototype.exec"),n=Ia();return nf=function(i){if(!e(i))throw new n("`regex` must be a RegExp");return function(a){return r(i,a)!==null}},nf}var sf,jy;function IP(){if(jy)return sf;jy=1;const t=(function*(){}).constructor;return sf=()=>t,sf}var of,Uy;function BP(){if(Uy)return of;Uy=1;var t=Ca(),e=OP(),r=e(/^\s*(?:function)?\*/),n=Eu()(),s=rp(),i=t("Object.prototype.toString"),o=t("Function.prototype.toString"),a=IP();return of=function(u){if(typeof u!="function")return!1;if(r(o(u)))return!0;if(!n){var l=i(u);return l==="[object GeneratorFunction]"}if(!s)return!1;var f=a();return f&&s(u)===f.prototype},of}var af,Fy;function CP(){if(Fy)return af;Fy=1;var t=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},e(function(){throw 42},null,r)}catch(T){T!==n&&(e=null)}else e=null;var s=/^\s*class\b/,i=function(g){try{var w=t.call(g);return s.test(w)}catch{return!1}},o=function(g){try{return i(g)?!1:(t.call(g),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",u="[object Function]",l="[object GeneratorFunction]",f="[object HTMLAllCollection]",h="[object HTML document.all class]",d="[object HTMLCollection]",p=typeof Symbol=="function"&&!!Symbol.toStringTag,m=!(0 in[,]),v=function(){return!1};if(typeof document=="object"){var S=document.all;a.call(S)===a.call(document.all)&&(v=function(g){if((m||!g)&&(typeof g>"u"||typeof g=="object"))try{var w=a.call(g);return(w===f||w===h||w===d||w===c)&&g("")==null}catch{}return!1})}return af=e?function(g){if(v(g))return!0;if(!g||typeof g!="function"&&typeof g!="object")return!1;try{e(g,null,r)}catch(w){if(w!==n)return!1}return!i(g)&&o(g)}:function(g){if(v(g))return!0;if(!g||typeof g!="function"&&typeof g!="object")return!1;if(p)return o(g);if(i(g))return!1;var w=a.call(g);return w!==u&&w!==l&&!/^\[object HTML/.test(w)?!1:o(g)},af}var cf,$y;function NP(){if($y)return cf;$y=1;var t=CP(),e=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,u,l){for(var f=0,h=c.length;f<h;f++)r.call(c,f)&&(l==null?u(c[f],f,c):u.call(l,c[f],f,c))},s=function(c,u,l){for(var f=0,h=c.length;f<h;f++)l==null?u(c.charAt(f),f,c):u.call(l,c.charAt(f),f,c)},i=function(c,u,l){for(var f in c)r.call(c,f)&&(l==null?u(c[f],f,c):u.call(l,c[f],f,c))};function o(a){return e.call(a)==="[object Array]"}return cf=function(c,u,l){if(!t(u))throw new TypeError("iterator must be a function");var f;arguments.length>=3&&(f=l),o(c)?n(c,u,f):typeof c=="string"?s(c,u,f):i(c,u,f)},cf}var uf,Ly;function RP(){return Ly||(Ly=1,uf=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),uf}var lf,Dy;function MP(){if(Dy)return lf;Dy=1;var t=RP(),e=typeof globalThis>"u"?Br:globalThis;return lf=function(){for(var n=[],s=0;s<t.length;s++)typeof e[t[s]]=="function"&&(n[n.length]=t[s]);return n},lf}var ff={exports:{}},df,Hy;function jP(){if(Hy)return df;Hy=1;var t=Su(),e=g1(),r=Ia(),n=Yi();return df=function(i,o,a){if(!i||typeof i!="object"&&typeof i!="function")throw new r("`obj` must be an object or a function`");if(typeof o!="string"&&typeof o!="symbol")throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var c=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,f=arguments.length>6?arguments[6]:!1,h=!!n&&n(i,o);if(t)t(i,o,{configurable:l===null&&h?h.configurable:!l,enumerable:c===null&&h?h.enumerable:!c,value:a,writable:u===null&&h?h.writable:!u});else if(f||!c&&!u&&!l)i[o]=a;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},df}var hf,zy;function UP(){if(zy)return hf;zy=1;var t=Su(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},hf=e,hf}var pf,Vy;function FP(){if(Vy)return pf;Vy=1;var t=A1(),e=jP(),r=UP()(),n=Yi(),s=Ia(),i=t("%Math.floor%");return pf=function(a,c){if(typeof a!="function")throw new s("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||i(c)!==c)throw new s("`length` must be a positive 32-bit integer");var u=arguments.length>2&&!!arguments[2],l=!0,f=!0;if("length"in a&&n){var h=n(a,"length");h&&!h.configurable&&(l=!1),h&&!h.writable&&(f=!1)}return(l||f||!u)&&(r?e(a,"length",c,!0,!0):e(a,"length",c)),a},pf}var yf,Gy;function $P(){if(Gy)return yf;Gy=1;var t=Ba(),e=ep(),r=E1();return yf=function(){return r(t,e,arguments)},yf}var qy;function LP(){return qy||(qy=1,function(t){var e=FP(),r=Su(),n=tp(),s=$P();t.exports=function(o){var a=n(arguments),c=o.length-(arguments.length-1);return e(a,1+(c>0?c:0),!0)},r?r(t.exports,"apply",{value:s}):t.exports.apply=s}(ff)),ff.exports}var mf,Wy;function k1(){if(Wy)return mf;Wy=1;var t=NP(),e=MP(),r=LP(),n=Ca(),s=Yi(),i=rp(),o=n("Object.prototype.toString"),a=Eu()(),c=typeof globalThis>"u"?Br:globalThis,u=e(),l=n("String.prototype.slice"),f=n("Array.prototype.indexOf",!0)||function(v,S){for(var T=0;T<v.length;T+=1)if(v[T]===S)return T;return-1},h={__proto__:null};a&&s&&i?t(u,function(m){var v=new c[m];if(Symbol.toStringTag in v&&i){var S=i(v),T=s(S,Symbol.toStringTag);if(!T&&S){var g=i(S);T=s(g,Symbol.toStringTag)}h["$"+m]=r(T.get)}}):t(u,function(m){var v=new c[m],S=v.slice||v.set;S&&(h["$"+m]=r(S))});var d=function(v){var S=!1;return t(h,function(T,g){if(!S)try{"$"+T(v)===g&&(S=l(g,1))}catch{}}),S},p=function(v){var S=!1;return t(h,function(T,g){if(!S)try{T(v),S=l(g,1)}catch{}}),S};return mf=function(v){if(!v||typeof v!="object")return!1;if(!a){var S=l(o(v),8,-1);return f(u,S)>-1?S:S!=="Object"?!1:p(v)}return s?d(v):null},mf}var bf,Ky;function DP(){if(Ky)return bf;Ky=1;var t=k1();return bf=function(r){return!!t(r)},bf}var Xy;function HP(){return Xy||(Xy=1,function(t){var e=_P(),r=BP(),n=k1(),s=DP();function i(Y){return Y.call.bind(Y)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=i(Object.prototype.toString),u=i(Number.prototype.valueOf),l=i(String.prototype.valueOf),f=i(Boolean.prototype.valueOf);if(o)var h=i(BigInt.prototype.valueOf);if(a)var d=i(Symbol.prototype.valueOf);function p(Y,jr){if(typeof Y!="object")return!1;try{return jr(Y),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=s;function m(Y){return typeof Promise<"u"&&Y instanceof Promise||Y!==null&&typeof Y=="object"&&typeof Y.then=="function"&&typeof Y.catch=="function"}t.isPromise=m;function v(Y){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(Y):s(Y)||F(Y)}t.isArrayBufferView=v;function S(Y){return n(Y)==="Uint8Array"}t.isUint8Array=S;function T(Y){return n(Y)==="Uint8ClampedArray"}t.isUint8ClampedArray=T;function g(Y){return n(Y)==="Uint16Array"}t.isUint16Array=g;function w(Y){return n(Y)==="Uint32Array"}t.isUint32Array=w;function k(Y){return n(Y)==="Int8Array"}t.isInt8Array=k;function _(Y){return n(Y)==="Int16Array"}t.isInt16Array=_;function O(Y){return n(Y)==="Int32Array"}t.isInt32Array=O;function B(Y){return n(Y)==="Float32Array"}t.isFloat32Array=B;function N(Y){return n(Y)==="Float64Array"}t.isFloat64Array=N;function $(Y){return n(Y)==="BigInt64Array"}t.isBigInt64Array=$;function j(Y){return n(Y)==="BigUint64Array"}t.isBigUint64Array=j;function H(Y){return c(Y)==="[object Map]"}H.working=typeof Map<"u"&&H(new Map);function G(Y){return typeof Map>"u"?!1:H.working?H(Y):Y instanceof Map}t.isMap=G;function ee(Y){return c(Y)==="[object Set]"}ee.working=typeof Set<"u"&&ee(new Set);function U(Y){return typeof Set>"u"?!1:ee.working?ee(Y):Y instanceof Set}t.isSet=U;function X(Y){return c(Y)==="[object WeakMap]"}X.working=typeof WeakMap<"u"&&X(new WeakMap);function te(Y){return typeof WeakMap>"u"?!1:X.working?X(Y):Y instanceof WeakMap}t.isWeakMap=te;function W(Y){return c(Y)==="[object WeakSet]"}W.working=typeof WeakSet<"u"&&W(new WeakSet);function C(Y){return W(Y)}t.isWeakSet=C;function D(Y){return c(Y)==="[object ArrayBuffer]"}D.working=typeof ArrayBuffer<"u"&&D(new ArrayBuffer);function Z(Y){return typeof ArrayBuffer>"u"?!1:D.working?D(Y):Y instanceof ArrayBuffer}t.isArrayBuffer=Z;function R(Y){return c(Y)==="[object DataView]"}R.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&R(new DataView(new ArrayBuffer(1),0,1));function F(Y){return typeof DataView>"u"?!1:R.working?R(Y):Y instanceof DataView}t.isDataView=F;var z=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function se(Y){return c(Y)==="[object SharedArrayBuffer]"}function ae(Y){return typeof z>"u"?!1:(typeof se.working>"u"&&(se.working=se(new z)),se.working?se(Y):Y instanceof z)}t.isSharedArrayBuffer=ae;function fe(Y){return c(Y)==="[object AsyncFunction]"}t.isAsyncFunction=fe;function ue(Y){return c(Y)==="[object Map Iterator]"}t.isMapIterator=ue;function oe(Y){return c(Y)==="[object Set Iterator]"}t.isSetIterator=oe;function ie(Y){return c(Y)==="[object Generator]"}t.isGeneratorObject=ie;function ye(Y){return c(Y)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=ye;function me(Y){return p(Y,u)}t.isNumberObject=me;function ve(Y){return p(Y,l)}t.isStringObject=ve;function ke(Y){return p(Y,f)}t.isBooleanObject=ke;function Ze(Y){return o&&p(Y,h)}t.isBigIntObject=Ze;function Ie(Y){return a&&p(Y,d)}t.isSymbolObject=Ie;function Mr(Y){return me(Y)||ve(Y)||ke(Y)||Ze(Y)||Ie(Y)}t.isBoxedPrimitive=Mr;function ms(Y){return typeof Uint8Array<"u"&&(Z(Y)||ae(Y))}t.isAnyArrayBuffer=ms,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(Y){Object.defineProperty(t,Y,{enumerable:!1,value:function(){throw new Error(Y+" is not supported in userland")}})})}(gl)),gl}var gf,Yy;function zP(){return Yy||(Yy=1,gf=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"}),gf}var ec={exports:{}},Jy;function VP(){return Jy||(Jy=1,typeof Object.create=="function"?ec.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:ec.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}),ec.exports}var Zy;function x1(){return Zy||(Zy=1,function(t){var e=Object.getOwnPropertyDescriptors||function(F){for(var z=Object.keys(F),se={},ae=0;ae<z.length;ae++)se[z[ae]]=Object.getOwnPropertyDescriptor(F,z[ae]);return se},r=/%[sdj%]/g;t.format=function(R){if(!k(R)){for(var F=[],z=0;z<arguments.length;z++)F.push(o(arguments[z]));return F.join(" ")}for(var z=1,se=arguments,ae=se.length,fe=String(R).replace(r,function(oe){if(oe==="%%")return"%";if(z>=ae)return oe;switch(oe){case"%s":return String(se[z++]);case"%d":return Number(se[z++]);case"%j":try{return JSON.stringify(se[z++])}catch{return"[Circular]"}default:return oe}}),ue=se[z];z<ae;ue=se[++z])T(ue)||!N(ue)?fe+=" "+ue:fe+=" "+o(ue);return fe},t.deprecate=function(R,F){if(typeof process<"u"&&process.noDeprecation===!0)return R;if(typeof process>"u")return function(){return t.deprecate(R,F).apply(this,arguments)};var z=!1;function se(){if(!z){if(process.throwDeprecation)throw new Error(F);process.traceDeprecation?console.trace(F):console.error(F),z=!0}return R.apply(this,arguments)}return se};var n={},s=/^$/;if(process.env.NODE_DEBUG){var i=process.env.NODE_DEBUG;i=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+i+"$","i")}t.debuglog=function(R){if(R=R.toUpperCase(),!n[R])if(s.test(R)){var F=process.pid;n[R]=function(){var z=t.format.apply(t,arguments);console.error("%s %d: %s",R,F,z)}}else n[R]=function(){};return n[R]};function o(R,F){var z={seen:[],stylize:c};return arguments.length>=3&&(z.depth=arguments[2]),arguments.length>=4&&(z.colors=arguments[3]),S(F)?z.showHidden=F:F&&t._extend(z,F),O(z.showHidden)&&(z.showHidden=!1),O(z.depth)&&(z.depth=2),O(z.colors)&&(z.colors=!1),O(z.customInspect)&&(z.customInspect=!0),z.colors&&(z.stylize=a),l(z,R,z.depth)}t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(R,F){var z=o.styles[F];return z?"\x1B["+o.colors[z][0]+"m"+R+"\x1B["+o.colors[z][1]+"m":R}function c(R,F){return R}function u(R){var F={};return R.forEach(function(z,se){F[z]=!0}),F}function l(R,F,z){if(R.customInspect&&F&&H(F.inspect)&&F.inspect!==t.inspect&&!(F.constructor&&F.constructor.prototype===F)){var se=F.inspect(z,R);return k(se)||(se=l(R,se,z)),se}var ae=f(R,F);if(ae)return ae;var fe=Object.keys(F),ue=u(fe);if(R.showHidden&&(fe=Object.getOwnPropertyNames(F)),j(F)&&(fe.indexOf("message")>=0||fe.indexOf("description")>=0))return h(F);if(fe.length===0){if(H(F)){var oe=F.name?": "+F.name:"";return R.stylize("[Function"+oe+"]","special")}if(B(F))return R.stylize(RegExp.prototype.toString.call(F),"regexp");if($(F))return R.stylize(Date.prototype.toString.call(F),"date");if(j(F))return h(F)}var ie="",ye=!1,me=["{","}"];if(v(F)&&(ye=!0,me=["[","]"]),H(F)){var ve=F.name?": "+F.name:"";ie=" [Function"+ve+"]"}if(B(F)&&(ie=" "+RegExp.prototype.toString.call(F)),$(F)&&(ie=" "+Date.prototype.toUTCString.call(F)),j(F)&&(ie=" "+h(F)),fe.length===0&&(!ye||F.length==0))return me[0]+ie+me[1];if(z<0)return B(F)?R.stylize(RegExp.prototype.toString.call(F),"regexp"):R.stylize("[Object]","special");R.seen.push(F);var ke;return ye?ke=d(R,F,z,ue,fe):ke=fe.map(function(Ze){return p(R,F,z,ue,Ze,ye)}),R.seen.pop(),m(ke,ie,me)}function f(R,F){if(O(F))return R.stylize("undefined","undefined");if(k(F)){var z="'"+JSON.stringify(F).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return R.stylize(z,"string")}if(w(F))return R.stylize(""+F,"number");if(S(F))return R.stylize(""+F,"boolean");if(T(F))return R.stylize("null","null")}function h(R){return"["+Error.prototype.toString.call(R)+"]"}function d(R,F,z,se,ae){for(var fe=[],ue=0,oe=F.length;ue<oe;++ue)W(F,String(ue))?fe.push(p(R,F,z,se,String(ue),!0)):fe.push("");return ae.forEach(function(ie){ie.match(/^\d+$/)||fe.push(p(R,F,z,se,ie,!0))}),fe}function p(R,F,z,se,ae,fe){var ue,oe,ie;if(ie=Object.getOwnPropertyDescriptor(F,ae)||{value:F[ae]},ie.get?ie.set?oe=R.stylize("[Getter/Setter]","special"):oe=R.stylize("[Getter]","special"):ie.set&&(oe=R.stylize("[Setter]","special")),W(se,ae)||(ue="["+ae+"]"),oe||(R.seen.indexOf(ie.value)<0?(T(z)?oe=l(R,ie.value,null):oe=l(R,ie.value,z-1),oe.indexOf(`
72
+ `)>-1&&(fe?oe=oe.split(`
73
+ `).map(function(ye){return" "+ye}).join(`
74
+ `).slice(2):oe=`
75
+ `+oe.split(`
76
+ `).map(function(ye){return" "+ye}).join(`
77
+ `))):oe=R.stylize("[Circular]","special")),O(ue)){if(fe&&ae.match(/^\d+$/))return oe;ue=JSON.stringify(""+ae),ue.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(ue=ue.slice(1,-1),ue=R.stylize(ue,"name")):(ue=ue.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),ue=R.stylize(ue,"string"))}return ue+": "+oe}function m(R,F,z){var se=R.reduce(function(ae,fe){return fe.indexOf(`
78
+ `)>=0,ae+fe.replace(/\u001b\[\d\d?m/g,"").length+1},0);return se>60?z[0]+(F===""?"":F+`
79
+ `)+" "+R.join(`,
80
+ `)+" "+z[1]:z[0]+F+" "+R.join(", ")+" "+z[1]}t.types=HP();function v(R){return Array.isArray(R)}t.isArray=v;function S(R){return typeof R=="boolean"}t.isBoolean=S;function T(R){return R===null}t.isNull=T;function g(R){return R==null}t.isNullOrUndefined=g;function w(R){return typeof R=="number"}t.isNumber=w;function k(R){return typeof R=="string"}t.isString=k;function _(R){return typeof R=="symbol"}t.isSymbol=_;function O(R){return R===void 0}t.isUndefined=O;function B(R){return N(R)&&ee(R)==="[object RegExp]"}t.isRegExp=B,t.types.isRegExp=B;function N(R){return typeof R=="object"&&R!==null}t.isObject=N;function $(R){return N(R)&&ee(R)==="[object Date]"}t.isDate=$,t.types.isDate=$;function j(R){return N(R)&&(ee(R)==="[object Error]"||R instanceof Error)}t.isError=j,t.types.isNativeError=j;function H(R){return typeof R=="function"}t.isFunction=H;function G(R){return R===null||typeof R=="boolean"||typeof R=="number"||typeof R=="string"||typeof R=="symbol"||typeof R>"u"}t.isPrimitive=G,t.isBuffer=zP();function ee(R){return Object.prototype.toString.call(R)}function U(R){return R<10?"0"+R.toString(10):R.toString(10)}var X=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function te(){var R=new Date,F=[U(R.getHours()),U(R.getMinutes()),U(R.getSeconds())].join(":");return[R.getDate(),X[R.getMonth()],F].join(" ")}t.log=function(){console.log("%s - %s",te(),t.format.apply(t,arguments))},t.inherits=VP(),t._extend=function(R,F){if(!F||!N(F))return R;for(var z=Object.keys(F),se=z.length;se--;)R[z[se]]=F[z[se]];return R};function W(R,F){return Object.prototype.hasOwnProperty.call(R,F)}var C=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(F){if(typeof F!="function")throw new TypeError('The "original" argument must be of type Function');if(C&&F[C]){var z=F[C];if(typeof z!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(z,C,{value:z,enumerable:!1,writable:!1,configurable:!0}),z}function z(){for(var se,ae,fe=new Promise(function(ie,ye){se=ie,ae=ye}),ue=[],oe=0;oe<arguments.length;oe++)ue.push(arguments[oe]);ue.push(function(ie,ye){ie?ae(ie):se(ye)});try{F.apply(this,ue)}catch(ie){ae(ie)}return fe}return Object.setPrototypeOf(z,Object.getPrototypeOf(F)),C&&Object.defineProperty(z,C,{value:z,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(z,e(F))},t.promisify.custom=C;function D(R,F){if(!R){var z=new Error("Promise was rejected with a falsy value");z.reason=R,R=z}return F(R)}function Z(R){if(typeof R!="function")throw new TypeError('The "original" argument must be of type Function');function F(){for(var z=[],se=0;se<arguments.length;se++)z.push(arguments[se]);var ae=z.pop();if(typeof ae!="function")throw new TypeError("The last argument must be of type Function");var fe=this,ue=function(){return ae.apply(fe,arguments)};R.apply(this,z).then(function(oe){process.nextTick(ue.bind(null,null,oe))},function(oe){process.nextTick(D.bind(null,oe,ue))})}return Object.setPrototypeOf(F,Object.getPrototypeOf(R)),Object.defineProperties(F,e(R)),F}t.callbackify=Z}(bl)),bl}Object.defineProperty(vu,"__esModule",{value:!0});vu.decode=GP;vu.encode=qP;const T1=Ws;function GP(t){return(T1.isBrowser?new TextDecoder("utf-8"):new(x1()).TextDecoder("utf-8")).decode(t)}function qP(t){return(T1.isBrowser?new TextEncoder:new(x1()).TextEncoder("utf-8")).encode(t)}var Au={},kd={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(t,e){var r=Zs,n=r.Buffer;function s(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(s(r,e),e.Buffer=i);function i(o,a,c){return n(o,a,c)}i.prototype=Object.create(n.prototype),s(n,i),i.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},i.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var u=n(o);return a!==void 0?typeof c=="string"?u.fill(a,c):u.fill(a):u.fill(0),u},i.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},i.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(kd,kd.exports);var WP=kd.exports,tc=WP.Buffer;function KP(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var o=t.length,a=t.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function l(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=tc.from(d)),!tc.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var p=0,m=0,v=0,S=d.length;v!==S&&d[v]===0;)v++,p++;for(var T=(S-v)*u+1>>>0,g=new Uint8Array(T);v!==S;){for(var w=d[v],k=0,_=T-1;(w!==0||k<m)&&_!==-1;_--,k++)w+=256*g[_]>>>0,g[_]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");m=k,v++}for(var O=T-m;O!==T&&g[O]===0;)O++;for(var B=a.repeat(p);O<T;++O)B+=t.charAt(g[O]);return B}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return tc.alloc(0);for(var p=0,m=0,v=0;d[p]===a;)m++,p++;for(var S=(d.length-p)*c+1>>>0,T=new Uint8Array(S);p<d.length;){var g=d.charCodeAt(p);if(g>255)return;var w=e[g];if(w===255)return;for(var k=0,_=S-1;(w!==0||k<v)&&_!==-1;_--,k++)w+=o*T[_]>>>0,T[_]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");v=k,p++}for(var O=S-v;O!==S&&T[O]===0;)O++;var B=tc.allocUnsafe(m+(S-O));B.fill(0,0,m);for(var N=m;O!==S;)B[N++]=T[O++];return B}function h(d){var p=f(d);if(p)return p;throw new Error("Non-base"+o+" character")}return{encode:l,decodeUnsafe:f,decode:h}}var XP=KP,YP=XP,JP="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ZP=YP(JP),QP=Br&&Br.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Au,"__esModule",{value:!0});Au.encode=eO;Au.decode=tO;const _1=QP(ZP);function eO(t){return _1.default.encode(t)}function tO(t){return _1.default.decode(t)}var ku={};Object.defineProperty(ku,"__esModule",{value:!0});ku.encode=nO;ku.decode=sO;const rO=Zs;function nO(t){return t.toString("base64")}function sO(t){return rO.Buffer.from(t,"base64")}var iO=Br&&Br.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),oO=Br&&Br.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xu=Br&&Br.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iO(e,t,r);return oO(e,t),e};Object.defineProperty(En,"__esModule",{value:!0});En.base64=En.bs58=En.utf8=P1=En.hex=void 0;var P1=En.hex=xu(wu);En.utf8=xu(vu);En.bs58=xu(Au);En.base64=xu(ku);class es{constructor(e,r,n,s,i){try{this.swapId=Array.from(Buffer.from(e,"hex")),this.secretHash=Array.from(Buffer.from(n,"hex"))}catch(o){throw new Error("Error decoding swapId or secretHash",{cause:o})}if(this.secretHash.length!=32||this.swapId.length!=32)throw new Error("swapId or secretHash must be exactly 32 bits in size");try{this.redeemer=new mr.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new Cf.BigNumber(s.toString(10),10),this.expiresIn=new Cf.BigNumber(i)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(i)&&i>0))throw new Error("expiresIn must be a positive integer.")}static from(e){let r;if(e.source_swap.chain.includes("solana"))r=e.source_swap;else if(e.destination_swap.chain.includes("solana"))r=e.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:s,secret_hash:i,timelock:o}=r,a=BigInt(r.amount);return new es(n,s,i,a,o)}}function O1(t){let e;try{e=[...P1.decode(t)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(e.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+e.length);return e}class I1{constructor(e,r,n,s,i){var f,h;if(this.provider=e,this.url=r,!e)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(n==null)throw new Error("Network is required");const o=n===E.Network.MAINNET?pd.mainnet:pd.staging,a={native:((f=i==null?void 0:i.programAddress)==null?void 0:f.native)??o.native,spl:((h=i==null?void 0:i.programAddress)==null?void 0:h.spl)??o.spl},c=(i==null?void 0:i.relayer)??Ew[n];this.auth=s;try{this.relayer=new mr.web3.PublicKey(c)}catch(d){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:d})}this.relayerClient=new ti(this.auth,this.url);const u=a.spl?{...X0,metadata:{...X0.metadata??{}},address:a.spl}:void 0,l=a.native?{...Ad,metadata:{...Ad.metadata??{}},address:a.native}:void 0;try{this.splProgram=u?new mr.Program(u,this.provider):void 0,this.nativeProgram=l?new mr.Program(l,this.provider):void 0}catch(d){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:d})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return E.Err("Order is required");if(V.isSolanaOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const r=V.ChainAsset.fromString(e.source_swap.asset);return V.isSolanaNativeToken(r.chain,r.symbol)?this.nativeProgram?await this.initiateNativeSwap(e):E.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(e):E.Err("SPL program is not initialized")}catch(r){return E.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async sendSplViaRelayer(e,r){try{e.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,e.feePayer=this.relayer;const s=(await this.provider.wallet.signTransaction(e)).serialize({requireAllSignatures:!1}).toString("base64"),i=await E.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:s}),headers:{"Content-Type":"application/json"}});return i.error||!i.result?E.Err(`Error from Relayer: ${i.error}`):await Va(this.provider.connection,i.result)?E.Ok(i.result):E.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return E.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(e,r){if(!r)return E.Err("Order is required");try{const n=await this.provider.sendAndConfirm(e);return n?await Va(this.provider.connection,n)?E.Ok(n):E.Err("HTLC: Failed to Initiate swap, confirmation timed out"):E.Err("Failed to initiate HTLC transaction")}catch(n){return E.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiateSplSwap(e){if(!this.splProgram)return E.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=this.splProgram.methods.initiate(i,r,n,s,null),a=await ji(e.source_swap.asset,this.url);if(!a.ok)return E.Err(a.error);const{tokenAddress:c}=a.val,u=new mr.web3.PublicKey(c),l={initiator:this.provider.publicKey,mint:u,initiatorTokenAccount:l2.getAssociatedTokenAddressSync(u,this.provider.publicKey),sponsor:this.relayer},f=await o.accounts(l).transaction();return this.sendSplViaRelayer(f,e.order_id)}catch(r){return E.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(e){if(!this.nativeProgram)return E.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(o,e)}catch(r){return E.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateWithCreateOrderResponse(e){if(!this.relayer)return E.Err("No relayer address");const{versioned_tx:r,versioned_tx_gasless:n}=e;if(n===null)try{const i=Buffer.from(r,"base64"),o=mr.web3.VersionedTransaction.deserialize(i),a=await this.provider.sendAndConfirm(o);return await Va(this.provider.connection,a)?E.Ok(a):E.Err("Failed to initiate HTLC transaction")}catch(i){return E.Err(`Error in non-gasless flow: ${i}`)}const s=await this.auth.getAuthHeaders();if(!s.ok)return E.Err(s.error);try{const i=mr.web3.VersionedTransaction.deserialize(Buffer.from(n,"base64")),o=await this.provider.wallet.signTransaction(i);if(!o.signatures[0])return E.Err("No signature found after signing transaction");const c=Buffer.from(o.serialize()).toString("base64"),u=await this.relayerClient.initiate(e.order_id,c);return u.error?E.Err(u.error):u.val?E.Ok(u.val):E.Err("Initiate: No result found")}catch(i){return E.Err(`Error initiating with create order response: ${i}`)}}async redeem(e,r){try{const n=O1(r),s=await this.relayerClient.redeem(e.order_id,Buffer.from(n).toString("hex"));if(s.error||!s.val)return E.Err(`Redeem: Error from relayer: ${s.error}`);const i=s.val;return await Va(this.provider.connection,i)?E.Ok(i):E.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),E.Err(`Error redeeming: ${n}`)}}async refund(){return E.Err("Refund is automatically handled by the relayer.")}}const B1="1.45.2",aO="1.62.0",cO={"-32700":"ParseError","-32701":"OversizedRequest","-32702":"OversizedResponse","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError","-32604":"ServerBusy","-32000":"CallExecutionFailed","-32001":"UnknownError","-32003":"SubscriptionClosed","-32004":"SubscriptionClosedWithError","-32005":"BatchesNotSupported","-32006":"TooManySubscriptions","-32050":"TransientError","-32002":"TransactionExecutionClientError"};class C1 extends Error{}class N1 extends C1{constructor(e,r){super(e),this.code=r,this.type=cO[r]??"ServerError"}}class uO extends C1{constructor(e,r,n){super(e),this.status=r,this.statusText=n}}var R1=t=>{throw TypeError(t)},np=(t,e,r)=>e.has(t)||R1("Cannot "+r),Ue=(t,e,r)=>(np(t,e,"read from private field"),r?r.call(t):e.get(t)),ws=(t,e,r)=>e.has(t)?R1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Pi=(t,e,r,n)=>(np(t,e,"write to private field"),e.set(t,r),r),M1=(t,e,r)=>(np(t,e,"access private method"),r),lO=(t,e,r,n)=>({set _(s){Pi(t,e,s)},get _(){return Ue(t,e,n)}}),qn,Ao,bn,xs,ra,Ts,Oc,j1,U1;function fO(t){const e=new URL(t);return e.protocol=e.protocol.replace("http","ws"),e.toString()}const dO={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class hO{constructor(e,r={}){if(ws(this,Oc),ws(this,qn,0),ws(this,Ao,0),ws(this,bn,null),ws(this,xs,null),ws(this,ra,new Set),ws(this,Ts,new Map),this.endpoint=e,this.options={...dO,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=fO(this.endpoint))}async makeRequest(e,r,n){const s=await M1(this,Oc,j1).call(this);return new Promise((i,o)=>{Pi(this,qn,Ue(this,qn)+1),Ue(this,Ts).set(Ue(this,qn),{resolve:i,reject:o,timeout:setTimeout(()=>{Ue(this,Ts).delete(Ue(this,qn)),o(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{Ue(this,Ts).delete(Ue(this,qn)),o(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:Ue(this,qn),method:e,params:r}))}).then(({error:i,result:o})=>{if(i)throw new N1(i.message,i.code);return o})}async subscribe(e){const r=new pO(e);return Ue(this,ra).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}qn=new WeakMap;Ao=new WeakMap;bn=new WeakMap;xs=new WeakMap;ra=new WeakMap;Ts=new WeakMap;Oc=new WeakSet;j1=function(){return Ue(this,xs)?Ue(this,xs):(Pi(this,xs,new Promise(t=>{var e;(e=Ue(this,bn))==null||e.close(),Pi(this,bn,new this.options.WebSocketConstructor(this.endpoint)),Ue(this,bn).addEventListener("open",()=>{Pi(this,Ao,0),t(Ue(this,bn))}),Ue(this,bn).addEventListener("close",()=>{lO(this,Ao)._++,Ue(this,Ao)<=this.options.maxReconnects&&setTimeout(()=>{M1(this,Oc,U1).call(this)},this.options.reconnectTimeout)}),Ue(this,bn).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(s){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:s}));return}if("id"in n&&n.id!=null&&Ue(this,Ts).has(n.id)){const{resolve:s,timeout:i}=Ue(this,Ts).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;Ue(this,ra).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),Ue(this,xs))};U1=async function(){var t;return(t=Ue(this,bn))==null||t.close(),Pi(this,xs,null),Promise.allSettled([...Ue(this,ra)].map(e=>e.subscribe(this)))};class pO{constructor(e){this.subscriptionId=null,this.subscribed=!1,this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){const{subscriptionId:r}=this;return this.subscribed=!1,r==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[r]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;const r=await e.makeRequest(this.input.method,this.input.params,this.input.signal);this.subscribed&&(this.subscriptionId=r)}}var F1=t=>{throw TypeError(t)},sp=(t,e,r)=>e.has(t)||F1("Cannot "+r),ur=(t,e,r)=>(sp(t,e,"read from private field"),r?r.call(t):e.get(t)),rc=(t,e,r)=>e.has(t)?F1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),xd=(t,e,r,n)=>(sp(t,e,"write to private field"),e.set(t,r),r),yO=(t,e,r)=>(sp(t,e,"access private method"),r),mo,br,ko,Td,$1;class mO{constructor(e){rc(this,Td),rc(this,mo,0),rc(this,br),rc(this,ko),xd(this,br,e)}fetch(e,r){const n=ur(this,br).fetch??fetch;if(!n)throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");return n(e,r)}async request(e){var s,i;xd(this,mo,ur(this,mo)+1);const r=await this.fetch(((s=ur(this,br).rpc)==null?void 0:s.url)??ur(this,br).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":B1,"Client-Target-Api-Version":aO,"Client-Request-Method":e.method,...(i=ur(this,br).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:ur(this,mo),method:e.method,params:e.params})});if(!r.ok)throw new uO(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new N1(n.error.message,n.error.code);return n.result}async subscribe(e){const r=await yO(this,Td,$1).call(this).subscribe(e);return e.signal&&(e.signal.throwIfAborted(),e.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}mo=new WeakMap;br=new WeakMap;ko=new WeakMap;Td=new WeakSet;$1=function(){var t;if(!ur(this,ko)){const e=ur(this,br).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");xd(this,ko,new hO(((t=ur(this,br).websocket)==null?void 0:t.url)??ur(this,br).url,{WebSocketConstructor:e,...ur(this,br).websocket}))}return ur(this,ko)};function Qy(t){switch(t){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${t}`)}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bO(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function L1(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function _d(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function D1(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Pd(t){if(!Array.isArray(t))throw new Error("array expected")}function H1(t,e){if(!L1(!0,e))throw new Error(`${t}: array of strings expected`)}function gO(t,e){if(!L1(!1,e))throw new Error(`${t}: array of numbers expected`)}function wO(...t){const e=i=>i,r=(i,o)=>a=>i(o(a)),n=t.map(i=>i.encode).reduceRight(r,e),s=t.map(i=>i.decode).reduce(r,e);return{encode:n,decode:s}}function vO(t){const e=typeof t=="string"?t.split(""):t,r=e.length;H1("alphabet",e);const n=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(Pd(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(Pd(s),s.map(i=>{_d("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function EO(t=""){return _d("join",t),{encode:e=>(H1("join.decode",e),e.join(t)),decode:e=>(_d("join.decode",e),e.split(t))}}function em(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Pd(t),!t.length)return[];let n=0;const s=[],i=Array.from(t,a=>{if(D1(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let u=n;u<o;u++){const l=i[u],f=e*a,h=f+l;if(!Number.isSafeInteger(h)||f/e!==a||h-l!==f)throw new Error("convertRadix: carry overflow");const d=h/r;a=h%r;const p=Math.floor(d);if(i[u]=p,!Number.isSafeInteger(p)||p*r+a!==h)throw new Error("convertRadix: carry overflow");if(c)p?c=!1:n=u;else continue}if(s.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)s.push(0);return s.reverse()}function SO(t){D1(t);const e=2**8;return{encode:r=>{if(!bO(r))throw new Error("radix.encode input should be Uint8Array");return em(Array.from(r),e,t)},decode:r=>(gO("radix.decode",r),Uint8Array.from(em(r,t,e)))}}const AO=t=>wO(SO(58),vO(t),EO("")),z1=AO("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Tu=t=>z1.encode(t),na=t=>z1.decode(t);function Xt(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}const wf=8192;function mt(t){if(t.length<wf)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=wf){const n=t.slice(r,r+wf);e+=String.fromCharCode(...n)}return btoa(e)}function V1(t){var s;const e=t.startsWith("0x")?t.slice(2):t,r=e.length%2===0?e:`0${e}`,n=((s=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:s.map(i=>parseInt(i,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${t}`);return Uint8Array.from(n)}function Di(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"")}function _u(t,e){return Array.from({length:Math.ceil(t.length/e)},(r,n)=>t.slice(n*e,(n+1)*e))}class G1{constructor(e,r){if(typeof e!="function")throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=_O(r),this._batchScheduleFn=PO(r),this._cacheKeyFn=OO(r),this._cacheMap=IO(r),this._batch=null,this.name=BO(r)}load(e){if(e==null)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const r=xO(this),n=this._cacheMap;let s;if(n){s=this._cacheKeyFn(e);const o=n.get(s);if(o){const a=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{a.push(()=>{c(o)})})}}r.keys.push(e);const i=new Promise((o,a)=>{r.callbacks.push({resolve:o,reject:a})});return n&&n.set(s,i),i}loadMany(e){if(!q1(e))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${e}.`);const r=[];for(let n=0;n<e.length;n++)r.push(this.load(e[n]).catch(s=>s));return Promise.all(r)}clear(e){const r=this._cacheMap;if(r){const n=this._cacheKeyFn(e);r.delete(n)}return this}clearAll(){const e=this._cacheMap;return e&&e.clear(),this}prime(e,r){const n=this._cacheMap;if(n){const s=this._cacheKeyFn(e);if(n.get(s)===void 0){let i;r instanceof Error?(i=Promise.reject(r),i.catch(()=>{})):i=Promise.resolve(r),n.set(s,i)}}return this}}const kO=typeof process=="object"&&typeof process.nextTick=="function"?function(t){vf||(vf=Promise.resolve()),vf.then(()=>{process.nextTick(t)})}:typeof setImmediate=="function"?function(t){setImmediate(t)}:function(t){setTimeout(t)};let vf;function xO(t){const e=t._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<t._maxBatchSize)return e;const r={hasDispatched:!1,keys:[],callbacks:[]};return t._batch=r,t._batchScheduleFn(()=>{TO(t,r)}),r}function TO(t,e){if(e.hasDispatched=!0,e.keys.length===0){Od(e);return}let r;try{r=t._batchLoadFn(e.keys)}catch(n){return Ef(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!r||typeof r.then!="function")return Ef(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(r)}.`));Promise.resolve(r).then(n=>{if(!q1(n))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(n)}.`);if(n.length!==e.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.
81
+
82
+ Keys:
83
+ ${String(e.keys)}
84
+
85
+ Values:
86
+ ${String(n)}`);Od(e);for(let s=0;s<e.callbacks.length;s++){const i=n[s];i instanceof Error?e.callbacks[s].reject(i):e.callbacks[s].resolve(i)}}).catch(n=>{Ef(t,e,n)})}function Ef(t,e,r){Od(e);for(let n=0;n<e.keys.length;n++)t.clear(e.keys[n]),e.callbacks[n].reject(r)}function Od(t){if(t.cacheHits)for(let e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}function _O(t){if(!(!t||t.batch!==!1))return 1;const r=t&&t.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError(`maxBatchSize must be a positive number: ${r}`);return r}function PO(t){const e=t&&t.batchScheduleFn;if(e===void 0)return kO;if(typeof e!="function")throw new TypeError(`batchScheduleFn must be a function: ${e}`);return e}function OO(t){const e=t&&t.cacheKeyFn;if(e===void 0)return r=>r;if(typeof e!="function")throw new TypeError(`cacheKeyFn must be a function: ${e}`);return e}function IO(t){if(!(!t||t.cache!==!1))return null;const r=t&&t.cacheMap;if(r===void 0)return new Map;if(r!==null){const s=["get","set","delete","clear"].filter(i=>r&&typeof r[i]!="function");if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}function BO(t){return t&&t.name?t.name:null}function q1(t){return typeof t=="object"&&t!==null&&"length"in t&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}function Ic(t){let e=BigInt(t);const r=[];let n=0;if(e===0n)return[0];for(;e>0;)r[n]=Number(e&0x7fn),e>>=7n,e>0n&&(r[n]|=128),n+=1;return r}function CO(t){let e=0n,r=0n,n=0;for(;;){if(n>=t.length)throw new Error("ULEB decode error: buffer overflow");const s=t[n];if(n+=1,e+=BigInt(s&127)<<r,!(s&128))break;r+=7n}if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("ULEB decode error: value exceeds MAX_SAFE_INTEGER");return{value:Number(e),length:n}}class NO{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}shift(e){return this.bytePosition+=e,this}read8(){const e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){const e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){const e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){const e=this.read32(),n=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+n).toString(10)}read128(){const e=BigInt(this.read64()),n=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+n).toString(10)}read256(){const e=BigInt(this.read128()),n=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+n).toString(10)}readBytes(e){const r=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,r,e);return this.shift(e),n}readULEB(){const e=this.bytePosition+this.dataView.byteOffset,r=new Uint8Array(this.dataView.buffer,e),{value:n,length:s}=CO(r);return this.shift(s),n}readVec(e){const r=this.readULEB(),n=[];for(let s=0;s<r;s++)n.push(e(this,s,r));return n}}function RO(t,e){switch(e){case"base58":return Tu(t);case"base64":return mt(t);case"hex":return Di(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function W1(t,e=["<",">"]){const[r,n]=e,s=[];let i="",o=0;for(let a=0;a<t.length;a++){const c=t[a];if(c===r&&o++,c===n&&o--,o===0&&c===","){s.push(i.trim()),i="";continue}i+=c}return s.push(i.trim()),s}class MO{constructor({initialSize:e=1024,maxSize:r=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=r,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const r=this.bytePosition+e;if(r>this.size){const n=Math.min(this.maxSize,Math.max(this.size+r,this.size+this.allocateSize));if(r>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${r}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}writeBytes(e){this.ensureSizeOrGrow(e.length);for(let r=0;r<e.length;r++)this.dataView.setUint8(this.bytePosition+r,e[r]);return this.shift(e.length)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return Sf(BigInt(e),8).forEach(r=>this.write8(r)),this}write128(e){return Sf(BigInt(e),16).forEach(r=>this.write8(r)),this}write256(e){return Sf(BigInt(e),32).forEach(r=>this.write8(r)),this}writeULEB(e){return Ic(e).forEach(r=>this.write8(r)),this}writeVec(e,r){return this.writeULEB(e.length),Array.from(e).forEach((n,s)=>r(this,n,s,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return RO(this.toBytes(),e)}}function Sf(t,e){const r=new Uint8Array(e);let n=0;for(;t>0;)r[n]=Number(t%BigInt(256)),t=t/BigInt(256),n+=1;return r}var K1=t=>{throw TypeError(t)},X1=(t,e,r)=>e.has(t)||K1("Cannot "+r),gr=(t,e,r)=>(X1(t,e,"read from private field"),r?r.call(t):e.get(t)),Bc=(t,e,r)=>e.has(t)?K1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Cc=(t,e,r,n)=>(X1(t,e,"write to private field"),e.set(t,r),r),pi,bo,hc,Wn;const jO=class Y1{constructor(e){Bc(this,pi),Bc(this,bo),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),Cc(this,pi,e.write),Cc(this,bo,e.serialize??((r,n)=>{const s=new MO({initialSize:this.serializedSize(r)??void 0,...n});return gr(this,pi).call(this,r,s),s.toBytes()})),this.validate=e.validate??(()=>{})}write(e,r){this.validate(e),gr(this,pi).call(this,e,r)}serialize(e,r){return this.validate(e),new UO(this,gr(this,bo).call(this,e,r))}parse(e){const r=new NO(e);return this.read(r)}fromHex(e){return this.parse(V1(e))}fromBase58(e){return this.parse(na(e))}fromBase64(e){return this.parse(Xt(e))}transform({name:e,input:r,output:n,validate:s}){return new Y1({name:e??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>gr(this,pi).call(this,r?r(i):i,o),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,o)=>gr(this,bo).call(this,r?r(i):i,o),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};pi=new WeakMap;bo=new WeakMap;let tn=jO;const J1=Symbol.for("@mysten/serialized-bcs");function ip(t){return!!t&&typeof t=="object"&&t[J1]===!0}class UO{constructor(e,r){Bc(this,hc),Bc(this,Wn),Cc(this,hc,e),Cc(this,Wn,r)}get[J1](){return!0}toBytes(){return gr(this,Wn)}toHex(){return Di(gr(this,Wn))}toBase64(){return mt(gr(this,Wn))}toBase58(){return Tu(gr(this,Wn))}parse(){return gr(this,hc).parse(gr(this,Wn))}}hc=new WeakMap;Wn=new WeakMap;function Nc({size:t,...e}){return new tn({...e,serializedSize:()=>t})}function Af({readMethod:t,writeMethod:e,...r}){return Nc({...r,read:n=>n[t](),write:(n,s)=>s[e](n),validate:n=>{var s;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,n)}})}function kf({readMethod:t,writeMethod:e,...r}){return Nc({...r,read:n=>n[t](),write:(n,s)=>s[e](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${s}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,s)}})}function FO({serialize:t,...e}){const r=new tn({...e,serialize:t,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function $O({toBytes:t,fromBytes:e,...r}){return new tn({...r,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return e(i)},write:(n,s)=>{const i=t(n);s.writeULEB(i.length);for(let o=0;o<i.length;o++)s.write8(i[o])},serialize:n=>{const s=t(n),i=Ic(s.length),o=new Uint8Array(i.length+s.length);return o.set(i,0),o.set(s,i.length),o},validate:n=>{var s;if(typeof n!="string")throw new TypeError(`Invalid ${r.name} value: ${n}. Expected string`);(s=r.validate)==null||s.call(r,n)}})}function LO(t){let e=null;function r(){return e||(e=t()),e}return new tn({name:"lazy",read:n=>r().read(n),serializedSize:n=>r().serializedSize(n),write:(n,s)=>r().write(n,s),serialize:(n,s)=>r().serialize(n,s).toBytes()})}class DO extends tn{constructor({name:e,fields:r,...n}){const s=Object.entries(r);super({name:e,serializedSize:i=>{let o=0;for(const[a,c]of s){const u=c.serializedSize(i[a]);if(u==null)return null;o+=u}return o},read:i=>{const o={};for(const[a,c]of s)o[a]=c.read(i);return o},write:(i,o)=>{for(const[a,c]of s)c.write(i[a],o)},...n,validate:i=>{var o;if((o=n==null?void 0:n.validate)==null||o.call(n,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`)}})}}class HO extends tn{constructor({fields:e,...r}){const n=Object.entries(e);super({read:s=>{const i=s.readULEB(),o=n[i];if(!o)throw new TypeError(`Unknown value ${i} for enum ${r.name}`);const[a,c]=o;return{[a]:(c==null?void 0:c.read(s))??!0,$kind:a}},write:(s,i)=>{const[o,a]=Object.entries(s).filter(([c])=>Object.hasOwn(e,c))[0];for(let c=0;c<n.length;c++){const[u,l]=n[c];if(u===o){i.writeULEB(c),l==null||l.write(a,i);return}}},...r,validate:s=>{var a;if((a=r==null?void 0:r.validate)==null||a.call(r,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(e,c));if(i.length!==1)throw new TypeError(`Expected object with one key, but found ${i.length} for type ${r.name}}`);const[o]=i;if(!Object.hasOwn(e,o))throw new TypeError(`Invalid enum variant ${o}`)}})}}class zO extends tn{constructor({fields:e,name:r,...n}){super({name:r??`(${e.map(s=>s.name).join(", ")})`,serializedSize:s=>{let i=0;for(let o=0;o<e.length;o++){const a=e[o].serializedSize(s[o]);if(a==null)return null;i+=a}return i},read:s=>{const i=[];for(const o of e)i.push(o.read(s));return i},write:(s,i)=>{for(let o=0;o<e.length;o++)e[o].write(s[o],i)},...n,validate:s=>{var i;if((i=n==null?void 0:n.validate)==null||i.call(n,s),!Array.isArray(s))throw new TypeError(`Expected array, found ${typeof s}`);if(s.length!==e.length)throw new TypeError(`Expected array of length ${e.length}, found ${s.length}`)}})}}function VO(t,e,r){return new tn({read:n=>{const s=new Array(t);for(let i=0;i<t;i++)s[i]=e.read(n);return s},write:(n,s)=>{for(const i of n)e.write(i,s)},...r,name:(r==null?void 0:r.name)??`${e.name}[${t}]`,validate:n=>{var s;if((s=r==null?void 0:r.validate)==null||s.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==t)throw new TypeError(`Expected array of length ${t}, found ${n.length}`)}})}function GO(t){return I.enum(`Option<${t.name}>`,{None:null,Some:t}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>e.$kind==="Some"?e.Some:null})}function qO(t,e){return new tn({read:r=>{const n=r.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=t.read(r);return s},write:(r,n)=>{n.writeULEB(r.length);for(const s of r)t.write(s,n)},...e,name:(e==null?void 0:e.name)??`vector<${t.name}>`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`)}})}function WO(t,e){return I.vector(I.tuple([t,e])).transform({name:`Map<${t.name}, ${e.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const I={u8(t){return Af({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...t,name:(t==null?void 0:t.name)??"u8"})},u16(t){return Af({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...t,name:(t==null?void 0:t.name)??"u16"})},u32(t){return Af({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...t,name:(t==null?void 0:t.name)??"u32"})},u64(t){return kf({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...t,name:(t==null?void 0:t.name)??"u64"})},u128(t){return kf({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...t,name:(t==null?void 0:t.name)??"u128"})},u256(t){return kf({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...t,name:(t==null?void 0:t.name)??"u256"})},bool(t){return Nc({size:1,read:e=>e.read8()===1,write:(e,r)=>r.write8(e?1:0),...t,name:(t==null?void 0:t.name)??"bool",validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),typeof e!="boolean")throw new TypeError(`Expected boolean, found ${typeof e}`)}})},uleb128(t){return FO({read:e=>e.readULEB(),serialize:e=>Uint8Array.from(Ic(e)),...t,name:(t==null?void 0:t.name)??"uleb128"})},bytes(t,e){return Nc({size:t,read:r=>r.readBytes(t),write:(r,n)=>{n.writeBytes(new Uint8Array(r))},...e,name:(e==null?void 0:e.name)??`bytes[${t}]`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`);if(r.length!==t)throw new TypeError(`Expected array of length ${t}, found ${r.length}`)}})},byteVector(t){return new tn({read:e=>{const r=e.readULEB();return e.readBytes(r)},write:(e,r)=>{const n=new Uint8Array(e);r.writeULEB(n.length),r.writeBytes(n)},...t,name:(t==null?void 0:t.name)??"vector<u8>",serializedSize:e=>{const r="length"in e?e.length:null;return r==null?null:Ic(r).length+r},validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),!e||typeof e!="object"||!("length"in e))throw new TypeError(`Expected array, found ${typeof e}`)}})},string(t){return $O({toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...t,name:(t==null?void 0:t.name)??"string"})},fixedArray:VO,option:GO,vector:qO,tuple(t,e){return new zO({fields:t,...e})},struct(t,e,r){return new DO({name:t,fields:e,...r})},enum(t,e,r){return new HO({name:t,fields:e,...r})},map:WO,lazy(t){return LO(t)}};var Z1=t=>{throw TypeError(t)},Q1=(t,e,r)=>e.has(t)||Z1("Cannot "+r),pt=(t,e,r)=>(Q1(t,e,"read from private field"),e.get(t)),tm=(t,e,r)=>e.has(t)?Z1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),rm=(t,e,r,n)=>(Q1(t,e,"write to private field"),e.set(t,r),r),Es,xt;const KO=class ev{constructor({prefix:e,cache:r}={}){tm(this,Es),tm(this,xt),rm(this,Es,e??[]),rm(this,xt,r??new Map)}read(e,r){const n=[pt(this,Es),...e].join(":");if(pt(this,xt).has(n))return pt(this,xt).get(n);const s=r();return pt(this,xt).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(pt(this,xt).set(n,i),i)).catch(i=>{throw pt(this,xt).delete(n),i}):s}readSync(e,r){const n=[pt(this,Es),...e].join(":");if(pt(this,xt).has(n))return pt(this,xt).get(n);const s=r();return pt(this,xt).set(n,s),s}clear(e){const r=[...pt(this,Es),...e??[]].join(":");if(!r){pt(this,xt).clear();return}for(const n of pt(this,xt).keys())n.startsWith(r)&&pt(this,xt).delete(n)}scope(e){return new ev({prefix:[...pt(this,Es),...Array.isArray(e)?e:[e]],cache:pt(this,xt)})}};Es=new WeakMap;xt=new WeakMap;let XO=KO;class tv{constructor({network:e,base:r,cache:n=(r==null?void 0:r.cache)??new XO}){this.network=e,this.base=r??this,this.cache=n}$extend(...e){return Object.create(this,Object.fromEntries(e.map(r=>[r.name,{value:r.register(this)}])))}}let fn;function rv(t){return{lang:(t==null?void 0:t.lang)??(fn==null?void 0:fn.lang),message:t==null?void 0:t.message,abortEarly:(t==null?void 0:t.abortEarly)??(fn==null?void 0:fn.abortEarly),abortPipeEarly:(t==null?void 0:t.abortPipeEarly)??(fn==null?void 0:fn.abortPipeEarly)}}let xf;function YO(t){return xf==null?void 0:xf.get(t)}let Tf;function JO(t){return Tf==null?void 0:Tf.get(t)}let _f;function ZO(t,e){var r;return(r=_f==null?void 0:_f.get(t))==null?void 0:r.get(e)}function nv(t){var r,n;const e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&((n=(r=Object.getPrototypeOf(t))==null?void 0:r.constructor)==null?void 0:n.name))??"null":e}function Lt(t,e,r,n,s){const i=s&&"input"in s?s.input:r.value,o=(s==null?void 0:s.expected)??t.expects??null,a=(s==null?void 0:s.received)??nv(i),c={kind:t.kind,type:t.type,input:i,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:t.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=t.kind==="schema",l=(s==null?void 0:s.message)??t.message??ZO(t.reference,c.lang)??(u?JO(c.lang):null)??n.message??YO(c.lang);l!==void 0&&(c.message=typeof l=="function"?l(c):l),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function wt(t){return{version:1,vendor:"valibot",validate(e){return t["~run"]({value:e},rv())}}}function QO(t,e){return Object.hasOwn(t,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}function e3(t,e){const r=[...new Set(t)];return r.length>1?`(${r.join(` ${e} `)})`:r[0]??"never"}var t3=class extends Error{constructor(t){super(t[0].message),this.name="ValiError",this.issues=t}};function op(t,e){return{kind:"validation",type:"check",reference:op,async:!1,expects:null,requirement:t,message:e,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&Lt(this,"input",r,n),r}}}function jt(t){return{kind:"validation",type:"integer",reference:jt,async:!1,expects:null,requirement:Number.isInteger,message:t,"~run"(e,r){return e.typed&&!this.requirement(e.value)&&Lt(this,"integer",e,r),e}}}function Pu(t){return{kind:"transformation",type:"transform",reference:Pu,async:!1,operation:t,"~run"(e){return e.value=this.operation(e.value),e}}}function r3(t,e,r){return typeof t.fallback=="function"?t.fallback(e,r):t.fallback}function Ou(t,e,r){return typeof t.default=="function"?t.default(e,r):t.default}function Id(t,e){return!t["~run"]({value:e},{abortEarly:!0}).issues}function Se(t,e){return{kind:"schema",type:"array",reference:Se,expects:"Array",async:!1,item:t,message:e,get"~standard"(){return wt(this)},"~run"(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<s.length;o++){const a=s[o],c=this.item["~run"]({value:a},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:o,value:a};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Lt(this,"type",r,n);return r}}}function sv(t){return{kind:"schema",type:"bigint",reference:sv,expects:"bigint",async:!1,message:t,get"~standard"(){return wt(this)},"~run"(e,r){return typeof e.value=="bigint"?e.typed=!0:Lt(this,"type",e,r),e}}}function Ji(t){return{kind:"schema",type:"boolean",reference:Ji,expects:"boolean",async:!1,message:t,get"~standard"(){return wt(this)},"~run"(e,r){return typeof e.value=="boolean"?e.typed=!0:Lt(this,"type",e,r),e}}}function Bd(t){return{kind:"schema",type:"lazy",reference:Bd,expects:"unknown",async:!1,getter:t,get"~standard"(){return wt(this)},"~run"(e,r){return this.getter(e.value)["~run"](e,r)}}}function rt(t,e){return{kind:"schema",type:"literal",reference:rt,expects:nv(t),async:!1,literal:t,message:e,get"~standard"(){return wt(this)},"~run"(r,n){return r.value===this.literal?r.typed=!0:Lt(this,"type",r,n),r}}}function Ge(t,e){return{kind:"schema",type:"nullable",reference:Ge,expects:`(${t.expects} | null)`,async:!1,wrapped:t,default:e,get"~standard"(){return wt(this)},"~run"(r,n){return r.value===null&&(this.default!==void 0&&(r.value=Ou(this,r,n)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function sa(t,e){return{kind:"schema",type:"nullish",reference:sa,expects:`(${t.expects} | null | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return wt(this)},"~run"(r,n){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=Ou(this,r,n)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function Ut(t){return{kind:"schema",type:"number",reference:Ut,expects:"number",async:!1,message:t,get"~standard"(){return wt(this)},"~run"(e,r){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:Lt(this,"type",e,r),e}}}function de(t,e){return{kind:"schema",type:"object",reference:de,expects:"Object",async:!1,entries:t,message:e,get"~standard"(){return wt(this)},"~run"(r,n){var i;const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const o in this.entries){const a=this.entries[o];if(o in s||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){const c=o in s?s[o]:Ou(a),u=a["~run"]({value:c},n);if(u.issues){const l={type:"object",origin:"value",input:s,key:o,value:c};for(const f of u.issues)f.path?f.path.unshift(l):f.path=[l],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=u.issues),n.abortEarly){r.typed=!1;break}}u.typed||(r.typed=!1),r.value[o]=u.value}else if(a.fallback!==void 0)r.value[o]=r3(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(Lt(this,"key",r,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:s,key:o,value:s[o]}]}),n.abortEarly))break}}else Lt(this,"type",r,n);return r}}}function Kt(t,e){return{kind:"schema",type:"optional",reference:Kt,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return wt(this)},"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Ou(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function ia(t,e,r){return{kind:"schema",type:"record",reference:ia,expects:"Object",async:!1,key:t,value:e,message:r,get"~standard"(){return wt(this)},"~run"(n,s){var o,a;const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const c in i)if(QO(i,c)){const u=i[c],l=this.key["~run"]({value:c},s);if(l.issues){const h={type:"object",origin:"key",input:i,key:c,value:u};for(const d of l.issues)d.path=[h],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=l.issues),s.abortEarly){n.typed=!1;break}}const f=this.value["~run"]({value:u},s);if(f.issues){const h={type:"object",origin:"value",input:i,key:c,value:u};for(const d of f.issues)d.path?d.path.unshift(h):d.path=[h],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=f.issues),s.abortEarly){n.typed=!1;break}}(!l.typed||!f.typed)&&(n.typed=!1),l.typed&&(n.value[l.value]=f.value)}}else Lt(this,"type",n,s);return n}}}function xe(t){return{kind:"schema",type:"string",reference:xe,expects:"string",async:!1,message:t,get"~standard"(){return wt(this)},"~run"(e,r){return typeof e.value=="string"?e.typed=!0:Lt(this,"type",e,r),e}}}function ap(t,e){return{kind:"schema",type:"tuple",reference:ap,expects:"Array",async:!1,items:t,message:e,get"~standard"(){return wt(this)},"~run"(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<this.items.length;o++){const a=s[o],c=this.items[o]["~run"]({value:a},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:o,value:a};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Lt(this,"type",r,n);return r}}}function nm(t){let e;if(t)for(const r of t)e?e.push(...r.issues):e=r.issues;return e}function rn(t,e){return{kind:"schema",type:"union",reference:rn,expects:e3(t.map(r=>r.expects),"|"),async:!1,options:t,message:e,get"~standard"(){return wt(this)},"~run"(r,n){let s,i,o;for(const a of this.options){const c=a["~run"]({value:r.value},n);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else o?o.push(c):o=[c]}if(s)return s;if(i){if(i.length===1)return i[0];Lt(this,"type",r,n,{issues:nm(i)}),r.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];Lt(this,"type",r,n,{issues:nm(o)})}return r}}}function Na(){return{kind:"schema",type:"unknown",reference:Na,expects:"unknown",async:!1,get"~standard"(){return wt(this)},"~run"(t){return t.typed=!0,t}}}function De(t,e,r){const n=t["~run"]({value:e},rv(r));if(n.issues)throw new t3(n.issues);return n.value}function ft(...t){return{...t[0],pipe:t,get"~standard"(){return wt(this)},"~run"(e,r){for(const n of t)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!r.abortEarly&&!r.abortPipeEarly)&&(e=n["~run"](e,r))}return e}}}const iv=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,ov=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,n3=235;function s3(t){return t.length>n3?!1:t.includes("@")?iv.test(t):ov.test(t)}function i3(t,e="at"){const r=t.toLowerCase();let n;if(r.includes("@")){if(!iv.test(r))throw new Error(`Invalid SuiNS name ${t}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!ov.test(r))throw new Error(`Invalid SuiNS name ${t}`);n=r.split(".").slice(0,-1)}return e==="dot"?`${n.join(".")}.sui`:`${n.slice(0,-1).join(".")}@${n[n.length-1]}`}const o3=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,a3=/^\d+$/,c3=64,av="/",Vt=t=>{const e=t.split(av);if(e.length<2||e.length>3)return!1;const[r,n,s]=e;return s!==void 0&&!a3.test(s)||!s3(r)?!1:o3.test(n)&&n.length<c3},u3=t=>{const e=t.split(/::|<|>|,/);for(const r of e)if(r.includes(av)&&!Vt(r))return!1;return!0},l3=32;function sm(t){try{return na(t).length===l3}catch{return!1}}const Iu=32;function wr(t){return d3(t)&&h3(t)===Iu}function nc(t){return wr(t)}function f3(t){return t.includes("::")?Ks(t):t}function Ks(t){const[e,r]=t.split("::"),n=Vt(e),s=t.slice(e.length+r.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,o=s.includes("<")?W1(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(a=>f3(a.trim())):[];return{address:n?e:we(e),module:r,name:i,typeParams:o}}function Rc(t){const{address:e,module:r,name:n,typeParams:s}=typeof t=="string"?Ks(t):t,i=(s==null?void 0:s.length)>0?`<${s.map(o=>typeof o=="string"?o:Rc(o)).join(",")}>`:"";return`${e}::${r}::${n}${i}`}function we(t,e=!1){let r=t.toLowerCase();return!e&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(Iu*2,"0")}`}function Jr(t,e=!1){return we(t,e)}function d3(t){return/^(0x|0X)?[a-fA-F0-9]+$/.test(t)&&t.length%2===0}function h3(t){return/^(0x|0X)/.test(t)?(t.length-2)/2:t.length/2}function ri(t){const e=Object.entries(t).map(([r,n])=>de({[r]:n}));return ft(rn(e),Pu(r=>({...r,$kind:Object.keys(r)[0]})))}const Zi=ft(xe(),Pu(t=>we(t)),op(wr)),Yt=Zi,Xs=xe(),Dt=ft(rn([xe(),ft(Ut(),jt())]),op(t=>{try{return BigInt(t),BigInt(t)>=0&&BigInt(t)<=18446744073709551615n}catch{return!1}},"Invalid u64")),ls=de({objectId:Zi,version:Dt,digest:xe()}),Re=ft(rn([de({GasCoin:rt(!0)}),de({Input:ft(Ut(),jt()),type:Kt(rt("pure"))}),de({Input:ft(Ut(),jt()),type:Kt(rt("object"))}),de({Result:ft(Ut(),jt())}),de({NestedResult:ap([ft(Ut(),jt()),ft(Ut(),jt())])})]),Pu(t=>({...t,$kind:Object.keys(t)[0]}))),p3=de({budget:Ge(Dt),price:Ge(Dt),owner:Ge(Zi),payment:Ge(Se(ls))}),Cd=rn([rt("address"),rt("bool"),rt("u8"),rt("u16"),rt("u32"),rt("u64"),rt("u128"),rt("u256"),de({vector:Bd(()=>Cd)}),de({datatype:de({package:xe(),module:xe(),type:xe(),typeParameters:Se(Bd(()=>Cd))})}),de({typeParameter:ft(Ut(),jt())})]),y3=de({ref:Ge(rn([rt("&"),rt("&mut")])),body:Cd}),m3=de({package:Yt,module:xe(),function:xe(),typeArguments:Se(xe()),arguments:Se(Re),_argumentTypes:Kt(Ge(Se(y3)))}),b3=de({name:xe(),inputs:ia(xe(),rn([Re,Se(Re)])),data:ia(xe(),Na())}),g3=ri({MoveCall:m3,TransferObjects:de({objects:Se(Re),address:Re}),SplitCoins:de({coin:Re,amounts:Se(Re)}),MergeCoins:de({destination:Re,sources:Se(Re)}),Publish:de({modules:Se(Xs),dependencies:Se(Yt)}),MakeMoveVec:de({type:Ge(xe()),elements:Se(Re)}),Upgrade:de({modules:Se(Xs),dependencies:Se(Yt),package:Yt,ticket:Re}),$Intent:b3}),cv=ri({ImmOrOwnedObject:ls,SharedObject:de({objectId:Yt,initialSharedVersion:Dt,mutable:Ji()}),Receiving:ls}),w3=ri({Object:cv,Pure:de({bytes:Xs}),UnresolvedPure:de({value:Na()}),UnresolvedObject:de({objectId:Yt,version:Kt(Ge(Dt)),digest:Kt(Ge(xe())),initialSharedVersion:Kt(Ge(Dt)),mutable:Kt(Ge(Ji()))})}),im=ri({Object:cv,Pure:de({bytes:Xs})}),uv=ri({None:rt(!0),Epoch:Dt}),pc=de({version:rt(2),sender:sa(Zi),expiration:sa(uv),gasData:p3,inputs:Se(w3),commands:Se(g3)}),vs={MoveCall(t){const[e,r="",n=""]="target"in t?t.target.split("::"):[t.package,t.module,t.function];return{$kind:"MoveCall",MoveCall:{package:e,module:r,function:n,typeArguments:t.typeArguments??[],arguments:t.arguments??[]}}},TransferObjects(t,e){return{$kind:"TransferObjects",TransferObjects:{objects:t.map(r=>De(Re,r)),address:De(Re,e)}}},SplitCoins(t,e){return{$kind:"SplitCoins",SplitCoins:{coin:De(Re,t),amounts:e.map(r=>De(Re,r))}}},MergeCoins(t,e){return{$kind:"MergeCoins",MergeCoins:{destination:De(Re,t),sources:e.map(r=>De(Re,r))}}},Publish({modules:t,dependencies:e}){return{$kind:"Publish",Publish:{modules:t.map(r=>typeof r=="string"?r:mt(new Uint8Array(r))),dependencies:e.map(r=>Jr(r))}}},Upgrade({modules:t,dependencies:e,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:t.map(s=>typeof s=="string"?s:mt(new Uint8Array(s))),dependencies:e.map(s=>Jr(s)),package:r,ticket:De(Re,n)}}},MakeMoveVec({type:t,elements:e}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:t??null,elements:e.map(r=>De(Re,r))}}},Intent({name:t,inputs:e={},data:r={}}){return{$kind:"$Intent",$Intent:{name:t,inputs:Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>De(Re,i)):De(Re,s)])),data:r}}}},v3=/^vector<(.+)>$/,E3=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class vr{static parseFromStr(e,r=!1){if(e==="address")return{address:null};if(e==="bool")return{bool:null};if(e==="u8")return{u8:null};if(e==="u16")return{u16:null};if(e==="u32")return{u32:null};if(e==="u64")return{u64:null};if(e==="u128")return{u128:null};if(e==="u256")return{u256:null};if(e==="signer")return{signer:null};const n=e.match(v3);if(n)return{vector:vr.parseFromStr(n[1],r)};const s=e.match(E3);if(s)return{struct:{address:r?we(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:vr.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,r=!1){return W1(e).map(n=>vr.parseFromStr(n,r))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${vr.tagToString(e.vector)}>`;if("struct"in e){const r=e.struct,n=r.typeParams.map(vr.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function S3(t){return I.u64({name:"unsafe_u64",...t}).transform({input:e=>e,output:e=>Number(e)})}function A3(t){return I.enum("Option",{None:null,Some:t})}const Me=I.bytes(Iu).transform({validate:t=>{const e=typeof t=="string"?t:Di(t);if(!e||!wr(we(e)))throw new Error(`Invalid Sui address ${e}`)},input:t=>typeof t=="string"?V1(we(t)):t,output:t=>we(Di(t))}),Ar=I.byteVector().transform({name:"ObjectDigest",input:t=>na(t),output:t=>Tu(new Uint8Array(t)),validate:t=>{if(na(t).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),cr=I.struct("SuiObjectRef",{objectId:Me,version:I.u64(),digest:Ar}),lv=I.struct("SharedObjectRef",{objectId:Me,initialSharedVersion:I.u64(),mutable:I.bool()}),fv=I.enum("ObjectArg",{ImmOrOwnedObject:cr,SharedObject:lv,Receiving:cr}),_s=I.enum("Owner",{AddressOwner:Me,ObjectOwner:Me,Shared:I.struct("Shared",{initialSharedVersion:I.u64()}),Immutable:null,ConsensusAddressOwner:I.struct("ConsensusAddressOwner",{owner:Me,startVersion:I.u64()})}),dv=I.enum("CallArg",{Pure:I.struct("Pure",{bytes:I.byteVector().transform({input:t=>typeof t=="string"?Xt(t):t,output:t=>mt(new Uint8Array(t))})}),Object:fv}),cp=I.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:I.lazy(()=>cp),struct:I.lazy(()=>gv),u16:null,u32:null,u256:null}),up=cp.transform({input:t=>typeof t=="string"?vr.parseFromStr(t,!0):t,output:t=>vr.tagToString(t)}),Kr=I.enum("Argument",{GasCoin:null,Input:I.u16(),Result:I.u16(),NestedResult:I.tuple([I.u16(),I.u16()])}),hv=I.struct("ProgrammableMoveCall",{package:Me,module:I.string(),function:I.string(),typeArguments:I.vector(up),arguments:I.vector(Kr)}),pv=I.enum("Command",{MoveCall:hv,TransferObjects:I.struct("TransferObjects",{objects:I.vector(Kr),address:Kr}),SplitCoins:I.struct("SplitCoins",{coin:Kr,amounts:I.vector(Kr)}),MergeCoins:I.struct("MergeCoins",{destination:Kr,sources:I.vector(Kr)}),Publish:I.struct("Publish",{modules:I.vector(I.byteVector().transform({input:t=>typeof t=="string"?Xt(t):t,output:t=>mt(new Uint8Array(t))})),dependencies:I.vector(Me)}),MakeMoveVec:I.struct("MakeMoveVec",{type:A3(up).transform({input:t=>t===null?{None:!0}:{Some:t},output:t=>t.Some??null}),elements:I.vector(Kr)}),Upgrade:I.struct("Upgrade",{modules:I.vector(I.byteVector().transform({input:t=>typeof t=="string"?Xt(t):t,output:t=>mt(new Uint8Array(t))})),dependencies:I.vector(Me),package:Me,ticket:Kr})}),yv=I.struct("ProgrammableTransaction",{inputs:I.vector(dv),commands:I.vector(pv)}),mv=I.enum("TransactionKind",{ProgrammableTransaction:yv,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),bv=I.enum("TransactionExpiration",{None:null,Epoch:S3()}),gv=I.struct("StructTag",{address:Me,module:I.string(),name:I.string(),typeParams:I.vector(cp)}),wv=I.struct("GasData",{payment:I.vector(cr),owner:Me,price:I.u64(),budget:I.u64()}),vv=I.struct("TransactionDataV1",{kind:mv,sender:Me,gasData:wv,expiration:bv}),Ev=I.enum("TransactionData",{V1:vv}),Sv=I.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),Av=I.enum("IntentVersion",{V0:null}),kv=I.enum("AppId",{Sui:null}),xv=I.struct("Intent",{scope:Sv,version:Av,appId:kv});function Tv(t){return I.struct(`IntentMessage<${t.name}>`,{intent:xv,value:t})}const _v=I.enum("CompressedSignature",{ED25519:I.bytes(64),Secp256k1:I.bytes(64),Secp256r1:I.bytes(64),ZkLogin:I.byteVector(),Passkey:I.byteVector()}),Pv=I.enum("PublicKey",{ED25519:I.bytes(32),Secp256k1:I.bytes(33),Secp256r1:I.bytes(33),ZkLogin:I.byteVector(),Passkey:I.bytes(33)}),Ov=I.struct("MultiSigPkMap",{pubKey:Pv,weight:I.u8()}),Iv=I.struct("MultiSigPublicKey",{pk_map:I.vector(Ov),threshold:I.u16()}),k3=I.struct("MultiSig",{sigs:I.vector(_v),bitmap:I.u16(),multisig_pk:Iv}),x3=I.byteVector().transform({input:t=>typeof t=="string"?Xt(t):t,output:t=>mt(new Uint8Array(t))}),Bv=I.struct("SenderSignedTransaction",{intentMessage:Tv(Ev),txSignatures:I.vector(x3)}),T3=I.vector(Bv,{name:"SenderSignedData"}),_3=I.struct("PasskeyAuthenticator",{authenticatorData:I.byteVector(),clientDataJson:I.string(),userSignature:I.byteVector()}),P3=I.enum("PackageUpgradeError",{UnableToFetchPackage:I.struct("UnableToFetchPackage",{packageId:Me}),NotAPackage:I.struct("NotAPackage",{objectId:Me}),IncompatibleUpgrade:null,DigestDoesNotMatch:I.struct("DigestDoesNotMatch",{digest:I.byteVector()}),UnknownUpgradePolicy:I.struct("UnknownUpgradePolicy",{policy:I.u8()}),PackageIDDoesNotMatch:I.struct("PackageIDDoesNotMatch",{packageId:Me,ticketId:Me})}),O3=I.struct("ModuleId",{address:Me,name:I.string()}),om=I.struct("MoveLocation",{module:O3,function:I.u16(),instruction:I.u16(),functionName:I.option(I.string())}),I3=I.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:I.struct("IndexOutOfBounds",{idx:I.u16()}),SecondaryIndexOutOfBounds:I.struct("SecondaryIndexOutOfBounds",{resultIdx:I.u16(),secondaryIdx:I.u16()}),InvalidResultArity:I.struct("InvalidResultArity",{resultIdx:I.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),B3=I.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),C3=I.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:I.struct("MoveObjectTooBig",{objectSize:I.u64(),maxObjectSize:I.u64()}),MovePackageTooBig:I.struct("MovePackageTooBig",{objectSize:I.u64(),maxObjectSize:I.u64()}),CircularObjectOwnership:I.struct("CircularObjectOwnership",{object:Me}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:I.option(om),MoveAbort:I.tuple([om,I.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:I.struct("CommandArgumentError",{argIdx:I.u16(),kind:I3}),TypeArgumentError:I.struct("TypeArgumentError",{argumentIdx:I.u16(),kind:B3}),UnusedValueWithoutDrop:I.struct("UnusedValueWithoutDrop",{resultIdx:I.u16(),secondaryIdx:I.u16()}),InvalidPublicFunctionReturnType:I.struct("InvalidPublicFunctionReturnType",{idx:I.u16()}),InvalidTransferObject:null,EffectsTooLarge:I.struct("EffectsTooLarge",{currentSize:I.u64(),maxSize:I.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:I.struct("PackageUpgradeError",{upgradeError:P3}),WrittenObjectsTooLarge:I.struct("WrittenObjectsTooLarge",{currentSize:I.u64(),maxSize:I.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:I.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:I.vector(Me)}),AddressDeniedForCoin:I.struct("AddressDeniedForCoin",{address:Me,coinType:I.string()}),CoinTypeGlobalPause:I.struct("CoinTypeGlobalPause",{coinType:I.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),Cv=I.enum("ExecutionStatus",{Success:null,Failed:I.struct("ExecutionFailed",{error:C3,command:I.option(I.u64())})}),Nv=I.struct("GasCostSummary",{computationCost:I.u64(),storageCost:I.u64(),storageRebate:I.u64(),nonRefundableStorageFee:I.u64()}),N3=I.struct("TransactionEffectsV1",{status:Cv,executedEpoch:I.u64(),gasUsed:Nv,modifiedAtVersions:I.vector(I.tuple([Me,I.u64()])),sharedObjects:I.vector(cr),transactionDigest:Ar,created:I.vector(I.tuple([cr,_s])),mutated:I.vector(I.tuple([cr,_s])),unwrapped:I.vector(I.tuple([cr,_s])),deleted:I.vector(cr),unwrappedThenDeleted:I.vector(cr),wrapped:I.vector(cr),gasObject:I.tuple([cr,_s]),eventsDigest:I.option(Ar),dependencies:I.vector(Ar)}),lp=I.tuple([I.u64(),Ar]),R3=I.enum("ObjectIn",{NotExist:null,Exist:I.tuple([lp,_s])}),M3=I.enum("ObjectOut",{NotExist:null,ObjectWrite:I.tuple([Ar,_s]),PackageWrite:lp}),j3=I.enum("IDOperation",{None:null,Created:null,Deleted:null}),U3=I.struct("EffectsObjectChange",{inputState:R3,outputState:M3,idOperation:j3}),F3=I.enum("UnchangedSharedKind",{ReadOnlyRoot:lp,MutateDeleted:I.u64(),ReadDeleted:I.u64(),Cancelled:I.u64(),PerEpochConfig:null}),$3=I.struct("TransactionEffectsV2",{status:Cv,executedEpoch:I.u64(),gasUsed:Nv,transactionDigest:Ar,gasObjectIndex:I.option(I.u32()),eventsDigest:I.option(Ar),dependencies:I.vector(Ar),lamportVersion:I.u64(),changedObjects:I.vector(I.tuple([Me,U3])),unchangedSharedObjects:I.vector(I.tuple([Me,F3])),auxDataDigest:I.option(Ar)}),L3=I.enum("TransactionEffects",{V1:N3,V2:$3});function xo(t){switch(t){case"u8":return I.u8();case"u16":return I.u16();case"u32":return I.u32();case"u64":return I.u64();case"u128":return I.u128();case"u256":return I.u256();case"bool":return I.bool();case"string":return I.string();case"id":case"address":return Me}const e=t.match(/^(vector|option)<(.+)>$/);if(e){const[r,n]=e.slice(1);return r==="vector"?I.vector(xo(n)):I.option(xo(n))}throw new Error(`Invalid Pure type name: ${t}`)}const he={...I,U8:I.u8(),U16:I.u16(),U32:I.u32(),U64:I.u64(),U128:I.u128(),U256:I.u256(),ULEB128:I.uleb128(),Bool:I.bool(),String:I.string(),Address:Me,AppId:kv,Argument:Kr,CallArg:dv,Command:pv,CompressedSignature:_v,GasData:wv,Intent:xv,IntentMessage:Tv,IntentScope:Sv,IntentVersion:Av,MultiSig:k3,MultiSigPkMap:Ov,MultiSigPublicKey:Iv,ObjectArg:fv,ObjectDigest:Ar,Owner:_s,PasskeyAuthenticator:_3,ProgrammableMoveCall:hv,ProgrammableTransaction:yv,PublicKey:Pv,SenderSignedData:T3,SenderSignedTransaction:Bv,SharedObjectRef:lv,StructTag:gv,SuiObjectRef:cr,TransactionData:Ev,TransactionDataV1:vv,TransactionEffects:L3,TransactionExpiration:bv,TransactionKind:mv,TypeTag:up},am=de({digest:xe(),objectId:xe(),version:rn([ft(Ut(),jt()),xe(),sv()])}),D3=ri({ImmOrOwned:am,Shared:de({objectId:Yt,initialSharedVersion:Dt,mutable:Ji()}),Receiving:am}),cm=ri({Object:D3,Pure:Se(ft(Ut(),jt()))});function um(t){var r;const e=t.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(Xt(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:t.sender??void 0,expiration:((r=t.expiration)==null?void 0:r.$kind)==="Epoch"?{Epoch:Number(t.expiration.Epoch)}:t.expiration?{None:!0}:null,gasConfig:{owner:t.gasData.owner??void 0,budget:t.gasData.budget??void 0,price:t.gasData.price??void 0,payment:t.gasData.payment??void 0},inputs:e,transactions:t.commands.map(n=>{if(n.MakeMoveVec)return{kind:"MakeMoveVec",type:n.MakeMoveVec.type===null?{None:!0}:{Some:vr.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>dn(s,e))};if(n.MergeCoins)return{kind:"MergeCoins",destination:dn(n.MergeCoins.destination,e),sources:n.MergeCoins.sources.map(s=>dn(s,e))};if(n.MoveCall)return{kind:"MoveCall",target:`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,typeArguments:n.MoveCall.typeArguments,arguments:n.MoveCall.arguments.map(s=>dn(s,e))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(Xt(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:dn(n.SplitCoins.coin,e),amounts:n.SplitCoins.amounts.map(s=>dn(s,e))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>dn(s,e)),address:dn(n.TransferObjects.address,e)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(Xt(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:dn(n.Upgrade.ticket,e)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function dn(t,e){if(t.$kind==="GasCoin")return{kind:"GasCoin"};if(t.$kind==="Result")return{kind:"Result",index:t.Result};if(t.$kind==="NestedResult")return{kind:"NestedResult",index:t.NestedResult[0],resultIndex:t.NestedResult[1]};if(t.$kind==="Input")return e[t.Input];throw new Error(`Invalid argument ${Object.keys(t)}`)}function H3(t){var e,r,n;return De(pc,{version:2,sender:t.sender??null,expiration:t.expiration?"Epoch"in t.expiration?{Epoch:t.expiration.Epoch}:{None:!0}:null,gasData:{owner:t.gasConfig.owner??null,budget:((e=t.gasConfig.budget)==null?void 0:e.toString())??null,price:((r=t.gasConfig.price)==null?void 0:r.toString())??null,payment:((n=t.gasConfig.payment)==null?void 0:n.map(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:t.inputs.map(s=>{if(s.kind==="Input"){if(Id(cm,s.value)){const i=De(cm,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:mt(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:t.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?vr.tagToString(s.type.Some):null,elements:s.objects.map(i=>hn(i))}};case"MergeCoins":return{MergeCoins:{destination:hn(s.destination),sources:s.sources.map(i=>hn(i))}};case"MoveCall":{const[i,o,a]=s.target.split("::");return{MoveCall:{package:i,module:o,function:a,typeArguments:s.typeArguments,arguments:s.arguments.map(c=>hn(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>mt(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:hn(s.coin),amounts:s.amounts.map(i=>hn(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>hn(i)),address:hn(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>mt(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:hn(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function hn(t){switch(t.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:t.index};case"NestedResult":return{NestedResult:[t.index,t.resultIndex]};case"Input":return{Input:t.index}}}function Ra(t){return rn(Object.entries(t).map(([e,r])=>de({[e]:r})))}const yr=Ra({GasCoin:rt(!0),Input:ft(Ut(),jt()),Result:ft(Ut(),jt()),NestedResult:ap([ft(Ut(),jt()),ft(Ut(),jt())])}),z3=de({budget:Ge(Dt),price:Ge(Dt),owner:Ge(Zi),payment:Ge(Se(ls))}),V3=de({package:Yt,module:xe(),function:xe(),typeArguments:Se(xe()),arguments:Se(yr)}),G3=de({name:xe(),inputs:ia(xe(),rn([yr,Se(yr)])),data:ia(xe(),Na())}),q3=Ra({MoveCall:V3,TransferObjects:de({objects:Se(yr),address:yr}),SplitCoins:de({coin:yr,amounts:Se(yr)}),MergeCoins:de({destination:yr,sources:Se(yr)}),Publish:de({modules:Se(Xs),dependencies:Se(Yt)}),MakeMoveVec:de({type:Ge(xe()),elements:Se(yr)}),Upgrade:de({modules:Se(Xs),dependencies:Se(Yt),package:Yt,ticket:yr}),$Intent:G3}),W3=Ra({ImmOrOwnedObject:ls,SharedObject:de({objectId:Yt,initialSharedVersion:Dt,mutable:Ji()}),Receiving:ls}),K3=Ra({Object:W3,Pure:de({bytes:Xs}),UnresolvedPure:de({value:Na()}),UnresolvedObject:de({objectId:Yt,version:Kt(Ge(Dt)),digest:Kt(Ge(xe())),initialSharedVersion:Kt(Ge(Dt)),mutable:Kt(Ge(Ji()))})}),X3=Ra({None:rt(!0),Epoch:Dt}),Y3=de({version:rt(2),sender:sa(Zi),expiration:sa(X3),gasData:z3,inputs:Se(K3),commands:Se(q3),digest:Kt(Ge(xe()))});function J3(t){return{$kind:"Pure",Pure:{bytes:t instanceof Uint8Array?mt(t):t.toBase64()}}}const kr={Pure:J3,ObjectRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:e,version:r,objectId:we(t)}}}},SharedObjectRef({objectId:t,mutable:e,initialSharedVersion:r}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:e,initialSharedVersion:r,objectId:we(t)}}}},ReceivingRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:e,version:r,objectId:we(t)}}}}};BigInt(1e9);const Z3="0x1",Rv="0x2",Q3=Jr("0x6"),eI=`${Rv}::sui::SUI`;Jr("0x5");Jr("0x8");const tI=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),et=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),re=new Uint32Array(32);function zn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=re[2*t],u=re[2*t+1],l=re[2*e],f=re[2*e+1],h=re[2*r],d=re[2*r+1],p=re[2*n],m=re[2*n+1],v=Ym(c,l,o);u=Jm(v,u,f,a),c=v|0,{Dh:m,Dl:p}={Dh:m^u,Dl:p^c},{Dh:m,Dl:p}={Dh:T6(m,p),Dl:_6(m)},{h:d,l:h}=Xm(d,h,m,p),{Bh:f,Bl:l}={Bh:f^d,Bl:l^h},{Bh:f,Bl:l}={Bh:Wm(f,l,24),Bl:Km(f,l,24)},re[2*t]=c,re[2*t+1]=u,re[2*e]=l,re[2*e+1]=f,re[2*r]=h,re[2*r+1]=d,re[2*n]=p,re[2*n+1]=m}function Vn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=re[2*t],u=re[2*t+1],l=re[2*e],f=re[2*e+1],h=re[2*r],d=re[2*r+1],p=re[2*n],m=re[2*n+1],v=Ym(c,l,o);u=Jm(v,u,f,a),c=v|0,{Dh:m,Dl:p}={Dh:m^u,Dl:p^c},{Dh:m,Dl:p}={Dh:Wm(m,p,16),Dl:Km(m,p,16)},{h:d,l:h}=Xm(d,h,m,p),{Bh:f,Bl:l}={Bh:f^d,Bl:l^h},{Bh:f,Bl:l}={Bh:k6(f,l,63),Bl:x6(f,l,63)},re[2*t]=c,re[2*t+1]=u,re[2*e]=l,re[2*e+1]=f,re[2*r]=h,re[2*r+1]=d,re[2*n]=p,re[2*n+1]=m}function rI(t,e={},r,n,s){if(ss(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class nI extends Lc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ss(e),ss(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=Oo(this.buffer)}update(e){os(this),e=Sn(e),is(e);const{blockLen:r,buffer:n,buffer32:s}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===r&&(Kn(s),this.compress(s,0,!1),Kn(s),this.pos=0);const u=Math.min(r-this.pos,i-c),l=o+c;if(u===r&&!(l%4)&&c+u<i){const f=new Uint32Array(a,l,Math.floor((i-c)/4));Kn(f);for(let h=0;c+r<i;h+=s.length,c+=r)this.length+=r,this.compress(f,h,!1);Kn(f);continue}n.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){os(this),zd(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,Pr(this.buffer.subarray(r)),Kn(n),this.compress(n,0,!0),Kn(n);const s=Oo(e);this.get().forEach((i,o)=>s[o]=pn(i))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:s,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=i,e.finished=s,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class sI extends nI{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=et[0]|0,this.v0h=et[1]|0,this.v1l=et[2]|0,this.v1h=et[3]|0,this.v2l=et[4]|0,this.v2h=et[5]|0,this.v3l=et[6]|0,this.v3h=et[7]|0,this.v4l=et[8]|0,this.v4h=et[9]|0,this.v5l=et[10]|0,this.v5h=et[11]|0,this.v6l=et[12]|0,this.v6h=et[13]|0,this.v7l=et[14]|0,this.v7h=et[15]|0,rI(r,e,64,16,16);let{key:n,personalization:s,salt:i}=e,o=0;if(n!==void 0&&(n=Sn(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=Sn(i);const a=Oo(i);this.v4l^=pn(a[0]),this.v4h^=pn(a[1]),this.v5l^=pn(a[2]),this.v5h^=pn(a[3])}if(s!==void 0){s=Sn(s);const a=Oo(s);this.v6l^=pn(a[0]),this.v6h^=pn(a[1]),this.v7l^=pn(a[2]),this.v7h^=pn(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:n,v1h:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:f,v5h:h,v6l:d,v6h:p,v7l:m,v7h:v}=this;return[e,r,n,s,i,o,a,c,u,l,f,h,d,p,m,v]}set(e,r,n,s,i,o,a,c,u,l,f,h,d,p,m,v){this.v0l=e|0,this.v0h=r|0,this.v1l=n|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=f|0,this.v5h=h|0,this.v6l=d|0,this.v6h=p|0,this.v7l=m|0,this.v7h=v|0}compress(e,r,n){this.get().forEach((c,u)=>re[u]=c),re.set(et,16);let{h:s,l:i}=qm(BigInt(this.length));re[24]=et[8]^i,re[25]=et[9]^s,n&&(re[28]=~re[28],re[29]=~re[29]);let o=0;const a=tI;for(let c=0;c<12;c++)zn(0,4,8,12,e,r+2*a[o++]),Vn(0,4,8,12,e,r+2*a[o++]),zn(1,5,9,13,e,r+2*a[o++]),Vn(1,5,9,13,e,r+2*a[o++]),zn(2,6,10,14,e,r+2*a[o++]),Vn(2,6,10,14,e,r+2*a[o++]),zn(3,7,11,15,e,r+2*a[o++]),Vn(3,7,11,15,e,r+2*a[o++]),zn(0,5,10,15,e,r+2*a[o++]),Vn(0,5,10,15,e,r+2*a[o++]),zn(1,6,11,12,e,r+2*a[o++]),Vn(1,6,11,12,e,r+2*a[o++]),zn(2,7,8,13,e,r+2*a[o++]),Vn(2,7,8,13,e,r+2*a[o++]),zn(3,4,9,14,e,r+2*a[o++]),Vn(3,4,9,14,e,r+2*a[o++]);this.v0l^=re[0]^re[16],this.v0h^=re[1]^re[17],this.v1l^=re[2]^re[18],this.v1h^=re[3]^re[19],this.v2l^=re[4]^re[20],this.v2h^=re[5]^re[21],this.v3l^=re[6]^re[22],this.v3h^=re[7]^re[23],this.v4l^=re[8]^re[24],this.v4h^=re[9]^re[25],this.v5l^=re[10]^re[26],this.v5h^=re[11]^re[27],this.v6l^=re[12]^re[28],this.v6h^=re[13]^re[29],this.v7l^=re[14]^re[30],this.v7h^=re[15]^re[31],Pr(re)}destroy(){this.destroyed=!0,Pr(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const iI=U6(t=>new sI(t)),Mv=iI;function oI(t,e,r){const n=he.Address.serialize(t).toBytes(),s=he.TypeTag.serialize(e).toBytes(),i=he.u64().serialize(r.length).toBytes(),o=Mv.create({dkLen:32});return o.update(new Uint8Array([240])),o.update(n),o.update(i),o.update(r),o.update(s),`0x${Di(o.digest().slice(0,32))}`}const aI="object",cI="ID",uI="ascii",lI="String",fI="string",dI="String",hI="option",pI="Option";function yI(t){const e=typeof t.body=="object"&&"datatype"in t.body?t.body.datatype:null;return!!e&&we(e.package)===we("0x2")&&e.module==="tx_context"&&e.type==="TxContext"}function Nd(t){if(typeof t=="string")switch(t){case"address":return he.Address;case"bool":return he.Bool;case"u8":return he.U8;case"u16":return he.U16;case"u32":return he.U32;case"u64":return he.U64;case"u128":return he.U128;case"u256":return he.U256;default:throw new Error(`Unknown type signature ${t}`)}if("vector"in t){if(t.vector==="u8")return he.byteVector().transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const e=Nd(t.vector);return e?he.vector(e):null}if("datatype"in t){const e=we(t.datatype.package);if(e===we(Z3)){if(t.datatype.module===uI&&t.datatype.type===lI||t.datatype.module===fI&&t.datatype.type===dI)return he.String;if(t.datatype.module===hI&&t.datatype.type===pI){const r=Nd(t.datatype.typeParameters[0]);return r?he.vector(r):null}}if(e===we(Rv)&&t.datatype.module===aI&&t.datatype.type===cI)return he.Address}return null}function mI(t){return typeof t=="object"&&"Reference"in t?{ref:"&",body:To(t.Reference)}:typeof t=="object"&&"MutableReference"in t?{ref:"&mut",body:To(t.MutableReference)}:{ref:null,body:To(t)}}function To(t){if(typeof t=="string")switch(t){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${t}`)}if("Vector"in t)return{vector:To(t.Vector)};if("Struct"in t)return{datatype:{package:t.Struct.address,module:t.Struct.module,type:t.Struct.name,typeParameters:t.Struct.typeArguments.map(To)}};if("TypeParameter"in t)return{typeParameter:t.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(t)}`)}const bI=50,gI=1000n,wI=5e10;function jv(t){return async function(r,n,s){return await kI(r,t),await AI(r,t),n.onlyTransactionKind||(await vI(r,t),await EI(r,t),await SI(r,t)),await s()}}async function vI(t,e){t.gasConfig.price||(t.gasConfig.price=String(await e.getReferenceGasPrice()))}async function EI(t,e){if(t.gasConfig.budget)return;const r=await e.dryRunTransactionBlock({transactionBlock:t.build({overrides:{gasData:{budget:String(wI),payment:[]}}})});if(r.effects.status.status!=="success")throw new Error(`Dry run failed, could not automatically determine a budget: ${r.effects.status.error}`,{cause:r});const n=gI*BigInt(t.gasConfig.price||1n),s=BigInt(r.effects.gasUsed.computationCost)+n,i=s+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);t.gasConfig.budget=String(i>s?i:s)}async function SI(t,e){if(!t.gasConfig.payment){const n=(await e.getCoins({owner:t.gasConfig.owner||t.sender,coinType:eI})).data.filter(s=>!t.inputs.find(o=>{var a;return(a=o.Object)!=null&&a.ImmOrOwnedObject?s.coinObjectId===o.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");t.gasConfig.payment=n.map(s=>De(ls,s))}}async function AI(t,e){const r=t.inputs.filter(l=>{var f;return l.UnresolvedObject&&!(l.UnresolvedObject.version||(f=l.UnresolvedObject)!=null&&f.initialSharedVersion)}),n=[...new Set(r.map(l=>Jr(l.UnresolvedObject.objectId)))],s=n.length?_u(n,bI):[],i=(await Promise.all(s.map(l=>e.multiGetObjects({ids:l,options:{showOwner:!0}})))).flat(),o=new Map(n.map((l,f)=>[l,i[f]])),a=Array.from(o).filter(([l,f])=>f.error).map(([l,f])=>JSON.stringify(f.error));if(a.length)throw new Error(`The following input objects are invalid: ${a.join(", ")}`);const c=i.map(l=>{if(l.error||!l.data)throw new Error(`Failed to fetch object: ${l.error}`);const f=l.data.owner,h=f&&typeof f=="object"?"Shared"in f?f.Shared.initial_shared_version:"ConsensusAddressOwner"in f?f.ConsensusAddressOwner.start_version:null:null;return{objectId:l.data.objectId,digest:l.data.digest,version:l.data.version,initialSharedVersion:h}}),u=new Map(n.map((l,f)=>[l,c[f]]));for(const[l,f]of t.inputs.entries()){if(!f.UnresolvedObject)continue;let h;const d=we(f.UnresolvedObject.objectId),p=u.get(d);f.UnresolvedObject.initialSharedVersion??(p==null?void 0:p.initialSharedVersion)?h=kr.SharedObjectRef({objectId:d,initialSharedVersion:f.UnresolvedObject.initialSharedVersion||(p==null?void 0:p.initialSharedVersion),mutable:f.UnresolvedObject.mutable||xI(t,l)}):TI(t,l)&&(h=kr.ReceivingRef({objectId:d,digest:f.UnresolvedObject.digest??(p==null?void 0:p.digest),version:f.UnresolvedObject.version??(p==null?void 0:p.version)})),t.inputs[t.inputs.indexOf(f)]=h??kr.ObjectRef({objectId:d,digest:f.UnresolvedObject.digest??(p==null?void 0:p.digest),version:f.UnresolvedObject.version??(p==null?void 0:p.version)})}}async function kI(t,e){const{inputs:r,commands:n}=t,s=[],i=new Set;n.forEach(a=>{if(a.MoveCall){if(a.MoveCall._argumentTypes)return;if(a.MoveCall.arguments.map(l=>l.$kind==="Input"?t.inputs[l.Input]:null).some(l=>(l==null?void 0:l.UnresolvedPure)||(l==null?void 0:l.UnresolvedObject)&&typeof(l==null?void 0:l.UnresolvedObject.mutable)!="boolean")){const l=`${a.MoveCall.package}::${a.MoveCall.module}::${a.MoveCall.function}`;i.add(l),s.push(a.MoveCall)}}});const o=new Map;i.size>0&&await Promise.all([...i].map(async a=>{const[c,u,l]=a.split("::"),f=await e.getNormalizedMoveFunction({package:c,module:u,function:l});o.set(a,f.parameters.map(h=>mI(h)))})),s.length&&await Promise.all(s.map(async a=>{const c=o.get(`${a.package}::${a.module}::${a.function}`);if(!c)return;const l=c.length>0&&yI(c.at(-1))?c.slice(0,c.length-1):c;a._argumentTypes=l})),n.forEach(a=>{if(!a.MoveCall)return;const c=a.MoveCall,u=`${c.package}::${c.module}::${c.function}`,l=c._argumentTypes;if(l){if(l.length!==a.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${u}`);l.forEach((f,h)=>{var T,g;const d=c.arguments[h];if(d.$kind!=="Input")return;const p=r[d.Input];if(!p.UnresolvedPure&&!p.UnresolvedObject)return;const m=((T=p.UnresolvedPure)==null?void 0:T.value)??((g=p.UnresolvedObject)==null?void 0:g.objectId),v=Nd(f.body);if(v){d.type="pure",r[r.indexOf(p)]=kr.Pure(v.serialize(m));return}if(typeof m!="string")throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(m,null,2)}`);d.type="object";const S=p.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:m}}:p;r[d.Input]=S})}})}function xI(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=s.MoveCall._argumentTypes[i].ref!=="&"||r}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins"||s.$kind==="TransferObjects")&&(r=!0)}),r}function TI(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=_I(s.MoveCall._argumentTypes[i])||r}}),r}function _I(t){return typeof t.body!="object"||!("datatype"in t.body)?!1:t.body.datatype.package==="0x2"&&t.body.datatype.module==="transfer"&&t.body.datatype.type==="Receiving"}function Uv(t,e){return!!(t.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!e.onlyTransactionKind&&(!t.gasConfig.price||!t.gasConfig.budget||!t.gasConfig.payment))}async function PI(t,e,r){var i;if(II(t),!Uv(t,e))return await lm(t),r();const n=OI(e);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??jv(n))(t,e,async()=>{await lm(t),await r()})}function lm(t){t.inputs.forEach((e,r)=>{if(e.$kind!=="Object"&&e.$kind!=="Pure")throw new Error(`Input at index ${r} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function OI(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}function II(t){for(const e of t.commands)switch(e.$kind){case"SplitCoins":e.SplitCoins.amounts.forEach(r=>{fm(r,he.U64,t)});break;case"TransferObjects":fm(e.TransferObjects.address,he.Address,t);break}}function fm(t,e,r){if(t.$kind!=="Input")return;const n=r.inputs[t.Input];n.$kind==="UnresolvedPure"&&(r.inputs[t.Input]=kr.Pure(e.serialize(n.UnresolvedPure.value)))}function BI(t){function e(r){return t(r)}return e.system=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?kr.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},e.clock=()=>e(kr.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),e.random=()=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x8",mutable:!1}}),e.denyList=r=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",mutable:r==null?void 0:r.mutable}}),e.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),e}function CI(t){function e(r,n){if(typeof r=="string")return t(xo(r).serialize(n));if(r instanceof Uint8Array||ip(r))return t(r);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return e.u8=r=>t(he.U8.serialize(r)),e.u16=r=>t(he.U16.serialize(r)),e.u32=r=>t(he.U32.serialize(r)),e.u64=r=>t(he.U64.serialize(r)),e.u128=r=>t(he.U128.serialize(r)),e.u256=r=>t(he.U256.serialize(r)),e.bool=r=>t(he.Bool.serialize(r)),e.string=r=>t(he.String.serialize(r)),e.address=r=>t(he.Address.serialize(r)),e.id=e.address,e.vector=(r,n)=>t(he.vector(xo(r)).serialize(n)),e.option=(r,n)=>t(he.option(xo(r)).serialize(n)),e}function NI(t,e){const r=Array.from(`${t}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+e.length);return n.set(r),n.set(e,r.length),Mv(n,{dkLen:32})}function Mc(t){if(typeof t=="string")return we(t);if(t.Object)return t.Object.ImmOrOwnedObject?we(t.Object.ImmOrOwnedObject.objectId):t.Object.Receiving?we(t.Object.Receiving.objectId):we(t.Object.SharedObject.objectId);if(t.UnresolvedObject)return we(t.UnresolvedObject.objectId)}function RI(t,e,r){const n=s=>{switch(s.$kind){case"Input":{const i=e.get(s.Input);if(i===void 0)throw new Error(`Input ${s.Input} not found in input mapping`);return{...s,Input:i}}case"Result":{const i=r.get(s.Result);return i!==void 0?{...s,Result:i}:s}case"NestedResult":{const i=r.get(s.NestedResult[0]);return i!==void 0?{...s,NestedResult:[i,s.NestedResult[1]]}:s}default:return s}};switch(t.$kind){case"MoveCall":t.MoveCall.arguments=t.MoveCall.arguments.map(n);break;case"TransferObjects":t.TransferObjects.objects=t.TransferObjects.objects.map(n),t.TransferObjects.address=n(t.TransferObjects.address);break;case"SplitCoins":t.SplitCoins.coin=n(t.SplitCoins.coin),t.SplitCoins.amounts=t.SplitCoins.amounts.map(n);break;case"MergeCoins":t.MergeCoins.destination=n(t.MergeCoins.destination),t.MergeCoins.sources=t.MergeCoins.sources.map(n);break;case"MakeMoveVec":t.MakeMoveVec.elements=t.MakeMoveVec.elements.map(n);break;case"Upgrade":t.Upgrade.ticket=n(t.Upgrade.ticket);break;case"$Intent":{const s=t.$Intent.inputs;t.$Intent.inputs={};for(const[i,o]of Object.entries(s))t.$Intent.inputs[i]=Array.isArray(o)?o.map(n):n(o);break}}}function dm(t){return we(t).replace("0x","")}class Mt{constructor(e){this.version=2,this.sender=(e==null?void 0:e.sender)??null,this.expiration=(e==null?void 0:e.expiration)??null,this.inputs=(e==null?void 0:e.inputs)??[],this.commands=(e==null?void 0:e.commands)??[],this.gasData=(e==null?void 0:e.gasData)??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const n=he.TransactionKind.parse(e).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Mt.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:n.inputs,commands:n.commands})}static fromBytes(e){const r=he.TransactionData.parse(e),n=r==null?void 0:r.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return Mt.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(e){return e.version===2?new Mt(De(pc,e)):new Mt(De(pc,H3(e)))}static getDigestFromBytes(e){const r=NI("TransactionData",e);return Tu(r)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:r,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,o={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return he.TransactionKind.serialize(o,{maxSize:e}).toBytes();const a=(r==null?void 0:r.expiration)??this.expiration,c=(r==null?void 0:r.sender)??this.sender,u={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!u.budget)throw new Error("Missing gas budget");if(!u.payment)throw new Error("Missing gas payment");if(!u.price)throw new Error("Missing gas price");const l={sender:dm(c),expiration:a||{None:!0},gasData:{payment:u.payment,owner:dm(this.gasData.owner??c),price:BigInt(u.price),budget:BigInt(u.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return he.TransactionData.serialize({V1:l},{maxSize:e}).toBytes()}addInput(e,r){const n=this.inputs.length;return this.inputs.push(r),{Input:n,type:e,$kind:"Input"}}getInputUses(e,r){this.mapArguments((n,s)=>(n.$kind==="Input"&&n.Input===e&&r(n,s),n))}mapCommandArguments(e,r){const n=this.commands[e];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(i=>r(i,n,e));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(i=>r(i,n,e)),n.TransferObjects.address=r(n.TransferObjects.address,n,e);break;case"SplitCoins":n.SplitCoins.coin=r(n.SplitCoins.coin,n,e),n.SplitCoins.amounts=n.SplitCoins.amounts.map(i=>r(i,n,e));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,e),n.MergeCoins.sources=n.MergeCoins.sources.map(i=>r(i,n,e));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(i=>r(i,n,e));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,e);break;case"$Intent":const s=n.$Intent.inputs;n.$Intent.inputs={};for(const[i,o]of Object.entries(s))n.$Intent.inputs[i]=Array.isArray(o)?o.map(a=>r(a,n,e)):r(o,n,e);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(e){for(const r of this.commands.keys())this.mapCommandArguments(r,e)}replaceCommand(e,r,n=e){if(!Array.isArray(r)){this.commands[e]=r;return}const s=r.length-1;this.commands.splice(e,1,...structuredClone(r)),this.mapArguments((i,o,a)=>{if(a<e+r.length)return i;if(typeof n!="number"&&(i.$kind==="Result"&&i.Result===e||i.$kind==="NestedResult"&&i.NestedResult[0]===e)){if(!("NestedResult"in i)||i.NestedResult[1]===0)return De(Re,structuredClone(n));throw new Error(`Cannot replace command ${e} with a specific result type: NestedResult[${e}, ${i.NestedResult[1]}] references a nested element that cannot be mapped to the replacement result`)}switch(i.$kind){case"Result":i.Result===e&&typeof n=="number"&&(i.Result=n),i.Result>e&&(i.Result+=s);break;case"NestedResult":if(i.NestedResult[0]===e&&typeof n=="number")return{$kind:"NestedResult",NestedResult:[n,i.NestedResult[1]]};i.NestedResult[0]>e&&(i.NestedResult[0]+=s);break}return i})}replaceCommandWithTransaction(e,r,n){if(n.$kind!=="Result"&&n.$kind!=="NestedResult")throw new Error("Result must be of kind Result or NestedResult");this.insertTransaction(e,r),this.replaceCommand(e+r.commands.length,[],"Result"in n?{NestedResult:[n.Result+e,0]}:{NestedResult:[n.NestedResult[0]+e,n.NestedResult[1]]})}insertTransaction(e,r){var a,c;const n=new Map,s=new Map;for(let u=0;u<r.inputs.length;u++){const l=r.inputs[u],f=Mc(l);let h=-1;if(f!==void 0&&(h=this.inputs.findIndex(d=>Mc(d)===f),h!==-1&&((a=this.inputs[h].Object)!=null&&a.SharedObject)&&((c=l.Object)!=null&&c.SharedObject)&&(this.inputs[h].Object.SharedObject.mutable=this.inputs[h].Object.SharedObject.mutable||l.Object.SharedObject.mutable)),h!==-1)n.set(u,h);else{const d=this.inputs.length;this.inputs.push(l),n.set(u,d)}}for(let u=0;u<r.commands.length;u++)s.set(u,e+u);const i=[];for(let u=0;u<r.commands.length;u++){const l=structuredClone(r.commands[u]);RI(l,n,s),i.push(l)}this.commands.splice(e,0,...i);const o=i.length;o>0&&this.mapArguments((u,l,f)=>{if(f>=e&&f<e+i.length)return u;switch(u.$kind){case"Result":u.Result>=e&&(u.Result+=o);break;case"NestedResult":u.NestedResult[0]>=e&&(u.NestedResult[0]+=o);break}return u})}getDigest(){const e=this.build({onlyTransactionKind:!1});return Mt.getDigestFromBytes(e)}snapshot(){return De(pc,this)}shallowClone(){return new Mt({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}applyResolvedData(e){this.sender||(this.sender=e.sender??null),this.expiration||(this.expiration=e.expiration??null),this.gasData.budget||(this.gasData.budget=e.gasData.budget),this.gasData.owner||(this.gasData.owner=e.gasData.owner??null),this.gasData.payment||(this.gasData.payment=e.gasData.payment),this.gasData.price||(this.gasData.price=e.gasData.price);for(let r=0;r<this.inputs.length;r++){const n=this.inputs[r],s=e.inputs[r];switch(n.$kind){case"UnresolvedPure":if(s.$kind!=="Pure")throw new Error(`Expected input at index ${r} to resolve to a Pure argument, but got ${JSON.stringify(s)}`);this.inputs[r]=s;break;case"UnresolvedObject":if(s.$kind!=="Object")throw new Error(`Expected input at index ${r} to resolve to an Object argument, but got ${JSON.stringify(s)}`);if(s.Object.$kind==="ImmOrOwnedObject"||s.Object.$kind==="Receiving"){const i=n.UnresolvedObject,o=s.Object.ImmOrOwnedObject??s.Object.Receiving;if(we(i.objectId)!==we(o.objectId)||i.version!=null&&i.version!==o.version||i.digest!=null&&i.digest!==o.digest||i.mutable!=null||i.initialSharedVersion!=null)throw new Error(`Input at index ${r} did not match unresolved object. ${JSON.stringify(i)} is not compatible with ${JSON.stringify(o)}`)}else if(s.Object.$kind==="SharedObject"){const i=n.UnresolvedObject,o=s.Object.SharedObject;if(we(i.objectId)!==we(o.objectId)||i.initialSharedVersion!=null&&i.initialSharedVersion!==o.initialSharedVersion||i.mutable!=null&&i.mutable!==o.mutable||i.version!=null||i.digest!=null)throw new Error(`Input at index ${r} did not match unresolved object. ${JSON.stringify(i)} is not compatible with ${JSON.stringify(o)}`)}else throw new Error(`Input at index ${r} resolved to an unexpected Object kind: ${JSON.stringify(s.Object)}`);this.inputs[r]=s;break}}}}var Fv=t=>{throw TypeError(t)},fp=(t,e,r)=>e.has(t)||Fv("Cannot "+r),nt=(t,e,r)=>(fp(t,e,"read from private field"),r?r.call(t):e.get(t)),co=(t,e,r)=>e.has(t)?Fv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),sc=(t,e,r,n)=>(fp(t,e,"write to private field"),e.set(t,r),r),Bu=(t,e,r)=>(fp(t,e,"access private method"),r),oa,Bn,aa,Xn,Yr,Rd,Md,$v,Lv,dp;const MI="/",jI={"Mvr-Source":`@mysten/sui@${B1}`};class UI{constructor({cache:e,url:r,pageSize:n=50,overrides:s}){co(this,Yr),co(this,oa),co(this,Bn),co(this,aa),co(this,Xn),sc(this,oa,e),sc(this,Bn,r),sc(this,aa,n),sc(this,Xn,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),FI(nt(this,Xn))}async resolvePackage({package:e}){return yt(e)?{package:await nt(this,Yr,Rd).load(e)}:{package:e}}async resolveType({type:e}){if(!yt(e))return{type:e};const r=[...jd(e)],n=await nt(this,Yr,Md).loadMany(r),s={};for(let i=0;i<r.length;i++){const o=n[i];if(o instanceof Error)throw o;s[r[i]]=o}return{type:Ud(e,s)}}async resolve({types:e=[],packages:r=[]}){var l,f,h;const n=new Set;for(const d of e??[])jd(d,n);const s=[...n],[i,o]=await Promise.all([s.length>0?nt(this,Yr,Md).loadMany(s):[],r.length>0?nt(this,Yr,Rd).loadMany(r):[]]),a={...(l=nt(this,Xn))==null?void 0:l.types};for(const[d,p]of s.entries()){const m=i[d];if(m instanceof Error)throw m;a[p]=m}const c={};for(const d of e??[]){const p=Ud(d,a);c[d]={type:p}}const u={};for(const[d,p]of(r??[]).entries()){const m=((h=(f=nt(this,Xn))==null?void 0:f.packages)==null?void 0:h[p])??o[d];if(m instanceof Error)throw m;u[p]={package:m}}return{types:c,packages:u}}}oa=new WeakMap;Bn=new WeakMap;aa=new WeakMap;Xn=new WeakMap;Yr=new WeakSet;Rd=function(){return nt(this,oa).readSync(["#mvrPackageDataLoader",nt(this,Bn)??""],()=>{var r;const t=new G1(async n=>{if(!nt(this,Bn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await Bu(this,Yr,$v).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),e=(r=nt(this,Xn))==null?void 0:r.packages;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};Md=function(){return nt(this,oa).readSync(["#mvrTypeDataLoader",nt(this,Bn)??""],()=>{var r;const t=new G1(async n=>{if(!nt(this,Bn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await Bu(this,Yr,Lv).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),e=(r=nt(this,Xn))==null?void 0:r.types;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};$v=async function(t){if(t.length===0)return{};const e=_u(t,nt(this,aa)),r={};return await Promise.all(e.map(async n=>{var i;const s=await Bu(this,Yr,dp).call(this,"/v1/resolution/bulk",{names:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.package_id;a&&(r[o]=a)}})),r};Lv=async function(t){if(t.length===0)return{};const e=_u(t,nt(this,aa)),r={};return await Promise.all(e.map(async n=>{var i;const s=await Bu(this,Yr,dp).call(this,"/v1/struct-definition/bulk",{types:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.type_tag;a&&(r[o]=a)}})),r};dp=async function(t,e){if(!nt(this,Bn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${nt(this,Bn)}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...jI},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(`Failed to resolve types: ${n==null?void 0:n.message}`)}return r.json()};function FI(t){if(t!=null&&t.packages)for(const[e,r]of Object.entries(t.packages)){if(!Vt(e))throw new Error(`Invalid package name: ${e}`);if(!wr(we(r)))throw new Error(`Invalid package ID: ${r}`)}if(t!=null&&t.types)for(const[e,r]of Object.entries(t.types)){if(Ks(e).typeParams.length>0)throw new Error("Type overrides must be first-level only. If you want to supply generic types, just pass each type individually.");const n=Ks(r);if(!wr(n.address))throw new Error(`Invalid type: ${r}`)}}function jd(t,e=new Set){if(typeof t=="string"&&!yt(t))return e;const r=Dv(t)?t:Ks(t);yt(r.address)&&e.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)jd(n,e);return e}function Ud(t,e){const r=Dv(t)?t:Ks(t),n=`${r.address}::${r.module}::${r.name}`,s=e[n];return Rc({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>Ud(i,e))})}function yt(t){return t.includes(MI)||t.includes("@")||t.includes(".sui")}function Dv(t){return typeof t=="object"&&"address"in t&&"module"in t&&"name"in t&&"typeParams"in t}function $I(t){const e=new Set,r=new Set;for(const n of t.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&hm([n.MakeMoveVec.type]).forEach(o=>{r.add(o)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if(yt(i)){if(!Vt(i))throw new Error(`Invalid package name: ${i}`);e.add(i)}hm(s.typeArguments??[]).forEach(o=>{r.add(o)});break}return{packages:[...e],types:[...r]}}function LI(t,e){var r;for(const n of t.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!yt(n.MakeMoveVec.type))continue;if(!e.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=e.types[n.MakeMoveVec.type].type}const s=n.MoveCall;if(!s)continue;const i=s.package.split("::"),o=i[0];if(yt(o)&&!e.packages[o])throw new Error(`No address found for package: ${o}`);yt(o)&&(i[0]=e.packages[o].package,s.package=i.join("::"));const a=s.typeArguments;if(a){for(let c=0;c<a.length;c++)if(yt(a[c])){if(!e.types[a[c]])throw new Error(`No resolution found for type: ${a[c]}`);a[c]=e.types[a[c]].type}s.typeArguments=a}}}function hm(t){const e=new Set;for(const r of t)if(yt(r)){if(!u3(r))throw new Error(`Invalid type with names: ${r}`);e.add(r)}return e}const DI=t=>async(e,r,n)=>{const s=$I(e);if(s.types.length===0&&s.packages.length===0)return n();const i=await HI(r).core.mvr.resolve({types:s.types,packages:s.packages});LI(e,i),await n()};function HI(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}var Hv=t=>{throw TypeError(t)},hp=(t,e,r)=>e.has(t)||Hv("Cannot "+r),Q=(t,e,r)=>(hp(t,e,"read from private field"),r?r.call(t):e.get(t)),Vr=(t,e,r)=>e.has(t)?Hv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Pe=(t,e,r,n)=>(hp(t,e,"write to private field"),e.set(t,r),r),tt=(t,e,r)=>(hp(t,e,"access private method"),r),Ps,js,gn,Qr,qt,Wt,Er,Yn,ce,We,zv,yc,mc,bc,jc,Fd,pp,Vv,Gv;function Pf(t,e=1/0){const r={$kind:"Result",get Result(){return typeof t=="function"?t():t}},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",get NestedResult(){return[typeof t=="function"?t():t,i]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,o){if(o in i)return Reflect.get(i,o);if(o===Symbol.iterator)return function*(){let c=0;for(;c<e;)yield s(c),c++};if(typeof o=="symbol")return;const a=parseInt(o,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}const qv=Symbol.for("@mysten/transaction");function Wv(t){return!!t&&typeof t=="object"&&t[qv]===!0}const pm={buildPlugins:new Map,serializationPlugins:new Map},Of=Symbol.for("@mysten/transaction/registry");function uo(){try{const t=globalThis;return t[Of]||(t[Of]=pm),t[Of]}catch{return pm}}const Kv=class $d{constructor(){Vr(this,We),Vr(this,Ps),Vr(this,js),Vr(this,gn,new Map),Vr(this,Qr,[]),Vr(this,qt,[]),Vr(this,Wt,new Set),Vr(this,Er,new Set),Vr(this,Yn,new Map),Vr(this,ce),this.object=BI(r=>{var i,o;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&Id(Re,r))return r;const n=Mc(r),s=Q(this,ce).inputs.find(a=>n===Mc(a));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof r=="object"&&((o=r.Object)!=null&&o.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||r.Object.SharedObject.mutable),s?{$kind:"Input",Input:Q(this,ce).inputs.indexOf(s),type:"object"}:tt(this,We,mc).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:we(r)}}:r)});const e=uo();Pe(this,ce,new Mt),Pe(this,js,[...e.buildPlugins.values()]),Pe(this,Ps,[...e.serializationPlugins.values()])}static fromKind(e){const r=new $d;return Pe(r,ce,Mt.fromKindBytes(typeof e=="string"?Xt(e):e)),Pe(r,Qr,Q(r,ce).inputs.slice()),Pe(r,qt,Q(r,ce).commands.slice()),Pe(r,Wt,new Set(Q(r,qt).map((n,s)=>s))),r}static from(e){const r=new $d;return Wv(e)?Pe(r,ce,Mt.restore(e.getData())):typeof e!="string"||!e.startsWith("{")?Pe(r,ce,Mt.fromBytes(typeof e=="string"?Xt(e):e)):Pe(r,ce,Mt.restore(JSON.parse(e))),Pe(r,Qr,Q(r,ce).inputs.slice()),Pe(r,qt,Q(r,ce).commands.slice()),Pe(r,Wt,new Set(Q(r,qt).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(e,r){uo().serializationPlugins.set(e,r??e)}static unregisterGlobalSerializationPlugin(e){uo().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,r){uo().buildPlugins.set(e,r??e)}static unregisterGlobalBuildPlugin(e){uo().buildPlugins.delete(e)}addSerializationPlugin(e){Q(this,Ps).push(e)}addBuildPlugin(e){Q(this,js).push(e)}addIntentResolver(e,r){if(Q(this,gn).has(e)&&Q(this,gn).get(e)!==r)throw new Error(`Intent resolver for ${e} already exists`);Q(this,gn).set(e,r)}setSender(e){Q(this,ce).sender=e}setSenderIfNotSet(e){Q(this,ce).sender||(Q(this,ce).sender=e)}setExpiration(e){Q(this,ce).expiration=e?De(uv,e):null}setGasPrice(e){Q(this,ce).gasConfig.price=String(e)}setGasBudget(e){Q(this,ce).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){Q(this,ce).gasData.budget==null&&(Q(this,ce).gasConfig.budget=String(e))}setGasOwner(e){Q(this,ce).gasConfig.owner=e}setGasPayment(e){Q(this,ce).gasConfig.payment=e.map(r=>De(ls,r))}get blockData(){return um(Q(this,ce).snapshot())}getData(){return Q(this,ce).snapshot()}get[qv](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:CI(e=>ip(e)?tt(this,We,mc).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):tt(this,We,mc).call(this,"pure",Id(im,e)?De(im,e):e instanceof Uint8Array?kr.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(kr.ObjectRef(...e))}receivingRef(...e){return this.object(kr.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(kr.SharedObjectRef(...e))}add(e){if(typeof e=="function"){if(Q(this,Yn).has(e))return Q(this,Yn).get(e);const r=tt(this,We,zv).call(this),n=e(r);if(!(n&&typeof n=="object"&&"then"in n))return Pe(this,Wt,Q(r,Wt)),Q(this,Yn).set(e,n),n;const s=tt(this,We,yc).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Q(this,ce).commands.length,result:null}}});Q(this,Er).add(Promise.resolve(n).then(o=>{s.$Intent.data.result=o}));const i=Pf(()=>s.$Intent.data.resultIndex);return Q(this,Yn).set(e,i),i}else tt(this,We,yc).call(this,e);return Pf(Q(this,ce).commands.length-1)}splitCoins(e,r){const n=vs.SplitCoins(typeof e=="string"?this.object(e):tt(this,We,jc).call(this,e),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):tt(this,We,bc).call(this,s)));return tt(this,We,yc).call(this,n),Pf(Q(this,ce).commands.length-1,r.length)}mergeCoins(e,r){return this.add(vs.MergeCoins(this.object(e),r.map(n=>this.object(n))))}publish({modules:e,dependencies:r}){return this.add(vs.Publish({modules:e,dependencies:r}))}upgrade({modules:e,dependencies:r,package:n,ticket:s}){return this.add(vs.Upgrade({modules:e,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:e,...r}){return this.add(vs.MoveCall({...r,arguments:e==null?void 0:e.map(n=>tt(this,We,bc).call(this,n))}))}transferObjects(e,r){return this.add(vs.TransferObjects(e.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):tt(this,We,bc).call(this,r)))}makeMoveVec({type:e,elements:r}){return this.add(vs.MakeMoveVec({type:e,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(um(Q(this,ce).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const r=this.isFullyResolved();return JSON.stringify(De(Y3,r?{...Q(this,ce).snapshot(),digest:Q(this,ce).getDigest()}:Q(this,ce).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(e){const{signer:r,...n}=e,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!Q(this,ce).sender||Q(this,Er).size>0||Q(this,ce).commands.some(e=>e.$Intent)||Uv(Q(this,ce),{}))}async build(e={}){return await this.prepareForSerialization(e),await tt(this,We,Fd).call(this,e),Q(this,ce).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await tt(this,We,Fd).call(this,e),Q(this,ce).getDigest()}async prepareForSerialization(e){var s;await tt(this,We,Vv).call(this),tt(this,We,Gv).call(this);const r=new Set;for(const i of Q(this,ce).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...Q(this,Ps)];for(const i of r)if(!((s=e.supportedIntents)!=null&&s.includes(i))){if(!Q(this,gn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(Q(this,gn).get(i))}n.push(DI()),await tt(this,We,pp).call(this,n,e)}};Ps=new WeakMap;js=new WeakMap;gn=new WeakMap;Qr=new WeakMap;qt=new WeakMap;Wt=new WeakMap;Er=new WeakMap;Yn=new WeakMap;ce=new WeakMap;We=new WeakSet;zv=function(){const t=new Kv;return Pe(t,ce,Q(this,ce)),Pe(t,Ps,Q(this,Ps)),Pe(t,js,Q(this,js)),Pe(t,gn,Q(this,gn)),Pe(t,Er,Q(this,Er)),Pe(t,Wt,new Set(Q(this,Wt))),Pe(t,Yn,Q(this,Yn)),Q(this,Qr).push(Q(t,Qr)),Q(this,qt).push(Q(t,qt)),t};yc=function(t){const e=Q(this,ce).commands.length;return Q(this,qt).push(t),Q(this,Wt).add(e),Q(this,ce).commands.push(t),Q(this,ce).mapCommandArguments(e,r=>{if(r.$kind==="Result"&&!Q(this,Wt).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use in the current transaction`);if(r.$kind==="NestedResult"&&!Q(this,Wt).has(r.NestedResult[0]))throw new Error(`Result { NestedResult: [${r.NestedResult[0]}, ${r.NestedResult[1]}] } is not available to use in the current transaction`);if(r.$kind==="Input"&&r.Input>=Q(this,ce).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),t};mc=function(t,e){return Q(this,Qr).push(e),Q(this,ce).addInput(t,e)};bc=function(t){return ip(t)?this.pure(t):tt(this,We,jc).call(this,t)};jc=function(t){if(typeof t=="function"){const e=this.add(t);return typeof e=="function"?tt(this,We,jc).call(this,e):De(Re,e)}return De(Re,t)};Fd=async function(t){if(!t.onlyTransactionKind&&!Q(this,ce).sender)throw new Error("Missing transaction sender");await tt(this,We,pp).call(this,[...Q(this,js),PI],t)};pp=async function(t,e){try{const r=n=>{if(n>=t.length)return()=>{};const s=t[n];return async()=>{const i=r(n+1);let o=!1,a=!1;if(await s(Q(this,ce),e,async()=>{if(o)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);o=!0,await i(),a=!0}),!o)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!a)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await r(0)()}finally{Pe(this,Qr,Q(this,ce).inputs.slice()),Pe(this,qt,Q(this,ce).commands.slice()),Pe(this,Wt,new Set(Q(this,qt).map((r,n)=>n)))}};Vv=async function(){for(;Q(this,Er).size>0;){const t=Promise.all(Q(this,Er));Q(this,Er).clear(),Q(this,Er).add(t),await t,Q(this,Er).delete(t)}};Gv=function(){var o;const t=Q(this,ce).commands,e=Q(this,ce).inputs,r=Q(this,qt).flat(1/0),n=Q(this,Qr).flat(1/0);if(r.length!==t.length)throw new Error("Unexpected number of commands found in transaction data");if(n.length!==e.length)throw new Error("Unexpected number of inputs found in transaction data");const s=r.filter(a=>{var c;return((c=a.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Q(this,ce).commands=s,Q(this,ce).inputs=n,Pe(this,qt,s),Pe(this,Qr,n),Pe(this,Wt,new Set(s.map((a,c)=>c)));function i(a){var l;const c=t[a];if(((l=c.$Intent)==null?void 0:l.name)==="AsyncTransactionThunk"){const f=c.$Intent.data.result;if(f==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(f.Result)}const u=s.indexOf(c);if(u===-1)throw new Error("Unable to find original index for command");return u}Q(this,ce).mapArguments(a=>{if(a.$kind==="Input"){const c=n.indexOf(e[a.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...a,Input:c}}else if(a.$kind==="Result"){const c=i(a.Result);return{...a,Result:c}}else if(a.$kind==="NestedResult"){const c=i(a.NestedResult[0]);return{...a,NestedResult:[c,a.NestedResult[1]]}}return a});for(const[a,c]of t.entries())if(((o=c.$Intent)==null?void 0:o.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(a)}catch{}};let Ld=Kv;const zI={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class VI extends tv{constructor(e){var r,n,s;super(e),this.core=this,this.mvr=new UI({cache:this.cache.scope("core.mvr"),url:((r=e.mvr)==null?void 0:r.url)??zI[this.network],pageSize:(n=e.mvr)==null?void 0:n.pageSize,overrides:(s=e.mvr)==null?void 0:s.overrides})}async getObject(e){const{objectId:r}=e,{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(e){const r=vr.parseFromStr((await this.core.mvr.resolveType({type:e.name.type})).type),n=oI(e.parentId,r,e.name.bcs),{objects:[s]}=await this.getObjects({objectIds:[n],signal:e.signal});if(s instanceof Error)throw s;const i=Ks(s.type),o=await s.content;return{dynamicField:{id:s.id,digest:s.digest,version:s.version,type:s.type,previousTransaction:s.previousTransaction,name:{type:typeof i.typeParams[0]=="string"?i.typeParams[0]:Rc(i.typeParams[0]),bcs:e.name.bcs},value:{type:typeof i.typeParams[1]=="string"?i.typeParams[1]:Rc(i.typeParams[1]),bcs:o.slice(Iu+e.name.bcs.length)}}}}async waitForTransaction({signal:e,timeout:r=60*1e3,...n}){const s=e?AbortSignal.any([AbortSignal.timeout(r),e]):AbortSignal.timeout(r),i=new Promise((o,a)=>{s.addEventListener("abort",()=>a(s.reason))});for(i.catch(()=>{});;){s.throwIfAborted();try{return await this.getTransaction({...n,signal:s})}catch{await Promise.race([new Promise(o=>setTimeout(o,2e3)),i])}}}}class GI extends Error{}class Jn extends GI{constructor(e,r){super(r),this.code=e}static fromResponse(e,r){switch(e.code){case"notExists":return new Jn(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new Jn(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new Jn(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new Jn(e.code,`Display error: ${e.error}`);case"unknown":default:return new Jn(e.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function qI(t){return{...Mt.fromBytes(t).snapshot(),bcs:t}}function WI(t){const e=he.TransactionEffects.parse(t);switch(e.$kind){case"V1":return KI({effects:e.V1});case"V2":return XI({bytes:t,effects:e.V2});default:throw new Error(`Unknown transaction effects version: ${e.$kind}`)}}function KI(t){throw new Error("V1 effects are not supported yet")}function XI({bytes:t,effects:e}){const r=e.changedObjects.map(([n,s])=>{var i,o,a,c,u,l;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((o=s.inputState.Exist)==null?void 0:o[0][1])??null,inputOwner:((a=s.inputState.Exist)==null?void 0:a[1])??null,outputState:s.outputState.$kind==="NotExist"?"DoesNotExist":s.outputState.$kind,outputVersion:s.outputState.$kind==="PackageWrite"?(c=s.outputState.PackageWrite)==null?void 0:c[0]:s.outputState.ObjectWrite?e.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(u=s.outputState.PackageWrite)==null?void 0:u[1]:((l=s.outputState.ObjectWrite)==null?void 0:l[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.idOperation.$kind}});return{bcs:t,digest:e.transactionDigest,version:2,status:e.status.$kind==="Success"?{success:!0,error:null}:{success:!1,error:e.status.Failed.error.$kind},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:e.gasObjectIndex===null?null:r[e.gasObjectIndex]??null,eventsDigest:e.eventsDigest,dependencies:e.dependencies,lamportVersion:e.lamportVersion,changedObjects:r,unchangedConsensusObjects:e.unchangedSharedObjects.map(([n,s])=>({kind:s.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":s.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":s.$kind,objectId:n,version:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[0]:s[s.$kind],digest:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:e.auxDataDigest}}var Xv=t=>{throw TypeError(t)},Yv=(t,e,r)=>e.has(t)||Xv("Cannot "+r),Ct=(t,e,r)=>(Yv(t,e,"read from private field"),r?r.call(t):e.get(t)),YI=(t,e,r)=>e.has(t)?Xv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),JI=(t,e,r,n)=>(Yv(t,e,"write to private field"),e.set(t,r),r),at;class ZI extends VI{constructor({jsonRpcClient:e,mvr:r}){super({network:e.network,base:e,mvr:r}),YI(this,at),JI(this,at,e)}async getObjects(e){const r=_u(e.objectIds,50),n=[];for(const s of r){const i=await Ct(this,at).multiGetObjects({ids:s,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},signal:e.signal});for(const[o,a]of i.entries())a.error?n.push(Jn.fromResponse(a.error,s[o])):n.push(ym(a.data))}return{objects:n}}async getOwnedObjects(e){const r=await Ct(this,at).getOwnedObjects({owner:e.address,limit:e.limit,cursor:e.cursor,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},filter:e.type?{StructType:e.type}:null,signal:e.signal});return{objects:r.data.map(n=>{if(n.error)throw Jn.fromResponse(n.error);return ym(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(e){const r=await Ct(this,at).getCoins({owner:e.address,coinType:e.coinType,limit:e.limit,cursor:e.cursor,signal:e.signal});return{objects:r.data.map(n=>({id:n.coinObjectId,version:n.version,digest:n.digest,balance:n.balance,type:`0x2::coin::Coin<${n.coinType}>`,content:Promise.resolve(tB.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:e.address},previousTransaction:n.previousTransaction})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(e){const r=await Ct(this,at).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(e){return{balances:(await Ct(this,at).getAllBalances({owner:e.address,signal:e.signal})).map(n=>({coinType:n.coinType,balance:n.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){const r=await Ct(this,at).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal});return{transaction:mm(r)}}async executeTransaction(e){const r=await Ct(this,at).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal});return{transaction:mm(r)}}async dryRunTransaction(e){const r=Ld.from(e.transaction),n=await Ct(this,at).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:s,objectTypes:i}=QI({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:qI(e.transaction),balanceChanges:n.balanceChanges.map(o=>({coinType:o.coinType,address:Jv(o.owner),amount:o.amount}))}}}async getReferenceGasPrice(e){const r=await Ct(this,at).getReferenceGasPrice({signal:e==null?void 0:e.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(e){const r=await Ct(this,at).getDynamicFields({parentId:e.parentId,limit:e.limit,cursor:e.cursor});return{dynamicFields:r.data.map(n=>({id:n.objectId,type:n.objectType,name:{type:n.name.type,bcs:Xt(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(e){const r=await Ct(this,at).verifyZkLoginSignature({bytes:e.bytes,signature:e.signature,intentScope:e.intentScope,author:e.author});return{success:r.success,errors:r.errors}}async defaultNameServiceName(e){return{data:{name:(await Ct(this,at).resolveNameServiceNames(e)).data[0]}}}resolveTransactionPlugin(){return jv(Ct(this,at))}async getMoveFunction(e){const r=await Ct(this,at).getNormalizedMoveFunction({package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name});return{function:{packageId:we(e.packageId),moduleName:e.moduleName,name:e.name,visibility:nB(r.visibility),isEntry:r.isEntry,typeParameters:r.typeParameters.map(n=>({isPhantom:!1,constraints:rB(n)})),parameters:r.parameters.map(n=>bm(n)),returns:r.return.map(n=>bm(n))}}}}at=new WeakMap;function ym(t){var e;return{id:t.objectId,version:t.version,digest:t.digest,type:t.type,content:Promise.resolve(((e=t.bcs)==null?void 0:e.dataType)==="moveObject"?Xt(t.bcs.bcsBytes):new Uint8Array),owner:yi(t.owner),previousTransaction:t.previousTransaction??null}}function yi(t){if(t==="Immutable")return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in t)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:t.ConsensusAddressOwner.owner,startVersion:t.ConsensusAddressOwner.start_version}};if("AddressOwner"in t)return{$kind:"AddressOwner",AddressOwner:t.AddressOwner};if("ObjectOwner"in t)return{$kind:"ObjectOwner",ObjectOwner:t.ObjectOwner};if("Shared"in t)return{$kind:"Shared",Shared:{initialSharedVersion:t.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function Jv(t){if(t==="Immutable")return null;if("ConsensusAddressOwner"in t)return t.ConsensusAddressOwner.owner;if("AddressOwner"in t)return t.AddressOwner;if("ObjectOwner"in t)return t.ObjectOwner;if("Shared"in t)return null;throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function mm(t){var i,o,a;const e=he.SenderSignedData.parse(Xt(t.rawTransaction))[0],r={};(i=t.objectChanges)==null||i.forEach(c=>{c.type!=="published"&&(r[c.objectId]=c.objectType)});const n=he.TransactionData.serialize(e.intentMessage.value).toBytes(),s=Mt.restore({version:2,sender:e.intentMessage.value.V1.sender,expiration:e.intentMessage.value.V1.expiration,gasData:e.intentMessage.value.V1.gasData,inputs:e.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:e.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:t.digest,epoch:((o=t.effects)==null?void 0:o.executedEpoch)??null,effects:WI(new Uint8Array(t.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:e.txSignatures,balanceChanges:((a=t.balanceChanges)==null?void 0:a.map(c=>({coinType:c.coinType,address:Jv(c.owner),amount:c.amount})))??[]}}function QI({bytes:t,effects:e,objectChanges:r}){var o;const n=[],s=[],i={};return r==null||r.forEach(a=>{var c,u,l,f;switch(a.type){case"published":n.push({id:a.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:a.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.recipient),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"mutated":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.previousVersion,inputDigest:null,inputOwner:yi(a.owner),outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.owner),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"deleted":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:((u=(c=e.deleted)==null?void 0:c.find(h=>h.objectId===a.objectId))==null?void 0:u.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[a.objectId]=a.objectType;break;case"wrapped":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:((f=(l=e.wrapped)==null?void 0:l.find(h=>h.objectId===a.objectId))==null?void 0:f.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:a.sender},idOperation:"None"}),i[a.objectId]=a.objectType;break;case"created":n.push({id:a.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.owner),idOperation:"Created"}),i[a.objectId]=a.objectType;break}}),{objectTypes:i,effects:{bcs:t??null,digest:e.transactionDigest,version:2,status:e.status.status==="success"?{success:!0,error:null}:{success:!1,error:e.status.error},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:{id:(o=e.gasObject)==null?void 0:o.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:e.gasObject.reference.version,outputDigest:e.gasObject.reference.digest,outputOwner:yi(e.gasObject.owner),idOperation:"None"},eventsDigest:e.eventsDigest??null,dependencies:e.dependencies??[],lamportVersion:e.gasObject.reference.version,changedObjects:n,unchangedConsensusObjects:s,auxiliaryDataDigest:null}}}const eB=he.struct("Balance",{value:he.u64()}),tB=he.struct("Coin",{id:he.Address,balance:eB});function bm(t){if(typeof t!="string"){if("Reference"in t)return{reference:"immutable",body:_o(t.Reference)};if("MutableReference"in t)return{reference:"mutable",body:_o(t.MutableReference)}}return{reference:null,body:_o(t)}}function _o(t){switch(t){case"Address":return{$kind:"address"};case"Bool":return{$kind:"bool"};case"U8":return{$kind:"u8"};case"U16":return{$kind:"u16"};case"U32":return{$kind:"u32"};case"U64":return{$kind:"u64"};case"U128":return{$kind:"u128"};case"U256":return{$kind:"u256"}}if(typeof t=="string")throw new Error(`Unknown type: ${t}`);if("Vector"in t)return{$kind:"vector",vector:_o(t.Vector)};if("Struct"in t)return{$kind:"datatype",datatype:{typeName:`${we(t.Struct.address)}::${t.Struct.module}::${t.Struct.name}`,typeParameters:t.Struct.typeArguments.map(e=>_o(e))}};if("TypeParameter"in t)return{$kind:"typeParameter",index:t.TypeParameter};throw new Error(`Unknown type: ${JSON.stringify(t)}`)}function rB(t){return t.abilities.map(e=>{switch(e){case"Copy":return"copy";case"Drop":return"drop";case"Store":return"store";case"Key":return"key";default:return"unknown"}})}function nB(t){switch(t){case"Public":return"public";case"Private":return"private";case"Friend":return"friend";default:return"unknown"}}const sB=Symbol.for("@mysten/SuiClient");class gm extends tv{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new mO({url:e.url}),this.core=new ZI({jsonRpcClient:this,mvr:e.mvr})}get[sB](){return!0}async getRpcApiVersion({signal:e}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:e})).info.version}async getCoins({coinType:e,owner:r,cursor:n,limit:s,signal:i}){if(!r||!wr(we(r)))throw new Error("Invalid Sui address");return e&&yt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoins",params:[r,e,n,s],signal:i})}async getAllCoins(e){if(!e.owner||!wr(we(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit],signal:e.signal})}async getBalance({owner:e,coinType:r,signal:n}){if(!e||!wr(we(e)))throw new Error("Invalid Sui address");return r&&yt(r)&&(r=(await this.core.mvr.resolveType({type:r})).type),await this.transport.request({method:"suix_getBalance",params:[e,r],signal:n})}async getAllBalances(e){if(!e.owner||!wr(we(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner],signal:e.signal})}async getCoinMetadata({coinType:e,signal:r}){return e&&yt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[e],signal:r})}async getTotalSupply({coinType:e,signal:r}){return e&&yt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getTotalSupply",params:[e],signal:r})}async call(e,r,{signal:n}={}){return await this.transport.request({method:e,params:r,signal:n})}async getMoveFunctionArgTypes({package:e,module:r,function:n,signal:s}){return e&&Vt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e,r,n],signal:s})}async getNormalizedMoveModulesByPackage({package:e,signal:r}){return e&&Vt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e],signal:r})}async getNormalizedMoveModule({package:e,module:r,signal:n}){return e&&Vt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e,r],signal:n})}async getNormalizedMoveFunction({package:e,module:r,function:n,signal:s}){return e&&Vt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e,r,n],signal:s})}async getNormalizedMoveStruct({package:e,module:r,struct:n,signal:s}){return e&&Vt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e,r,n],signal:s})}async getOwnedObjects(e){if(!e.owner||!wr(we(e.owner)))throw new Error("Invalid Sui address");const r=e.filter?{...e.filter}:void 0;return r&&"MoveModule"in r&&Vt(r.MoveModule.package)?r.MoveModule={module:r.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:r.MoveModule.package})).package}:r&&"StructType"in r&&yt(r.StructType)&&(r.StructType=(await this.core.mvr.resolveType({type:r.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:r,options:e.options},e.cursor,e.limit],signal:e.signal})}async getObject(e){if(!e.id||!nc(Jr(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options],signal:e.signal})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options],signal:e.signal})}async multiGetObjects(e){if(e.ids.forEach(n=>{if(!n||!nc(Jr(n)))throw new Error(`Invalid Sui Object id ${n}`)}),e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options],signal:e.signal})}async queryTransactionBlocks({filter:e,options:r,cursor:n,limit:s,order:i,signal:o}){return e&&"MoveFunction"in e&&Vt(e.MoveFunction.package)&&(e={...e,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:e.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e,options:r},n,s,(i||"descending")==="descending"],signal:o})}async getTransactionBlock(e){if(!sm(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options],signal:e.signal})}async multiGetTransactionBlocks(e){if(e.digests.forEach(n=>{if(!sm(n))throw new Error(`Invalid Transaction digest ${n}`)}),e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options],signal:e.signal})}async executeTransactionBlock({transactionBlock:e,signature:r,options:n,requestType:s,signal:i}){const o=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof e=="string"?e:mt(e),Array.isArray(r)?r:[r],n],signal:i});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:o.digest})}catch{}return o}async signAndExecuteTransaction({transaction:e,signer:r,...n}){let s;e instanceof Uint8Array?s=e:(e.setSenderIfNotSet(r.toSuiAddress()),s=await e.build({client:this}));const{signature:i,bytes:o}=await r.signTransaction(s);return this.executeTransactionBlock({transactionBlock:o,signature:i,...n})}async getTotalTransactionBlocks({signal:e}={}){const r=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:e});return BigInt(r)}async getReferenceGasPrice({signal:e}={}){const r=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:e});return BigInt(r)}async getStakes(e){if(!e.owner||!wr(we(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner],signal:e.signal})}async getStakesByIds(e){return e.stakedSuiIds.forEach(r=>{if(!r||!nc(Jr(r)))throw new Error(`Invalid Sui Stake id ${r}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds],signal:e.signal})}async getLatestSuiSystemState({signal:e}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:e})}async queryEvents({query:e,cursor:r,limit:n,order:s,signal:i}){return e&&"MoveEventType"in e&&yt(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&Vt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&Vt(e.MoveModule.package)&&(e={...e,MoveModule:{module:e.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[e,r,n,(s||"descending")==="descending"],signal:i})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async devInspectTransactionBlock(e){var n,s;let r;if(Wv(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),r=mt(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof e.transactionBlock=="string")r=e.transactionBlock;else if(e.transactionBlock instanceof Uint8Array)r=mt(e.transactionBlock);else throw new Error("Unknown transaction block format.");return(n=e.signal)==null||n.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,r,(s=e.gasPrice)==null?void 0:s.toString(),e.epoch],signal:e.signal})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof e.transactionBlock=="string"?e.transactionBlock:mt(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!nc(Jr(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit],signal:e.signal})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name],signal:e.signal})}async getLatestCheckpointSequenceNumber({signal:e}={}){const r=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:e});return String(r)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id],signal:e.signal})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e==null?void 0:e.limit,e.descendingOrder],signal:e.signal})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e==null?void 0:e.epoch],signal:e==null?void 0:e.signal})}async getNetworkMetrics({signal:e}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:e})}async getAddressMetrics({signal:e}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:e})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getMoveCallMetrics({signal:e}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:e})}async getCurrentEpoch({signal:e}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:e})}async getValidatorsApy({signal:e}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:e})}async getChainIdentifier({signal:e}={}){const r=await this.getCheckpoint({id:"0",signal:e}),n=na(r.digest);return Di(n.slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name],signal:e.signal})}async resolveNameServiceNames({format:e="dot",...r}){const{nextCursor:n,hasNextPage:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:s,nextCursor:n,data:i.map(o=>i3(o,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e==null?void 0:e.version],signal:e==null?void 0:e.signal})}async verifyZkLoginSignature(e){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[e.bytes,e.signature,e.intentScope,e.author],signal:e.signal})}async waitForTransaction({signal:e,timeout:r=60*1e3,pollInterval:n=2*1e3,...s}){const i=AbortSignal.timeout(r),o=new Promise((a,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(o.catch(()=>{});!i.aborted;){e==null||e.throwIfAborted();try{return await this.getTransactionBlock(s)}catch{await Promise.race([new Promise(a=>setTimeout(a,n)),o])}}throw i.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}}class iB{constructor(e,r,n,s){this.client=new gm({url:Qy(n)}),this.url=e instanceof E.Url?e:new E.Url(e),this.account=r,this.network=n,this.auth=s,this.relayer=new ti(this.auth,this.url)}get htlcActorAddress(){var e,r;return"accounts"in this.account?((r=(e=this.account.accounts)==null?void 0:e[0])==null?void 0:r.address)??"":this.account.toSuiAddress()}async initiate(e){var r,n,s;if(!e)return E.Err("Order is required");if(V.isSuiOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const{source_swap:i}=e,o=BigInt(i.amount),a=i.asset,c=i.redeemer,u=i.secret_hash,l=await ji(i.asset,this.url);if(!l.ok)return E.Err(l.error);const{tokenAddress:f}=l.val,h=new Ld;h.setSender(this.htlcActorAddress);const[d]=h.splitCoins(h.gas,[o]);h.moveCall({target:`${yd[this.network].packageId}::${yd[this.network].moduleName}::initiate`,typeArguments:[f],arguments:[h.object(a),h.pure.address(this.htlcActorAddress),h.pure.address(c),h.pure.vector("u8",Buffer.from(u,"hex")),h.pure.u64(o),h.pure.u256(i.timelock),h.pure.vector("u8",Buffer.from("")),d,h.object(Q3)]});const p=await h.build({client:this.client}),m=await this.client.dryRunTransactionBlock({transactionBlock:p});if(m.effects.status.status==="failure")return E.Err(`${m.effects.status.error}`);let v;if("features"in this.account?v=await((r=this.account.features[gp.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:h,account:this.account.accounts[0],chain:`sui:${this.network}`})):v=await this.client.signAndExecuteTransaction({signer:this.account,transaction:h,options:{showEffects:!0}}),!v)return E.Err("Failed to initiate");const S=await this.client.waitForTransaction({digest:v.digest,options:{showEffects:!0}});return((n=S.effects)==null?void 0:n.status.status)==="failure"?E.Err(`Failed to initiate: ${(s=S.effects)==null?void 0:s.status.error}`):E.Ok(S.digest)}catch(i){return E.Err(i)}}async initiateWithCreateOrderResponse(e){var a,c,u;const{ptb_bytes:r}=e,s=await new gm({url:Qy("testnet")}).getReferenceGasPrice(),i=1e7,o=Ld.fromKind(new Uint8Array(r));o.setSender(this.htlcActorAddress),o.setGasPrice(s),o.setGasBudget(i);try{let l;if("features"in this.account?l=await((a=this.account.features[gp.SuiSignAndExecuteTransaction])==null?void 0:a.signAndExecuteTransaction({transaction:o,account:this.account.accounts[0],chain:`sui:${this.network}`})):l=await this.client.signAndExecuteTransaction({signer:this.account,transaction:o,options:{showEffects:!0}}),!l)return E.Err("Failed to initiate");const f=await this.client.waitForTransaction({digest:l.digest,options:{showEffects:!0}});return((c=f.effects)==null?void 0:c.status.status)==="failure"?E.Err(`Failed to initiate: ${(u=f.effects)==null?void 0:u.status.error}`):E.Ok(f.digest)}catch(l){return E.Err(String(l))}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?E.Err(n.error):n.val?E.Ok(n.val):E.Err("Redeem: No result found")}async refund(){return E.Err("Refund is taken care of by the relayer")}}function wm(t){let e=t.startsWith("0x")?t.slice(2):t;return e=e.toLowerCase(),e.length>64&&(e=e.slice(e.length-64)),e.length<64&&(e=e.padStart(64,"0")),`0x${e}`}class oB{constructor(e,r,n,s){this.url=typeof e=="string"?new E.Url(e):e,this.auth=n,s instanceof wp.TronWeb?(this.wallet={tronweb:s},this.tronweb=s):(this.wallet={adapter:s},this.tronweb=new wp.TronWeb({fullHost:Sw[r]})),this.relayer=new ti(this.auth,this.url)}get htlcActorAddress(){var e,r,n;return(e=this.wallet.adapter)!=null&&e.address?this.wallet.adapter.address:this.wallet.tronweb?((r=this.wallet.tronweb.defaultAddress)==null?void 0:r.base58)||"":((n=this.tronweb.defaultAddress)==null?void 0:n.base58)||""}async initiate(e){if(V.isEvmOrderResponse(e))return this.initiateDirectContractCall(e);try{const{source_swap:r}=e,n=await ji(r.asset,this.url);if(!n.ok)return E.Err(n.error);const{htlcAddress:s}=n.val;return await this.executeContractCall({contractAddress:s,method:"initiate(address,uint256,uint256,bytes32,bytes)",parameters:[{type:"address",value:r.redeemer},{type:"uint256",value:r.timelock},{type:"uint256",value:BigInt(r.amount)},{type:"bytes32",value:wm(String(r.secret_hash))},{type:"bytes",value:"0x"}],options:{}})}catch(r){return E.Err(`Failed to initiate: ${String(r)}`)}}async initiateDirectContractCall(e){var f;if(!this.htlcActorAddress)return E.Err("No HTLC actor address found");if(e.approval_transaction){const h=await this.executeApprovalTransaction(e);if(h.error)return E.Err(h.error)}if(!e.initiate_transaction)return E.Err("No initiate transaction data available for direct contract call");if(!((f=e.typed_data)!=null&&f.message))return E.Err("No typed data message found in order response");const{to:r,value:n,gas_limit:s}=e.initiate_transaction,{redeemer:i,timelock:o,amount:a,secretHash:c,destinationData:u}=e.typed_data.message,l=await this.executeContractCall({contractAddress:r,method:"initiate(address,uint256,uint256,bytes32,bytes)",parameters:[{type:"address",value:i},{type:"uint256",value:o},{type:"uint256",value:a},{type:"bytes32",value:wm(String(c))},{type:"bytes",value:u}],options:{feeLimit:parseInt(s),callValue:n?parseInt(n):0}});return!l.val||l.error?E.Err("Failed to initiate"+(l.error||"")):await this.waitForTransactionConfirmation(l.val)}async executeApprovalTransaction(e){if(console.log("No Allowance found, Executing Approval"),!this.htlcActorAddress)return E.Err("No HTLC actor address found");const r=e.approval_transaction;if(!r)return E.Ok("No approval transaction required");try{const n="0x"+r.data.slice(10),s=this.tronweb.utils.abi.decodeParams(["spender","amount"],["address","uint256"],n,!1);return await this.executeContractCall({contractAddress:r.to,method:"approve(address,uint256)",parameters:[{type:"address",value:s.spender},{type:"uint256",value:s.amount.toString()}],options:{feeLimit:Number(r.gas_limit),callValue:0}})}catch(n){return E.Err(`Approval transaction failed: ${String(n)}`)}}async executeContractCall({contractAddress:e,method:r,parameters:n,options:s}){try{const i=await this.tronweb.transactionBuilder.triggerSmartContract(e,r,s,n,this.htlcActorAddress);if(!(i!=null&&i.transaction))return E.Err("Failed to build transaction");const o=await this.signTransaction(i.transaction);if(o.error)return E.Err(o.error);const a=await this.tronweb.trx.sendRawTransaction(o.val);return a.result?(console.log("Transaction successful, txid:",a.txid),E.Ok(a.txid)):E.Err(String(a.message)||String(a.code)||"Transaction broadcast failed")}catch(i){return E.Err(`Contract call failed: ${String(i)}`)}}async signTransaction(e){if(this.wallet.adapter)try{const r=await this.wallet.adapter.signTransaction(e);return E.Ok(r)}catch(r){return E.Err(`Adapter signing failed: ${String(r)}`)}if(this.wallet.tronweb)try{const r=await this.wallet.tronweb.trx.sign(e);return E.Ok(r)}catch(r){return E.Err(`TronWeb signing failed: ${String(r)}`)}return E.Err("No signing method available (no adapter or TronWeb instance)")}async waitForTransactionConfirmation(e,r=30,n=3e3){for(let s=0;s<r;s++){try{const i=await this.tronweb.trx.getTransaction(e);if(!i)return E.Err("Transaction not found");if(i.txID&&i.ret[0].contractRet==="SUCCESS")return E.Ok(i.txID);if(i.ret[0].contractRet==="FAILED")return E.Err("Transaction failed on-chain")}catch(i){return E.Err(`Error checking transaction: ${String(i)}`)}await new Promise(i=>setTimeout(i,n))}return E.Err("Transaction confirmation timeout")}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?E.Err(n.error):E.Ok(n.val)}async refund(){return E.Err("Refund is taken care of by the relayer")}}var Zv={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(Br,()=>(()=>{var r={7531:s=>{var i=typeof Reflect=="object"?Reflect:null,o=i&&typeof i.apply=="function"?i.apply:function(g,w,k){return Function.prototype.apply.call(g,w,k)},a=i&&typeof i.ownKeys=="function"?i.ownKeys:Object.getOwnPropertySymbols?function(g){return Object.getOwnPropertyNames(g).concat(Object.getOwnPropertySymbols(g))}:function(g){return Object.getOwnPropertyNames(g)},c=Number.isNaN||function(g){return g!=g};function u(){u.init.call(this)}s.exports=u,s.exports.once=function(g,w){return new Promise(function(k,_){function O(H){g.removeListener(w,B),_(H)}function B(){typeof g.removeListener=="function"&&g.removeListener("error",O),k([].slice.call(arguments))}var N,$,j;T(g,w,B,{once:!0}),w!=="error"&&($=O,j={once:!0},typeof(N=g).on=="function")&&T(N,"error",$,j)})},(u.EventEmitter=u).prototype._events=void 0,u.prototype._eventsCount=0,u.prototype._maxListeners=void 0;var l=10;function f(g){if(typeof g!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof g)}function h(g){return g._maxListeners===void 0?u.defaultMaxListeners:g._maxListeners}function d(g,w,k,_){var O,B;return f(k),(O=g._events)===void 0?(O=g._events=Object.create(null),g._eventsCount=0):(O.newListener!==void 0&&(g.emit("newListener",w,k.listener||k),O=g._events),B=O[w]),B===void 0?(B=O[w]=k,++g._eventsCount):(typeof B=="function"?B=O[w]=_?[k,B]:[B,k]:_?B.unshift(k):B.push(k),0<(O=h(g))&&B.length>O&&!B.warned&&(B.warned=!0,(_=new Error("Possible EventEmitter memory leak detected. "+B.length+" "+String(w)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning",_.emitter=g,_.type=w,_.count=B.length,k=_,console)&&console.warn&&console.warn(k)),g}function p(g,w,k){return g={fired:!1,wrapFn:void 0,target:g,type:w,listener:k},w=(function(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}).bind(g),w.listener=k,g.wrapFn=w}function m(g,w,k){if(g=g._events,g===void 0)return[];if(g=g[w],g===void 0)return[];if(typeof g=="function")return k?[g.listener||g]:[g];if(k){for(var _=g,O=new Array(_.length),B=0;B<O.length;++B)O[B]=_[B].listener||_[B];return O}return S(g,g.length)}function v(g){var w=this._events;if(w!==void 0){if(w=w[g],typeof w=="function")return 1;if(w!==void 0)return w.length}return 0}function S(g,w){for(var k=new Array(w),_=0;_<w;++_)k[_]=g[_];return k}function T(g,w,k,_){if(typeof g.on=="function")_.once?g.once(w,k):g.on(w,k);else{if(typeof g.addEventListener!="function")throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof g);g.addEventListener(w,function O(B){_.once&&g.removeEventListener(w,O),k(B)})}}Object.defineProperty(u,"defaultMaxListeners",{enumerable:!0,get:function(){return l},set:function(g){if(typeof g!="number"||g<0||c(g))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+g+".");l=g}}),u.init=function(){this._events!==void 0&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},u.prototype.setMaxListeners=function(g){if(typeof g!="number"||g<0||c(g))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+g+".");return this._maxListeners=g,this},u.prototype.getMaxListeners=function(){return h(this)},u.prototype.emit=function(g){for(var w=[],k=1;k<arguments.length;k++)w.push(arguments[k]);var _=g==="error",O=this._events;if(O!==void 0)_=_&&O.error===void 0;else if(!_)return!1;if(_)throw(B=0<w.length?w[0]:B)instanceof Error?B:(_=new Error("Unhandled error."+(B?" ("+B.message+")":"")),_.context=B,_);var B=O[g];if(B===void 0)return!1;if(typeof B=="function")o(B,this,w);else for(var N=B.length,$=S(B,N),k=0;k<N;++k)o($[k],this,w);return!0},u.prototype.on=u.prototype.addListener=function(g,w){return d(this,g,w,!1)},u.prototype.prependListener=function(g,w){return d(this,g,w,!0)},u.prototype.once=function(g,w){return f(w),this.on(g,p(this,g,w)),this},u.prototype.prependOnceListener=function(g,w){return f(w),this.prependListener(g,p(this,g,w)),this},u.prototype.off=u.prototype.removeListener=function(g,w){var k,_,O,B,N;if(f(w),(_=this._events)!==void 0&&(k=_[g])!==void 0){if(k===w||k.listener===w)--this._eventsCount==0?this._events=Object.create(null):(delete _[g],_.removeListener&&this.emit("removeListener",g,k.listener||w));else if(typeof k!="function"){for(O=-1,B=k.length-1;0<=B;B--)if(k[B]===w||k[B].listener===w){N=k[B].listener,O=B;break}if(O<0)return this;if(O===0)k.shift();else{for(var $=k,j=O;j+1<$.length;j++)$[j]=$[j+1];$.pop()}k.length===1&&(_[g]=k[0]),_.removeListener!==void 0&&this.emit("removeListener",g,N||w)}}return this},u.prototype.removeAllListeners=function(g){var w,k=this._events;if(k!==void 0){if(k.removeListener===void 0)arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):k[g]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete k[g]);else if(arguments.length===0){for(var _,O=Object.keys(k),B=0;B<O.length;++B)(_=O[B])!=="removeListener"&&this.removeAllListeners(_);this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0}else if(typeof(w=k[g])=="function")this.removeListener(g,w);else if(w!==void 0)for(B=w.length-1;0<=B;B--)this.removeListener(g,w[B])}return this},u.prototype.listeners=function(g){return m(this,g,!0)},u.prototype.rawListeners=function(g){return m(this,g,!1)},u.listenerCount=function(g,w){return typeof g.listenerCount=="function"?g.listenerCount(w):v.call(g,w)},u.prototype.listenerCount=v,u.prototype.eventNames=function(){return 0<this._eventsCount?a(this._events):[]}},9616:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(p,m,v,S){S===void 0&&(S=v);var T=Object.getOwnPropertyDescriptor(m,v);T&&("get"in T?m.__esModule:!T.writable&&!T.configurable)||(T={enumerable:!0,get:function(){return m[v]}}),Object.defineProperty(p,S,T)}:function(p,m,v,S){p[S=S===void 0?v:S]=m[v]}),c=this&&this.__setModuleDefault||(Object.create?function(p,m){Object.defineProperty(p,"default",{enumerable:!0,value:m})}:function(p,m){p.default=m}),u=this&&this.__importStar||function(p){if(p&&p.__esModule)return p;var m={};if(p!=null)for(var v in p)v!=="default"&&Object.prototype.hasOwnProperty.call(p,v)&&a(m,p,v);return c(m,p),m};Object.defineProperty(i,"__esModule",{value:!0}),i.Sdk=void 0;const l=u(o(5149)),f=u(o(9386));var h=u(o(9815));class d extends l.CustomEmitter{constructor(v){super();A(this,"mount");A(this,"api");A(this,"session");A(this,"env");A(this,"async");A(this,"sync");A(this,"methods");A(this,"app",h.Projects.titles.crossmark);v!=null&&v.project&&(this.app=v==null?void 0:v.project),this.env=new l.Env,this.api=new l.Api(this),this.session=new l.Session(this),this.mount=new l.Mount(this),this.async=new f.Async(this),this.sync=new f.Sync(this),this.methods=Object.assign({},this.async,this.sync),new l.CustomEvents(this)}}i.Sdk=d},614:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(f,h,d,p){p===void 0&&(p=d);var m=Object.getOwnPropertyDescriptor(h,d);m&&("get"in m?h.__esModule:!m.writable&&!m.configurable)||(m={enumerable:!0,get:function(){return h[d]}}),Object.defineProperty(f,p,m)}:function(f,h,d,p){f[p=p===void 0?d:p]=h[d]}),c=this&&this.__setModuleDefault||(Object.create?function(f,h){Object.defineProperty(f,"default",{enumerable:!0,value:h})}:function(f,h){f.default=h}),u=this&&this.__importStar||function(f){if(f&&f.__esModule)return f;var h={};if(f!=null)for(var d in f)d!=="default"&&Object.prototype.hasOwnProperty.call(f,d)&&a(h,f,d);return c(h,f),h};Object.defineProperty(i,"__esModule",{value:!0}),i.Async=void 0;const l=u(o(9815));i.Async=class{constructor(f){A(this,"sdk");A(this,"api");A(this,"session");A(this,"mount");A(this,"signInAndWait",f=>this.api.awaitRequest({command:l.COMMANDS.SIGN,data:{tx:{TransactionType:"SignIn"},hex:f}}));A(this,"signAndWait",(f,h)=>this.api.awaitRequest({command:l.COMMANDS.SIGN,data:{tx:f,opts:h}}));A(this,"submitAndWait",(f,h,d)=>this.api.awaitRequest({command:l.COMMANDS.SUBMIT,data:{address:f,txblob:h,opts:d}}));A(this,"signAndSubmitAndWait",(f,h)=>this.api.awaitRequest({command:l.COMMANDS.SIGNANDSUBMIT,data:{tx:f,opts:h}}));A(this,"bulkSignAndWait",(f,h)=>this.api.awaitRequest({command:l.COMMANDS.BULKSIGN,data:{txns:f,opts:h}}));A(this,"bulkSubmitAndWait",(f,h,d)=>this.api.awaitRequest({command:l.COMMANDS.BULKSUBMIT,data:{address:f,txblobs:h,opts:d}}));A(this,"bulkSignAndSubmitAndWait",(f,h)=>this.api.awaitRequest({command:l.COMMANDS.BULK,data:{txns:f,opts:h}}));A(this,"encryptAndWait",{aes:(f,h,d)=>this.api.awaitRequest({command:l.COMMANDS.ENCRYPT,data:{address:f,data:h,opts:d}})});A(this,"decryptAndAwait",{aes:(f,h,d)=>this.api.awaitRequest({command:l.COMMANDS.DECRYPT,data:{address:f,hex:h,opts:d}})});A(this,"isLockedAndWait",()=>this.api.awaitRequest({command:l.COMMANDS.IS_LOCKED}));A(this,"versionAndWait",()=>this.api.awaitRequest({command:l.COMMANDS.VERSION}));A(this,"verifyAndWait",f=>this.api.awaitRequest({command:l.COMMANDS.VERIFY,data:{hex:f}}));A(this,"connect",f=>this.mount.loop(f));A(this,"detect",f=>this.mount.loop(f));this.sdk=f,this.api=f.api,this.session=f.session,this.mount=f.mount}}},9386:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Sync=i.Async=void 0;var a=o(614),c=(Object.defineProperty(i,"Async",{enumerable:!0,get:function(){return a.Async}}),o(8258));Object.defineProperty(i,"Sync",{enumerable:!0,get:function(){return c.Sync}})},8258:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(f,h,d,p){p===void 0&&(p=d);var m=Object.getOwnPropertyDescriptor(h,d);m&&("get"in m?h.__esModule:!m.writable&&!m.configurable)||(m={enumerable:!0,get:function(){return h[d]}}),Object.defineProperty(f,p,m)}:function(f,h,d,p){f[p=p===void 0?d:p]=h[d]}),c=this&&this.__setModuleDefault||(Object.create?function(f,h){Object.defineProperty(f,"default",{enumerable:!0,value:h})}:function(f,h){f.default=h}),u=this&&this.__importStar||function(f){if(f&&f.__esModule)return f;var h={};if(f!=null)for(var d in f)d!=="default"&&Object.prototype.hasOwnProperty.call(f,d)&&a(h,f,d);return c(h,f),h};Object.defineProperty(i,"__esModule",{value:!0}),i.Sync=void 0;const l=u(o(9815));i.Sync=class{constructor(f){A(this,"sdk");A(this,"api");A(this,"session");A(this,"mount");A(this,"signIn",f=>this.api.request({command:l.COMMANDS.SIGN,data:{tx:{TransactionType:"SignIn"},hex:f}}));A(this,"sign",(f,h)=>this.api.request({command:l.COMMANDS.SIGN,data:{tx:f,opts:h}}));A(this,"submit",(f,h,d)=>this.api.request({command:l.COMMANDS.SUBMIT,data:{address:f,txblob:h,opts:d}}));A(this,"signAndSubmit",(f,h)=>this.api.request({command:l.COMMANDS.SIGNANDSUBMIT,data:{tx:f,opts:h}}));A(this,"bulkSign",(f,h)=>this.api.request({command:l.COMMANDS.BULKSIGN,data:{txns:f,opts:h}}));A(this,"bulkSubmit",(f,h,d)=>this.api.request({command:l.COMMANDS.BULKSUBMIT,data:{address:f,txblobs:h,opts:d}}));A(this,"encrypt",{aes:(f,h,d)=>this.api.request({command:l.COMMANDS.ENCRYPT,data:{address:f,data:h,opts:d}})});A(this,"decrypt",{aes:(f,h,d)=>this.api.request({command:l.COMMANDS.DECRYPT,data:{address:f,hex:h,opts:d}})});A(this,"bulkSignAndSubmit",(f,h)=>this.api.request({command:l.COMMANDS.BULK,data:{txns:f,opts:h}}));A(this,"getResponse",f=>this.session.responses.get(f));A(this,"isConnected",()=>this.mount.isDetected);A(this,"isInstalled",()=>this.mount.isDetected);A(this,"isLocked",()=>this.api.request({command:l.COMMANDS.IS_LOCKED}));A(this,"isOpen",()=>this.session.isOpen);A(this,"version",()=>this.api.request({command:l.COMMANDS.VERSION}));A(this,"verify",f=>this.api.request({command:l.COMMANDS.VERIFY,data:{hex:f}}));A(this,"getAddress",()=>this.session.address);A(this,"getNetwork",()=>this.session.network);A(this,"getUser",()=>this.session.user);this.sdk=f,this.api=f.api,this.session=f.session,this.mount=f.mount}}},6515:function(s,i,o){var p,m,v;var a=this&&this.__createBinding||(Object.create?function(S,T,g,w){w===void 0&&(w=g);var k=Object.getOwnPropertyDescriptor(T,g);k&&("get"in k?T.__esModule:!k.writable&&!k.configurable)||(k={enumerable:!0,get:function(){return T[g]}}),Object.defineProperty(S,w,k)}:function(S,T,g,w){S[w=w===void 0?g:w]=T[g]}),c=this&&this.__setModuleDefault||(Object.create?function(S,T){Object.defineProperty(S,"default",{enumerable:!0,value:T})}:function(S,T){S.default=T}),u=this&&this.__importStar||function(S){if(S&&S.__esModule)return S;var T={};if(S!=null)for(var g in S)g!=="default"&&Object.prototype.hasOwnProperty.call(S,g)&&a(T,S,g);return c(T,S),T},l=this&&this.__importDefault||function(S){return S&&S.__esModule?S:{default:S}},l=(Object.defineProperty(i,"__esModule",{value:!0}),i.Api=void 0,l(o(7531)));const f=u(o(9815)),h=o(266);class d extends l.default{constructor(g){super();A(this,"sdk");A(this,"active",new Map);A(this,"uuid");A(this,"connected");A(this,"target");A(this,"timestamp");Ur(this,p,g=>{var O,B,N,$;try{if(window&&(!window||g.source===window&&g.source&&g.origin===window.location.origin)&&g.data){var w=((O=g.data)==null?void 0:O.type)||void 0,k=((B=g.data)==null?void 0:B.response)||void 0,_=((N=g.data)==null?void 0:N.app)||void 0;if((w!=="request"||_===this.sdk.app)&&w!==f.TYPES.UPDATE)return w===f.TYPES.EVENT&&"type"in g.data?ge(this,m).call(this,g.data):(k&&k.type===f.TYPES.RESPONSE&&this.emit(f.EVENTS.RESPONSE,g.data),k&&k.type===f.EVENTS.RESPONSE&&this.active.get(k.id)?($=this.active.get(k.id))==null?void 0:$.resolve(g.data):void 0)}}catch{}});Ur(this,m,g=>{g.event===f.EVENTS.PING&&this.emit(f.EVENTS.PING),g.event===f.EVENTS.CLOSE&&this.emit(f.EVENTS.CLOSE),g.event===f.EVENTS.OPEN&&this.emit(f.EVENTS.OPEN),g.event===f.EVENTS.SIGNOUT&&this.emit(f.EVENTS.SIGNOUT),g.event===f.EVENTS.USER_CHANGE&&this.emit(f.EVENTS.USER_CHANGE,g.data),g.event===f.EVENTS.NETWORK_CHANGE&&this.emit(f.EVENTS.NETWORK_CHANGE,g.data)});Ur(this,v,async g=>{var w=await new Promise((k,_)=>{this.active.set(g.id,{resolve:k,reject:_}),window&&window.postMessage(g)});return this.active.delete(g.id),w});A(this,"awaitRequest",async g=>{try{return await ge(this,v).call(this,{app:this.sdk.app,type:f.TYPES.REQUEST,id:(0,h.uuid)(),...g})}catch(w){throw w}});A(this,"request",g=>{try{var w=(0,h.uuid)();return ge(this,v).call(this,{app:this.sdk.app,type:f.TYPES.REQUEST,id:w,...g}),w}catch(k){throw k}});this.sdk=g,this.uuid=(0,h.uuid)(),this.connected=!1,this.timestamp=Date.now(),typeof window<"u"&&(this.target=window.origin,window.addEventListener("message",ge(this,p)))}}p=new WeakMap,m=new WeakMap,v=new WeakMap,i.Api=d},2585:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Env=void 0;class o{constructor(){A(this,"isAndroid",!1);A(this,"isIos",!1);A(this,"isOpera",!1);A(this,"isWindows",!1);A(this,"isSSR",!1);A(this,"isXApp",!1);A(this,"isMobile",!1);A(this,"isDesktop",!1);typeof window<"u"&&(this.isAndroid=!!(window!=null&&window.navigator.userAgent.match(/Android/i)),this.isIos=!!(window!=null&&window.navigator.userAgent.match(/iPhone|iPad|iPod/i)),this.isOpera=!!(window!=null&&window.navigator.userAgent.match(/Opera Mini/i)),this.isWindows=!!(window!=null&&window.navigator.userAgent.match(/IEMobile/i)),this.isSSR=!!(window!=null&&window.navigator.userAgent.match(/SSR/i)),this.isXApp=!!(window!=null&&window.navigator.userAgent.match(/xumm/i)),this.isMobile=!!(this.isAndroid||this.isIos||this.isOpera||this.isWindows),this.isDesktop=!this.isMobile&&!this.isSSR)}}i.Env=o,i.default=new o},6962:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(d,p,m,v){v===void 0&&(v=m);var S=Object.getOwnPropertyDescriptor(p,m);S&&("get"in S?p.__esModule:!S.writable&&!S.configurable)||(S={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(d,v,S)}:function(d,p,m,v){d[v=v===void 0?m:v]=p[m]}),c=this&&this.__setModuleDefault||(Object.create?function(d,p){Object.defineProperty(d,"default",{enumerable:!0,value:p})}:function(d,p){d.default=p}),u=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var p={};if(d!=null)for(var m in d)m!=="default"&&Object.prototype.hasOwnProperty.call(d,m)&&a(p,d,m);return c(p,d),p},l=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}},l=(Object.defineProperty(i,"__esModule",{value:!0}),i.CustomEvents=i.CustomEmitter=void 0,l(o(7531)));const f=u(o(9815));class h extends l.default{}i.CustomEmitter=h,i.CustomEvents=class extends h{constructor(p){super();A(this,"sdk");A(this,"api");this.sdk=p,this.api=this.sdk.api,this.api.on(f.EVENTS.PING,()=>this.sdk.emit(f.EVENTS.PING)),this.api.on(f.EVENTS.RESPONSE,m=>{this.sdk.emit(f.EVENTS.RESPONSE,m),this.sdk.emit(f.EVENTS.ALL,{type:f.EVENTS.RESPONSE,resp:m})}),this.api.on(f.EVENTS.USER_CHANGE,m=>{this.sdk.emit(f.EVENTS.USER_CHANGE,m),this.sdk.emit(f.EVENTS.ALL,{type:f.EVENTS.USER_CHANGE,user:m})}),this.api.on(f.EVENTS.NETWORK_CHANGE,m=>{this.sdk.emit(f.EVENTS.NETWORK_CHANGE,m),this.sdk.emit(f.EVENTS.ALL,{type:f.EVENTS.NETWORK_CHANGE,network:m})}),this.api.on(f.EVENTS.OPEN,()=>{this.sdk.emit(f.EVENTS.OPEN),this.sdk.emit(f.EVENTS.ALL,{type:f.EVENTS.OPEN})}),this.api.on(f.EVENTS.CLOSE,()=>{this.sdk.emit(f.EVENTS.CLOSE),this.sdk.emit(f.EVENTS.ALL,{type:f.EVENTS.CLOSE})}),this.api.on(f.EVENTS.SIGNOUT,()=>{this.sdk.emit(f.EVENTS.SIGNOUT),this.sdk.emit(f.EVENTS.ALL,{type:f.EVENTS.SIGNOUT})})}}},5149:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Session=i.Scheme=i.Mount=i.CustomEvents=i.CustomEmitter=i.Env=i.Api=void 0;var a=o(6515),c=(Object.defineProperty(i,"Api",{enumerable:!0,get:function(){return a.Api}}),o(2585)),u=(Object.defineProperty(i,"Env",{enumerable:!0,get:function(){return c.Env}}),o(6962)),l=(Object.defineProperty(i,"CustomEmitter",{enumerable:!0,get:function(){return u.CustomEmitter}}),Object.defineProperty(i,"CustomEvents",{enumerable:!0,get:function(){return u.CustomEvents}}),o(288)),f=(Object.defineProperty(i,"Mount",{enumerable:!0,get:function(){return l.Mount}}),o(2821)),h=(Object.defineProperty(i,"Scheme",{enumerable:!0,get:function(){return f.Scheme}}),o(2413));Object.defineProperty(i,"Session",{enumerable:!0,get:function(){return h.Session}})},288:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(p,m,v,S){S===void 0&&(S=v);var T=Object.getOwnPropertyDescriptor(m,v);T&&("get"in T?m.__esModule:!T.writable&&!T.configurable)||(T={enumerable:!0,get:function(){return m[v]}}),Object.defineProperty(p,S,T)}:function(p,m,v,S){p[S=S===void 0?v:S]=m[v]}),c=this&&this.__setModuleDefault||(Object.create?function(p,m){Object.defineProperty(p,"default",{enumerable:!0,value:m})}:function(p,m){p.default=m}),u=this&&this.__importStar||function(p){if(p&&p.__esModule)return p;var m={};if(p!=null)for(var v in p)v!=="default"&&Object.prototype.hasOwnProperty.call(p,v)&&a(m,p,v);return c(m,p),m},l=this&&this.__importDefault||function(p){return p&&p.__esModule?p:{default:p}},l=(Object.defineProperty(i,"__esModule",{value:!0}),i.Mount=void 0,l(o(7531)));const f=o(266),h=u(o(9815));class d extends l.default{constructor(v){super();A(this,"isDetected");A(this,"sdk");A(this,"loop",async v=>new Promise(async(S,T)=>{this.isDetected&&S(!0);var g=Date.now();if(this.sdk.app===h.Projects.titles.embark)for(;;){if(typeof window<"u"&&window.xrpl&&window.xrpl.isEmbark){this.isDetected=window.xrpl.isEmbark,window.embark=Object.assign({},window==null?void 0:window.embark,this.sdk),this.emit("detected"),this.sdk.emit("detected"),S(!0);break}if(await(0,f.sleep)(500),Date.now()>g+(v??1e4)){S(!1);break}}else for(;;){if(typeof window<"u"&&window.xrpl&&window.xrpl.isCrossmark){this.isDetected=window.xrpl.isCrossmark,window.crossmark=Object.assign({},window==null?void 0:window.crossmark,this.sdk),this.emit("detected"),this.sdk.emit("detected"),S(!0);break}if(await(0,f.sleep)(500),Date.now()>g+(v??1e4)){S(!1);break}}}));this.sdk=v,this.loop(1e4)}}i.Mount=d},2821:function(s,i,o){var a=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(i,"__esModule",{value:!0}),i.Scheme=void 0;const c=a(o(2585));i.Scheme={get:(u,l)=>{if(l.startsWith("_"))throw new Error("Access denied");if(c.default.isMobile)throw new Error("Crossmark only available from desktop");return l=u[l],typeof l=="function"?l.bind(u):l},set:(u,l,f)=>{if(l.startsWith("_"))throw new Error("Access denied");return u[l]=f,!0},deleteProperty:(u,l)=>{if(l.startsWith("_"))throw new Error("Access denied");return delete u[l],!0},ownKeys:u=>Object.keys(u).filter(l=>!l.startsWith("_"))}},2413:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(h,d,p,m){m===void 0&&(m=p);var v=Object.getOwnPropertyDescriptor(d,p);v&&("get"in v?d.__esModule:!v.writable&&!v.configurable)||(v={enumerable:!0,get:function(){return d[p]}}),Object.defineProperty(h,m,v)}:function(h,d,p,m){h[m=m===void 0?p:m]=d[p]}),c=this&&this.__setModuleDefault||(Object.create?function(h,d){Object.defineProperty(h,"default",{enumerable:!0,value:d})}:function(h,d){h.default=d}),u=this&&this.__importStar||function(h){if(h&&h.__esModule)return h;var d={};if(h!=null)for(var p in h)p!=="default"&&Object.prototype.hasOwnProperty.call(h,p)&&a(d,h,p);return c(d,h),d};Object.defineProperty(i,"__esModule",{value:!0}),i.Session=void 0;const l=u(o(9815));class f{constructor(d){A(this,"sdk");A(this,"user");A(this,"network");A(this,"address");A(this,"isOpen",!1);A(this,"lastPing");A(this,"state","unactive");A(this,"responses",new Map);A(this,"handleDetect",async()=>{this.network=(await this.sdk.api.awaitRequest({command:l.COMMANDS.NETWORK})).response.data.network,this.user=(await this.sdk.api.awaitRequest({command:l.COMMANDS.USER})).response.data.user,this.address=(await this.sdk.api.awaitRequest({command:l.COMMANDS.ADDRESS})).response.data.address,this.network&&this.user&&this.address&&(this.state="active")});A(this,"handlePing",()=>this.lastPing=Date.now());A(this,"handleClose",()=>this.isOpen=!1);A(this,"handleOpen",()=>this.isOpen=!0);A(this,"handleSignOut",()=>{this.state="unactive",this.address=void 0,this.network=void 0,this.user=void 0});A(this,"handleNetworkChange",d=>{this.network=d.network});A(this,"handleUserChange",d=>{this.user=d.user,this.address=void 0});A(this,"handleResponse",d=>{"address"in d.response.data&&(this.state="active",this.address=d.response.data.address),"network"in d.response.data&&(this.network=d.response.data.network),"user"in d.response.data&&(this.user=d.response.data.user),this.responses.set(d.request.id,d)});this.sdk=d,this.sdk.on(l.EVENTS.PING,this.handlePing),this.sdk.on(l.EVENTS.RESPONSE,this.handleResponse),this.sdk.on(l.EVENTS.USER_CHANGE,this.handleUserChange),this.sdk.on(l.EVENTS.NETWORK_CHANGE,this.handleNetworkChange),this.sdk.on(l.EVENTS.OPEN,this.handleOpen),this.sdk.on(l.EVENTS.CLOSE,this.handleClose),this.sdk.on(l.EVENTS.SIGNOUT,this.handleSignOut),this.sdk.on("detected",this.handleDetect)}}(i.Session=f).prototype.user=void 0,f.prototype.network=void 0,f.prototype.address=void 0},4240:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(h,d,p,m){m===void 0&&(m=p);var v=Object.getOwnPropertyDescriptor(d,p);v&&("get"in v?d.__esModule:!v.writable&&!v.configurable)||(v={enumerable:!0,get:function(){return d[p]}}),Object.defineProperty(h,m,v)}:function(h,d,p,m){h[m=m===void 0?p:m]=d[p]}),c=this&&this.__setModuleDefault||(Object.create?function(h,d){Object.defineProperty(h,"default",{enumerable:!0,value:d})}:function(h,d){h.default=d}),f=this&&this.__importStar||function(h){if(h&&h.__esModule)return h;var d={};if(h!=null)for(var p in h)p!=="default"&&Object.prototype.hasOwnProperty.call(h,p)&&a(d,h,p);return c(d,h),d};Object.defineProperty(i,"__esModule",{value:!0}),i.typings=i.modules=i.vanilla=void 0;const u=o(9616);Object.defineProperty(i,"vanilla",{enumerable:!0,get:function(){return u.Sdk}});var l=f(o(40)),f=(i.modules=l,f(o(9815)));i.typings=f,i.default=l.xmark},2898:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(h,d,p,m){m===void 0&&(m=p);var v=Object.getOwnPropertyDescriptor(d,p);v&&("get"in v?d.__esModule:!v.writable&&!v.configurable)||(v={enumerable:!0,get:function(){return d[p]}}),Object.defineProperty(h,m,v)}:function(h,d,p,m){h[m=m===void 0?p:m]=d[p]}),c=this&&this.__setModuleDefault||(Object.create?function(h,d){Object.defineProperty(h,"default",{enumerable:!0,value:d})}:function(h,d){h.default=d}),f=this&&this.__importStar||function(h){if(h&&h.__esModule)return h;var d={};if(h!=null)for(var p in h)p!=="default"&&Object.prototype.hasOwnProperty.call(h,p)&&a(d,h,p);return c(d,h),d},u=(Object.defineProperty(i,"__esModule",{value:!0}),o(9616)),l=f(o(5149)),f=f(o(9815));i.default=new Proxy(new u.Sdk({project:f.Projects.titles.crossmark}),l.Scheme)},477:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(h,d,p,m){m===void 0&&(m=p);var v=Object.getOwnPropertyDescriptor(d,p);v&&("get"in v?d.__esModule:!v.writable&&!v.configurable)||(v={enumerable:!0,get:function(){return d[p]}}),Object.defineProperty(h,m,v)}:function(h,d,p,m){h[m=m===void 0?p:m]=d[p]}),c=this&&this.__setModuleDefault||(Object.create?function(h,d){Object.defineProperty(h,"default",{enumerable:!0,value:d})}:function(h,d){h.default=d}),f=this&&this.__importStar||function(h){if(h&&h.__esModule)return h;var d={};if(h!=null)for(var p in h)p!=="default"&&Object.prototype.hasOwnProperty.call(h,p)&&a(d,h,p);return c(d,h),d},u=(Object.defineProperty(i,"__esModule",{value:!0}),o(9616)),l=f(o(5149)),f=f(o(9815));i.default=new Proxy(new u.Sdk({project:f.Projects.titles.embark}),l.Scheme)},40:function(s,i,o){var a=this&&this.__importDefault||function(l){return l&&l.__esModule?l:{default:l}},c=(Object.defineProperty(i,"__esModule",{value:!0}),i.embark=i.xmark=void 0,o(2898)),u=(Object.defineProperty(i,"xmark",{enumerable:!0,get:function(){return a(c).default}}),o(477));Object.defineProperty(i,"embark",{enumerable:!0,get:function(){return a(u).default}})},5007:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.uuid=void 0,i.uuid=()=>{let o="",a;for(a=0;a<32;a+=1)switch(a){case 8:case 20:o=(o+="-")+(16*Math.random()|0).toString(16);break;case 12:o=o+"-4";break;case 16:o=(o+="-")+(4*Math.random()|8).toString(16);break;default:o+=(16*Math.random()|0).toString(16)}return o}},266:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.uuid=i.sleep=void 0;var a=o(2200),c=(Object.defineProperty(i,"sleep",{enumerable:!0,get:function(){return a.sleep}}),o(5007));Object.defineProperty(i,"uuid",{enumerable:!0,get:function(){return c.uuid}})},2200:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.sleep=void 0,i.sleep=async o=>{await new Promise(a=>{setTimeout(a,o)})}},2025:(s,i)=>{var o;Object.defineProperty(i,"__esModule",{value:!0}),i.Config=void 0,i.Config=(o=class{},A(o,"config"),o)},7268:(s,i)=>{var o;Object.defineProperty(i,"__esModule",{value:!0}),i.Events=void 0,i.Events=(o=class{},A(o,"GenericEvent"),A(o,"BaseEvent"),A(o,"EventMessage"),A(o,"NetworkEvent"),A(o,"UserEvent"),A(o,"StateEvent"),A(o,"SignoutEvent"),o)},9291:(s,i)=>{var o;Object.defineProperty(i,"__esModule",{value:!0}),i.Models=void 0,i.Models=(o=class{},A(o,"Request"),A(o,"Response"),A(o,"FullResponse"),A(o,"IsConnectedRequest"),A(o,"IsLockedRequest"),A(o,"SignInRequest"),A(o,"IsOpenRequest"),A(o,"SignRequest"),A(o,"VersionRequest"),A(o,"NetworkRequest"),A(o,"UserRequest"),A(o,"AddressRequest"),A(o,"VerifyRequest"),A(o,"SignAndSubmitRequest"),A(o,"SubmitRequest"),A(o,"EncryptRequest"),A(o,"DecryptRequest"),A(o,"IsConnectedResponse"),A(o,"IsLockedResponse"),A(o,"SignInResponse"),A(o,"IsOpenResponse"),A(o,"SignResponse"),A(o,"VersionResponse"),A(o,"AddressResponse"),A(o,"NetworkResponse"),A(o,"UserResponse"),A(o,"VerifyResponse"),A(o,"SignAndSubmitResponse"),A(o,"SubmitResponse"),A(o,"IsConnectedFullResponse"),A(o,"IsLockedFullResponse"),A(o,"SignInFullResponse"),A(o,"IsOpenFullResponse"),A(o,"SignFullResponse"),A(o,"VersionFullResponse"),A(o,"AddressFullResponse"),A(o,"NetworkFullResponse"),A(o,"UserFullResponse"),A(o,"VerifyFullResponse"),A(o,"SignAndSubmitFullResponse"),A(o,"SubmitFullResponse"),A(o,"BulkSubmitRequest"),A(o,"BulkSignRequest"),A(o,"BulkSignAndSubmitRequest"),A(o,"BulkSubmitFullResponse"),A(o,"BulkSignFullResponse"),A(o,"BulkSignAndSubmitFullResponse"),A(o,"BulkSubmitResponse"),A(o,"BulkSignResponse"),A(o,"BulkSignAndSubmitResponse"),A(o,"EncryptResponse"),A(o,"EncryptFullResponse"),A(o,"DecryptResponse"),A(o,"DecryptFullResponse"),A(o,"SenderFullResponse"),A(o,"SenderRequest"),A(o,"SenderResponse"),A(o,"ManagerFullResponse"),A(o,"ManagerRequest"),A(o,"ManagerResponse"),A(o,"AllTransactionRequest"),A(o,"AllTransactionResponse"),A(o,"AllTransactionMetadata"),A(o,"AllTxResponse"),A(o,"AllSubmitResponse"),A(o,"AllTransactionStream"),A(o,"AllTransaction"),A(o,"AllFullTransaction"),A(o,"IndexedTransactionRequest"),A(o,"SignTransaction"),A(o,"SignOpts"),A(o,"CryptOpts"),A(o,"ExtendedSignOpts"),A(o,"Status"),o)},4151:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.CatchAllEvent=i.TYPES=i.EVENTS=i.COMMANDS=i.Extension=void 0;class o{}A(o,"CatchAllEvent"),A(o,"BasicUser"),A(o,"BasicNetwork"),A(o,"CleanExtMessage"),A(o,"CommResponse"),A(o,"CleanResponse"),A(o,"PostMessage"),A(o,"PortMessage"),A(o,"Payload"),A(o,"AppStatus"),A(o,"AllExtMessage"),A(o,"ExtMessage"),A(o,"RequestMessage"),A(o,"ResponseMessage"),A(o,"Targets"),A(o,"Events"),A(o,"Commands"),A(o,"Types");var a,c;i.Extension=o,a=o||(i.Extension=o={}),(c=a.TYPES||(a.TYPES={})).INIT="init",c.REFRESH="refresh",c.DISCONNECT="disconnect",c.PING="ping",c.REQUEST="request",c.RESPONSE="response",c.UPDATE="update",c.EVENT="event",(c=a.COMMANDS||(a.COMMANDS={})).VERSION="version",c.IS_CONNECTED="isConnected",c.IS_LOCKED="isLocked",c.OPEN="open",c.SIGN="sign",c.SIGNANDSUBMIT="sign-and-submit",c.BULKSUBMIT="bulk-submit",c.BULKSIGN="bulk-sign",c.BULK="bulk",c.SUBMIT="submit",c.MANAGER="manager",c.ADDRESS="address",c.NETWORK="network",c.USER="user",c.VERIFY="verify",c.SENDER="sender",c.CHANGENODE="change-node",c.CHANGEUSER="change-user",c.DECRYPT="decrypt",c.ENCRYPT="encrypt",(c=a.EVENTS||(a.EVENTS={})).ACCOUNTS_CHANGED="accountsChanged",c.CHAIN_CHANGED="chainChanged",c.CONNECT="connect",c.DISCONNECT="disconnect",c.MESSAGE="message",c.POPUP_MODE="popup-mode",c.STATE_UPDATE="state-update",c.NETWORK_CHANGE="network-change",c.USER_CHANGE="user-change",c.OPEN="open",c.CLOSE="close",c.PING="ping",c.SIGNIN="signin",c.SIGNOUT="signout",c.RESPONSE="response",c.ALL="all",(c=a.TARGETS||(a.TARGETS={})).CONTENT="content",c.BG="bg",c.POP="pop",i.COMMANDS=o.COMMANDS,i.EVENTS=o.EVENTS,i.TYPES=o.TYPES,i.CatchAllEvent=o.CatchAllEvent},9312:(s,i)=>{var o;Object.defineProperty(i,"__esModule",{value:!0}),i.Types=void 0,i.Types=(o=class{},A(o,"AgreementsSchema"),A(o,"GeneralSchema"),A(o,"NetworkSchema"),A(o,"CardSchema"),A(o,"ContactSchema"),A(o,"ProfileSchema"),A(o,"SecuritySchema"),A(o,"StateSchema"),A(o,"UserSchema"),A(o,"AppSchema"),A(o,"PreferenceSchema"),A(o,"VaultSchema"),A(o,"MountedUserSchema"),A(o,"Blank"),o)},7579:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(f,h,d,p){p===void 0&&(p=d);var m=Object.getOwnPropertyDescriptor(h,d);m&&("get"in m?h.__esModule:!m.writable&&!m.configurable)||(m={enumerable:!0,get:function(){return h[d]}}),Object.defineProperty(f,p,m)}:function(f,h,d,p){f[p=p===void 0?d:p]=h[d]}),c=this&&this.__setModuleDefault||(Object.create?function(f,h){Object.defineProperty(f,"default",{enumerable:!0,value:h})}:function(f,h){f.default=h}),u=this&&this.__importStar||function(f){if(f&&f.__esModule)return f;var h={};if(f!=null)for(var d in f)d!=="default"&&Object.prototype.hasOwnProperty.call(f,d)&&a(h,f,d);return c(h,f),h},u=(Object.defineProperty(i,"__esModule",{value:!0}),i.Types=void 0,u(o(9312)));class l{}A(l,"Api",u),i.Types=l,o=l||(i.Types=l={}),(u=o.TWCardColor||(o.TWCardColor={})).color1="tw-bg-cardGradient1",u.color2="tw-bg-cardGradient2",u.color3="tw-bg-cardGradient3",u.color4="tw-bg-cardGradient4",u.color5="tw-bg-cardGradient5",u.color6="tw-bg-cardGradient6",u.color7="tw-bg-cardGradient7",u.color8="tw-bg-cardGradient8",u.color9="tw-bg-cardGradient9",u.color10="tw-bg-cardGradient10",(u=o.CardColor||(o.CardColor={})).color1="color1",u.color2="color2",u.color3="color3",u.color4="color4",u.color5="color5",u.color6="color6",u.color7="color7",u.color8="color8",u.color9="color9",u.color10="color10",(u=o.NetworkTypes||(o.NetworkTypes={})).main="main",u.live="live",u.test="test",u.dev="dev",u.hooks="hooks",u.experimental="experimental",u.sidechain="sidechain",u.xls30="xls-30d",u.xls38="xls-38d",u.xahautest="xahau-test",(u=o.Protocol||(o.Protocol={})).xrpl="XRPL",u.evm="EVM",u.btc="BTC",u.bsc="BSC",u.ada="ADA",u.sol="SOL",u.usd="USD",(u=o.XRPLExplorers||(o.XRPLExplorers={})).bithomp="bithomp",u.xrplorg="xrpl.org",u.xrplf="xrplf",u.xrpscan="xrpscan",(o.EVMExplorers||(o.EVMExplorers={})).evmSideChain="evm-sidechain",o.networkColorMap={[o.NetworkTypes.main]:"tw-bg-[#38DBFF]",[o.NetworkTypes.live]:"tw-bg-[#38FFDB]",[o.NetworkTypes.test]:"tw-bg-[#DE7EFF]",[o.NetworkTypes.dev]:"tw-bg-[#FFB648]",[o.NetworkTypes.experimental]:"tw-bg-[#FF7B9B]",[o.NetworkTypes.sidechain]:"tw-bg-[#7CFF99]",[o.NetworkTypes.xls30]:"tw-bg-[#FF9C7C]",[o.NetworkTypes.xls38]:"tw-bg-[#C34D27]",[o.NetworkTypes.hooks]:"tw-bg-[#CF4C27]",[o.NetworkTypes.xahautest]:"tw-bg-[#CF4C27]"},o.BithompHost={[o.NetworkTypes.main]:"https://bithomp.com/explorer",[o.NetworkTypes.test]:"https://test.bithomp.com/explorer",[o.NetworkTypes.dev]:"https://dev.bithomp.com/explorer",[o.NetworkTypes.xls30]:"https://amm.bithomp.com/explorer",[o.NetworkTypes.hooks]:"https://beta.bithomp.com/explorer",[o.NetworkTypes.live]:"https://bithomp.com/explorer",[o.NetworkTypes.experimental]:"",[o.NetworkTypes.sidechain]:"",[o.NetworkTypes.xls38]:"",[o.NetworkTypes.xahautest]:"https://test.xahauexplorer.com/explorer"},o.XrplfHost={[o.NetworkTypes.main]:"https://explorer.xrplf.org",[o.NetworkTypes.test]:"https://explorer-testnet.xrplf.org",[o.NetworkTypes.hooks]:"https://hooks-testnet-v3-explorer.xrpl-labs.com",[o.NetworkTypes.dev]:"",[o.NetworkTypes.xls30]:"",[o.NetworkTypes.live]:"",[o.NetworkTypes.experimental]:"",[o.NetworkTypes.sidechain]:"",[o.NetworkTypes.xls38]:"",[o.NetworkTypes.xahautest]:"https://explorer.xahau-test.net"},o.XrplOrgHost={[o.NetworkTypes.main]:"https://livenet.xrpl.org",[o.NetworkTypes.test]:"https://testnet.xrpl.org",[o.NetworkTypes.dev]:"https://devnet.xrpl.org",[o.NetworkTypes.xls30]:"",[o.NetworkTypes.hooks]:"",[o.NetworkTypes.live]:"",[o.NetworkTypes.experimental]:"",[o.NetworkTypes.sidechain]:"",[o.NetworkTypes.xls38]:"",[o.NetworkTypes.xahautest]:""},o.XRPScanHost={[o.NetworkTypes.main]:"https://xrpscan.com",[o.NetworkTypes.test]:"",[o.NetworkTypes.dev]:"",[o.NetworkTypes.xls30]:"",[o.NetworkTypes.hooks]:"",[o.NetworkTypes.live]:"",[o.NetworkTypes.experimental]:"",[o.NetworkTypes.sidechain]:"",[o.NetworkTypes.xls38]:"",[o.NetworkTypes.xahautest]:""},o.EvmSideChainHost={[o.NetworkTypes.dev]:"https://evm-sidechain.xrpl.org",[o.NetworkTypes.main]:"",[o.NetworkTypes.test]:"",[o.NetworkTypes.xls30]:"",[o.NetworkTypes.hooks]:"",[o.NetworkTypes.live]:"",[o.NetworkTypes.experimental]:"",[o.NetworkTypes.sidechain]:"",[o.NetworkTypes.xls38]:"",[o.NetworkTypes.xahautest]:""},o.ExplorerAddressPath={[o.XRPLExplorers.bithomp]:"",[o.XRPLExplorers.xrplorg]:"/address",[o.XRPLExplorers.xrplf]:"",[o.XRPLExplorers.xrpscan]:"/account",[o.EVMExplorers.evmSideChain]:"/address"},o.ExplorerTxPath={[o.XRPLExplorers.bithomp]:"",[o.XRPLExplorers.xrplorg]:"/transactions",[o.XRPLExplorers.xrplf]:"/tx",[o.XRPLExplorers.xrpscan]:"/tx",[o.EVMExplorers.evmSideChain]:"/tx"},o.availableProtocols=[o.Protocol.xrpl,o.Protocol.evm]},2083:(s,i,o)=>{var a;Object.defineProperty(i,"__esModule",{value:!0}),i.Types=void 0,o(7579).Types.Api.Types,i.Types=(a=class{},A(a,"AgreementsSchema"),A(a,"GeneralSchema"),A(a,"NodeSchema"),A(a,"CardSchema"),A(a,"ContactSchema"),A(a,"ProfileSchema"),A(a,"SecuritySchema"),A(a,"StateSchema"),A(a,"UserSchema"),A(a,"AppSchema"),A(a,"PreferenceSchema"),A(a,"VaultSchema"),A(a,"MountedUserSchema"),A(a,"SecurityTypes"),A(a,"SecurityLevel"),A(a,"Blank"),a)},4855:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Card=void 0;class o{}A(o,"MappedAddresses"),A(o,"ThemeArray"),A(o,"Color");var a,c;i.Card=o,i=o||(i.Card=o={}),(a=i.TWCardColor||(i.TWCardColor={})).color1="tw-bg-cardGradient1",a.color2="tw-bg-cardGradient2",a.color3="tw-bg-cardGradient3",a.color4="tw-bg-cardGradient4",a.color5="tw-bg-cardGradient5",a.color6="tw-bg-cardGradient6",a.color7="tw-bg-cardGradient7",a.color8="tw-bg-cardGradient8",a.color9="tw-bg-cardGradient9",a.color10="tw-bg-cardGradient10",(c=a=i.cardColorTheme||(i.cardColorTheme={})).dark="Dark",c.light="Light",i.cardColorBg={[a.light]:"tw-bg-black",[a.dark]:"tw-bg-white"},i.cardColorStroke={[a.light]:"tw-stroke-black",[a.dark]:"tw-stroke-white"},i.cardColorText={[a.light]:"tw-text-black",[a.dark]:"tw-text-white"},i.cardColorFill={[a.light]:"tw-fill-black",[a.dark]:"tw-fill-white"},(c=i.CardColor||(i.CardColor={})).color1="color1",c.color2="color2",c.color3="color3",c.color4="color4",c.color5="color5",c.color6="color6",c.color7="color7",c.color8="color8",c.color9="color9",c.color10="color10"},4284:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.AES_CBC=void 0;var a=o(6914);i.AES_CBC=class{constructor(){A(this,"algo");A(this,"type",a.AlgoTypes.aes_cbc);A(this,"iv");A(this,"derivation");A(this,"encrypt");A(this,"decrypt")}}},410:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.AES_GCM=void 0;var a=o(6914);i.AES_GCM=class{constructor(){A(this,"algo");A(this,"type",a.AlgoTypes.aes_gcm);A(this,"iv");A(this,"tag");A(this,"derivation");A(this,"encrypt");A(this,"decrypt")}}},6914:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.AlgoTypes=void 0,i.AlgoTypes={standard:"sha512",pbkdf2:"pbkdf2-sha512",aes_cbc:"aes-512-cbc",aes_gcm:"aes-512-gcm"}},2625:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Standard=i.PBKDF2=i.AES_CBC=i.AES_GCM=void 0;var a=o(410),c=(Object.defineProperty(i,"AES_GCM",{enumerable:!0,get:function(){return a.AES_GCM}}),o(4284)),u=(Object.defineProperty(i,"AES_CBC",{enumerable:!0,get:function(){return c.AES_CBC}}),o(1055)),l=(Object.defineProperty(i,"PBKDF2",{enumerable:!0,get:function(){return u.PBKDF2}}),o(8633));Object.defineProperty(i,"Standard",{enumerable:!0,get:function(){return l.Standard}})},1055:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.PBKDF2=void 0;var a=o(6914);i.PBKDF2=class{constructor(){A(this,"type",a.AlgoTypes.pbkdf2);A(this,"iterations");A(this,"keylet");A(this,"iv");A(this,"encrypt")}}},8633:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Standard=void 0;var a=o(6914);i.Standard=class{constructor(){A(this,"type",a.AlgoTypes.standard);A(this,"encrypt")}}},4575:function(s,i,d){var a=this&&this.__createBinding||(Object.create?function(m,v,S,T){T===void 0&&(T=S);var g=Object.getOwnPropertyDescriptor(v,S);g&&("get"in g?v.__esModule:!g.writable&&!g.configurable)||(g={enumerable:!0,get:function(){return v[S]}}),Object.defineProperty(m,T,g)}:function(m,v,S,T){m[T=T===void 0?S:T]=v[S]}),c=this&&this.__setModuleDefault||(Object.create?function(m,v){Object.defineProperty(m,"default",{enumerable:!0,value:v})}:function(m,v){m.default=v}),h=this&&this.__importStar||function(m){if(m&&m.__esModule)return m;var v={};if(m!=null)for(var S in m)S!=="default"&&Object.prototype.hasOwnProperty.call(m,S)&&a(v,m,S);return c(v,m),v},u=(Object.defineProperty(i,"__esModule",{value:!0}),i.Types=void 0,d(1437)),l=h(d(2083)),f=h(d(4855)),h=h(d(2789)),d=d(2164);class p{}A(p,"AllNetworks",u.AllNetworks),A(p,"AllNodeTypes",u.AllNetworks.AllNodeTypes),A(p,"AllNodeExplorers",u.AllNetworks.AllNodeExplorers),A(p,"AllProtocols",d.Protocols),A(p,"Api",l),A(p,"Card",f.Card),A(p,"Security",h.Security),A(p,"BasicNetwork"),A(p,"BasicUser"),A(p,"NodeTypes"),A(p,"NodeExplorers"),A(p,"Protocols"),A(p,"Networks"),A(p,"Icons"),A(p,"EncryptionTypes"),A(p,"EncryptTypes"),A(p,"CardEncryptionTypes"),A(p,"PasscodeEncryptionTypes"),A(p,"availableProtocols",[d.Protocols.xrpl,d.Protocols.evm]),A(p,"NetworkIdentifiers",{[u.AllNetworks.NetworkLabels.xrpl]:u.AllNetworks.XrplLedger,[u.AllNetworks.NetworkLabels.xevm]:u.AllNetworks.Xevm,[u.AllNetworks.NetworkLabels.xahau]:u.AllNetworks.Xahau}),i.Types=p},8950:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.NetworkIcons=void 0,i.NetworkIcons={xrpl:"/assets/chains/xrpl/info/logo.png",xevm:"/assets/chains/xevm/info/logo.jpg",xahau:"/assets/chains/xahau/info/logo.jpg"}},7782:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.NetworkLabels=void 0,i.NetworkLabels={xrpl:"xrp ledger",xevm:"xevm sidechain",xahau:"xahau"}},1437:(s,i,f)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.AllNetworks=void 0;var a=f(1396),c=f(1743),u=f(4942),l=f(8950),f=f(7782),h=a.XahauNetwork.NetworkTypes,d=c.XrplLedgerNetwork.NetworkTypes,p=u.XevmNetwork.NetworkTypes,m=a.XahauNetwork.Explorers,v=c.XrplLedgerNetwork.Explorers,S=u.XevmNetwork.Explorers;class T{}A(T,"Xahau",a.XahauNetwork),A(T,"XrplLedger",c.XrplLedgerNetwork),A(T,"Xevm",u.XevmNetwork),A(T,"AllNodeTypes",{xahau:h,xrpl:d,xevm:p}),A(T,"AllNodeExplorers",{xahauExpl:m,xrplExpl:v,xevmExpl:S}),A(T,"NetworkLabels",f.NetworkLabels),A(T,"NetworkIcons",l.NetworkIcons),i.AllNetworks=T},1396:(s,i,l)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.XahauNetwork=void 0;var a,c=l(2164),u=l(8950),l=l(7782);class f{}A(f,"protocol",c.Protocols.xrpl),A(f,"Types"),A(f,"label",l.NetworkLabels.xahau),A(f,"icon",u.NetworkIcons.xahau),A(f,"asset","XAH"),A(f,"active",!0),A(f,"defaultReserves",{base:"1",inc:"0.2"}),i.XahauNetwork=f,a=f||(i.XahauNetwork=f={}),(c=a.NetworkTypes||(a.NetworkTypes={})).mainnet="mainnet",c.testnet="testnet",c.devnet="devnet",(c=a.Explorers||(a.Explorers={})).bithomp="bithomp",c.xrplf="xrplf",c.xrplorg="xrpl.org",a.colors={[a.NetworkTypes.mainnet]:"tw-bg-[#38DBFF]",[a.NetworkTypes.devnet]:"tw-bg-[#38FFDB]",[a.NetworkTypes.testnet]:"tw-bg-[#DE7EFF]"},a.BithompHost={[a.NetworkTypes.mainnet]:"https://xahauexplorer.com",[a.NetworkTypes.testnet]:"https://test.xahauexplorer.com",[a.NetworkTypes.devnet]:""},a.XrplfHost={[a.NetworkTypes.mainnet]:"https://explorer.xahau.network",[a.NetworkTypes.testnet]:"https://explorer.xahau-test.net",[a.NetworkTypes.devnet]:""},a.XrplOrgHost={[a.NetworkTypes.mainnet]:"https://xahau.xrpl.org",[a.NetworkTypes.testnet]:"https://xahau-testnet.xrpl.org",[a.NetworkTypes.devnet]:""},a.Hosts={[a.Explorers.bithomp]:a.BithompHost,[a.Explorers.xrplf]:a.XrplfHost,[a.Explorers.xrplorg]:a.XrplOrgHost},a.ExplorerAddressPath={[a.Explorers.bithomp]:"",[a.Explorers.xrplf]:"/address",[a.Explorers.xrplorg]:"/accounts"},a.ExplorerTxPath={[a.Explorers.bithomp]:"",[a.Explorers.xrplf]:"/tx",[a.Explorers.xrplorg]:"/transactions"},a.getExplorerHost=(h,d)=>h===a.Explorers.bithomp?a.BithompHost[d]:h===a.Explorers.xrplf?a.XrplfHost[d]:h===a.Explorers.xrplorg?a.XrplOrgHost[d]:void 0,a.getExplorerPath=(h,d)=>d==="address"?a.ExplorerAddressPath[h]:d==="tx"?a.ExplorerTxPath[h]:void 0},4942:(s,i,l)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.XevmNetwork=void 0;var a,c=l(2164),u=l(8950),l=l(7782);class f{}A(f,"protocol",c.Protocols.evm),A(f,"Types"),A(f,"label",l.NetworkLabels.xevm),A(f,"icon",u.NetworkIcons.xevm),A(f,"asset","EXRP"),A(f,"active",!1),A(f,"defaultReserves",{base:"0",inc:"0"}),i.XevmNetwork=f,a=f||(i.XevmNetwork=f={}),(c=a.NetworkTypes||(a.NetworkTypes={})).mainnet="mainnet",c.testnet="testnet",c.devnet="devnet",(a.Explorers||(a.Explorers={})).peersyst="peersyst",a.colors={[a.NetworkTypes.mainnet]:"tw-bg-[#38DBFF]",[a.NetworkTypes.testnet]:"tw-bg-[#DE7EFF]",[a.NetworkTypes.devnet]:"tw-bg-[#FFB648]"},a.PeersysHost={[a.NetworkTypes.mainnet]:"",[a.NetworkTypes.testnet]:"",[a.NetworkTypes.devnet]:"https://evm-sidechain.xrpl.org"},a.Hosts={[a.Explorers.peersyst]:a.PeersysHost},a.ExplorerAddressPath={[a.Explorers.peersyst]:"/address"},a.ExplorerTxPath={[a.Explorers.peersyst]:"/tx"},a.getExplorerHost=(h,d)=>{if(h===a.Explorers.peersyst)return a.PeersysHost[d]},a.getExplorerPath=(h,d)=>d==="address"?a.ExplorerAddressPath[h]:d==="tx"?a.ExplorerTxPath[h]:void 0},1743:(s,i,l)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.XrplLedgerNetwork=void 0;var a,c=l(2164),u=l(8950),l=l(7782);class f{}A(f,"protocol",c.Protocols.xrpl),A(f,"Types"),A(f,"label",l.NetworkLabels.xrpl),A(f,"icon",u.NetworkIcons.xrpl),A(f,"asset","XRP"),A(f,"active",!0),A(f,"defaultReserves",{base:"10",inc:"2"}),i.XrplLedgerNetwork=f,a=f||(i.XrplLedgerNetwork=f={}),(c=a.NetworkTypes||(a.NetworkTypes={})).mainnet="mainnet",c.testnet="testnet",c.devnet="devnet",c.xls30d="xls30d",c.xls38d="xls38d",(c=a.Explorers||(a.Explorers={})).bithomp="bithomp",c.xrplorg="xrpl.org",c.xrplf="xrplf",c.xrpscan="xrpscan",a.colors={[a.NetworkTypes.mainnet]:"tw-bg-[#38DBFF]",[a.NetworkTypes.testnet]:"tw-bg-[#DE7EFF]",[a.NetworkTypes.devnet]:"tw-bg-[#FFB648]",[a.NetworkTypes.xls30d]:"tw-bg-[#FF9C7C]",[a.NetworkTypes.xls38d]:"tw-bg-[#C34D27]"},a.BithompHost={[a.NetworkTypes.mainnet]:"https://bithomp.com/explorer",[a.NetworkTypes.testnet]:"https://test.bithomp.com/explorer",[a.NetworkTypes.devnet]:"https://dev.bithomp.com/explorer",[a.NetworkTypes.xls30d]:"https://amm.bithomp.com/explorer",[a.NetworkTypes.xls38d]:""},a.XrplfHost={[a.NetworkTypes.mainnet]:"https://explorer.xrplf.org",[a.NetworkTypes.testnet]:"https://explorer-testnet.xrplf.org",[a.NetworkTypes.devnet]:"",[a.NetworkTypes.xls30d]:"",[a.NetworkTypes.xls38d]:""},a.XrplOrgHost={[a.NetworkTypes.mainnet]:"https://livenet.xrpl.org",[a.NetworkTypes.testnet]:"https://testnet.xrpl.org",[a.NetworkTypes.devnet]:"https://devnet.xrpl.org",[a.NetworkTypes.xls30d]:"",[a.NetworkTypes.xls38d]:""},a.XRPScanHost={[a.NetworkTypes.mainnet]:"https://xrpscan.com",[a.NetworkTypes.testnet]:"",[a.NetworkTypes.devnet]:"",[a.NetworkTypes.xls30d]:"",[a.NetworkTypes.xls38d]:""},a.Hosts={[a.Explorers.bithomp]:a.BithompHost,[a.Explorers.xrplf]:a.XrplfHost,[a.Explorers.xrplorg]:a.XrplOrgHost,[a.Explorers.xrpscan]:a.XRPScanHost},a.ExplorerAddressPath={[a.Explorers.bithomp]:"",[a.Explorers.xrplorg]:"/address",[a.Explorers.xrplf]:"",[a.Explorers.xrpscan]:"/account"},a.ExplorerTxPath={[a.Explorers.bithomp]:"",[a.Explorers.xrplorg]:"/transactions",[a.Explorers.xrplf]:"/tx",[a.Explorers.xrpscan]:"/tx"},a.getExplorerHost=(h,d)=>h===a.Explorers.bithomp?a.BithompHost[d]:h===a.Explorers.xrplf?a.XrplfHost[d]:h===a.Explorers.xrplorg?a.XrplOrgHost[d]:h===a.Explorers.xrpscan?a.XRPScanHost[d]:void 0,a.getExplorerPath=(h,d)=>d==="address"?a.ExplorerAddressPath[h]:d==="tx"?a.ExplorerTxPath[h]:void 0},2164:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Protocols=void 0,i.Protocols={xrpl:"XRPL",evm:"EVM",btc:"BTC",bsc:"BSC",ada:"ADA",sol:"SOL",usd:"USD"}},2789:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Security=void 0;const a=o(2625);class c{}A(c,"EncryptTypes"),A(c,"AlgoTypes",o(6914).AlgoTypes),((i.Security=c)||(i.Security=c={})).AllEncryptionTypes={AES_CBC:a.AES_CBC,AES_GCM:a.AES_GCM,PBKDF2:a.PBKDF2,Standard:a.Standard}},7083:(s,i,o)=>{var a;Object.defineProperty(i,"__esModule",{value:!0}),i.Types=void 0,o(4575).Types.Api.Types,i.Types=(a=class{},A(a,"AgreementsSchema"),A(a,"GeneralSchema"),A(a,"NodeSchema"),A(a,"CardSchema"),A(a,"ContactSchema"),A(a,"ProfileSchema"),A(a,"SecuritySchema"),A(a,"StateSchema"),A(a,"UserSchema"),A(a,"AppSchema"),A(a,"PreferenceSchema"),A(a,"VaultSchema"),A(a,"MountedUserSchema"),A(a,"SecurityTypes"),A(a,"SecurityLevel"),A(a,"Blank"),a)},191:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Apps=void 0;class o{}A(o,"AppTitle"),A(o,"AppTypes"),i.Apps=o,(i=(i=o||(i.Apps=o={})).titles||(i.titles={})).crossmark="crossmark",i.embark="embark"},5659:function(s,i,m){var a=this&&this.__createBinding||(Object.create?function(S,T,g,w){w===void 0&&(w=g);var k=Object.getOwnPropertyDescriptor(T,g);k&&("get"in k?T.__esModule:!k.writable&&!k.configurable)||(k={enumerable:!0,get:function(){return T[g]}}),Object.defineProperty(S,w,k)}:function(S,T,g,w){S[w=w===void 0?g:w]=T[g]}),c=this&&this.__setModuleDefault||(Object.create?function(S,T){Object.defineProperty(S,"default",{enumerable:!0,value:T})}:function(S,T){S.default=T}),p=this&&this.__importStar||function(S){if(S&&S.__esModule)return S;var T={};if(S!=null)for(var g in S)g!=="default"&&Object.prototype.hasOwnProperty.call(S,g)&&a(T,S,g);return c(T,S),T},u=(Object.defineProperty(i,"__esModule",{value:!0}),i.Projects=i.BasicUser=i.BasicNetwork=i.Types=void 0,m(1437)),l=p(m(7083)),f=p(m(4855)),h=p(m(2789)),d=p(m(8084)),p=p(m(191)),m=m(2164);class v{}A(v,"AllNetworks",u.AllNetworks),A(v,"AllNodeTypes",u.AllNetworks.AllNodeTypes),A(v,"AllNodeExplorers",u.AllNetworks.AllNodeExplorers),A(v,"Themes",d),A(v,"Apps",p),A(v,"AllProtocols",m.Protocols),A(v,"Api",l),A(v,"Card",f.Card),A(v,"Security",h.Security),A(v,"BasicNetwork"),A(v,"BasicUser"),A(v,"NodeTypes"),A(v,"NodeExplorers"),A(v,"Protocols"),A(v,"Networks"),A(v,"Icons"),A(v,"EncryptionTypes"),A(v,"EncryptTypes"),A(v,"CardEncryptionTypes"),A(v,"PasscodeEncryptionTypes"),A(v,"availableProtocols",[m.Protocols.xrpl,m.Protocols.evm]),A(v,"NetworkIdentifiers",{[u.AllNetworks.NetworkLabels.xrpl]:u.AllNetworks.XrplLedger,[u.AllNetworks.NetworkLabels.xevm]:u.AllNetworks.Xevm,[u.AllNetworks.NetworkLabels.xahau]:u.AllNetworks.Xahau}),i.Types=v,i.BasicNetwork=v.BasicNetwork,i.BasicUser=v.BasicUser,i.Projects=p.Apps},8084:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Themes=void 0;const a=o(191);class c{}A(c,"ThemeTypes");var u;i.Themes=c,o=c||(i.Themes=c={}),(u=i=o.availableThemes||(o.availableThemes={})).theme1="theme1",u.theme2="theme2",u.theme3="theme3",u.theme4="theme4",u.theme5="theme5",u.theme6="theme6",o.DefaultThemes={[a.Apps.titles.crossmark]:i.theme1,[a.Apps.titles.embark]:i.theme6},o.CrossmarkThemeKey={[i.theme1]:"light",[i.theme2]:"dark",[i.theme3]:"moon",[i.theme4]:"sun",[i.theme5]:"blueberry",[i.theme6]:"treeberry"},o.EmbarkThemeKey={[i.theme1]:"",[i.theme2]:"",[i.theme3]:"",[i.theme4]:"",[i.theme5]:"",[i.theme6]:"treeberry"},o.ThemeKey={[a.Apps.titles.crossmark]:o.CrossmarkThemeKey,[a.Apps.titles.embark]:o.EmbarkThemeKey},o.ToastColor={[i.theme1]:"light",[i.theme2]:"dark",[i.theme3]:"light",[i.theme4]:"light",[i.theme5]:"dark",[i.theme6]:"dark"},o.SpinnerColor={[i.theme1]:"black",[i.theme2]:"white",[i.theme3]:"black",[i.theme4]:"black",[i.theme5]:"light",[i.theme6]:"light"}},2876:function(s,i,l){var a=this&&this.__createBinding||(Object.create?function(h,d,p,m){m===void 0&&(m=p);var v=Object.getOwnPropertyDescriptor(d,p);v&&("get"in v?d.__esModule:!v.writable&&!v.configurable)||(v={enumerable:!0,get:function(){return d[p]}}),Object.defineProperty(h,m,v)}:function(h,d,p,m){h[m=m===void 0?p:m]=d[p]}),c=this&&this.__setModuleDefault||(Object.create?function(h,d){Object.defineProperty(h,"default",{enumerable:!0,value:d})}:function(h,d){h.default=d}),u=this&&this.__importStar||function(h){if(h&&h.__esModule)return h;var d={};if(h!=null)for(var p in h)p!=="default"&&Object.prototype.hasOwnProperty.call(h,p)&&a(d,h,p);return c(d,h),d},u=(Object.defineProperty(i,"__esModule",{value:!0}),i.Types=void 0,u(l(4080))),l=l(5659).Types.Api.Types;class f{}A(f,"AgreementsSchema"),A(f,"GeneralSchema"),A(f,"NodeSchema"),A(f,"ContactSchema"),A(f,"ProfileSchema"),A(f,"AppSchema"),A(f,"PreferenceSchema"),A(f,"VaultSchema"),A(f,"CardSchema"),A(f,"StateSchema"),A(f,"SecuritySchema"),A(f,"UserSchema"),A(f,"MountedUserSchema"),A(f,"SecurityTypes",u),A(f,"SecurityLevel",l.SecurityLevel),A(f,"Blank"),i.Types=f},43:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Apps=void 0;class o{}A(o,"AppTitle"),A(o,"AppTypes"),i.Apps=o,(i=(i=o||(i.Apps=o={})).titles||(i.titles={})).crossmark="crossmark",i.embark="embark"},9455:(s,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Index=void 0,i.Index=class{constructor(){A(this,"algo");A(this,"type");A(this,"opts")}}},3710:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.HashTypes=i.AesTypes=i.Standard=i.Pbkdf2=i.hash=i.aes=void 0;var a=o(9455);Object.defineProperty(i,"aes",{enumerable:!0,get:function(){return a.Index}});const c=o(1261),u=(Object.defineProperty(i,"Standard",{enumerable:!0,get:function(){return c.Index}}),o(4483));Object.defineProperty(i,"Pbkdf2",{enumerable:!0,get:function(){return u.Index}}),i.hash={Pbkdf2:u.Index,Standard:c.Index},i.AesTypes={cbc:"aes-cbc",gcm:"aes-gcm",ctr:"aes-ctr",cfb:"aes-cfb",ecb:"aes-ecb",ofb:"aes-ofb"},i.HashTypes={standard:"hmac256",pbkdf2:"pbkdf2"}},4483:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Index=void 0;var a=o(3710);i.Index=class{constructor(){A(this,"type",a.HashTypes.pbkdf2);A(this,"opts");A(this,"make")}}},1261:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Index=void 0;var a=o(3710);i.Index=class{constructor(){A(this,"type",a.HashTypes.standard);A(this,"make")}}},5541:function(s,i,m){var a=this&&this.__createBinding||(Object.create?function(S,T,g,w){w===void 0&&(w=g);var k=Object.getOwnPropertyDescriptor(T,g);k&&("get"in k?T.__esModule:!k.writable&&!k.configurable)||(k={enumerable:!0,get:function(){return T[g]}}),Object.defineProperty(S,w,k)}:function(S,T,g,w){S[w=w===void 0?g:w]=T[g]}),c=this&&this.__setModuleDefault||(Object.create?function(S,T){Object.defineProperty(S,"default",{enumerable:!0,value:T})}:function(S,T){S.default=T}),p=this&&this.__importStar||function(S){if(S&&S.__esModule)return S;var T={};if(S!=null)for(var g in S)g!=="default"&&Object.prototype.hasOwnProperty.call(S,g)&&a(T,S,g);return c(T,S),T},u=(Object.defineProperty(i,"__esModule",{value:!0}),i.AllHashTypes=i.AllEncryptionTypes=i.Projects=i.BasicUser=i.BasicNetwork=i.Types=void 0,m(1437)),l=p(m(2876)),f=p(m(4855)),h=p(m(4080)),d=p(m(2897)),p=p(m(43)),m=m(2164);class v{}A(v,"AllNetworks",u.AllNetworks),A(v,"AllNodeTypes",u.AllNetworks.AllNodeTypes),A(v,"AllNodeExplorers",u.AllNetworks.AllNodeExplorers),A(v,"Themes",d),A(v,"Apps",p),A(v,"AllProtocols",m.Protocols),A(v,"Api",l),A(v,"Card",f.Card),A(v,"Security",h),A(v,"BasicNetwork"),A(v,"BasicUser"),A(v,"NodeTypes"),A(v,"NodeExplorers"),A(v,"Protocols"),A(v,"Networks"),A(v,"Icons"),A(v,"EncryptionTypes"),A(v,"EncryptTypes"),A(v,"HashTypes"),A(v,"CardEncryptionTypes"),A(v,"PasscodeHashTypes"),A(v,"availableProtocols",[m.Protocols.xrpl,m.Protocols.evm]),A(v,"NetworkIdentifiers",{[u.AllNetworks.NetworkLabels.xrpl]:u.AllNetworks.XrplLedger,[u.AllNetworks.NetworkLabels.xevm]:u.AllNetworks.Xevm,[u.AllNetworks.NetworkLabels.xahau]:u.AllNetworks.Xahau}),i.Types=v,i.BasicNetwork=v.BasicNetwork,i.BasicUser=v.BasicUser,i.Projects=p.Apps,i.AllEncryptionTypes=h.AllEncryptionTypes,i.AllHashTypes=h.AllHashTypes},4080:function(s,i,o){var a=this&&this.__createBinding||(Object.create?function(l,f,h,d){d===void 0&&(d=h);var p=Object.getOwnPropertyDescriptor(f,h);p&&("get"in p?f.__esModule:!p.writable&&!p.configurable)||(p={enumerable:!0,get:function(){return f[h]}}),Object.defineProperty(l,d,p)}:function(l,f,h,d){l[d=d===void 0?h:d]=f[h]}),c=this&&this.__setModuleDefault||(Object.create?function(l,f){Object.defineProperty(l,"default",{enumerable:!0,value:f})}:function(l,f){l.default=f}),u=this&&this.__importStar||function(l){if(l&&l.__esModule)return l;var f={};if(l!=null)for(var h in l)h!=="default"&&Object.prototype.hasOwnProperty.call(l,h)&&a(f,l,h);return c(f,l),f},u=(Object.defineProperty(i,"__esModule",{value:!0}),i.AllHashTypes=i.AllEncryptionTypes=void 0,u(o(3710)));i.AllEncryptionTypes={AES_CBC:u.AesTypes.cbc,AES_GCM:u.AesTypes.gcm,AES_CTR:u.AesTypes.ctr,AES_ECB:u.AesTypes.ecb,AES_OFB:u.AesTypes.ofb,AES_CFB:u.AesTypes.cfb},i.AllHashTypes={PBKDF2:u.HashTypes.pbkdf2,Standard:u.HashTypes.standard}},2897:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.Themes=void 0;const a=o(43);class c{}A(c,"ThemeTypes");var u;i.Themes=c,o=c||(i.Themes=c={}),(u=i=o.availableThemes||(o.availableThemes={})).theme1="theme1",u.theme2="theme2",u.theme3="theme3",u.theme4="theme4",u.theme5="theme5",u.theme6="theme6",o.DefaultThemes={[a.Apps.titles.crossmark]:i.theme1,[a.Apps.titles.embark]:i.theme6},o.CrossmarkThemeKey={[i.theme1]:"light",[i.theme2]:"dark",[i.theme3]:"moon",[i.theme4]:"sun",[i.theme5]:"blueberry",[i.theme6]:"treeberry"},o.EmbarkThemeKey={[i.theme1]:"",[i.theme2]:"",[i.theme3]:"",[i.theme4]:"",[i.theme5]:"",[i.theme6]:"treeberry"},o.ThemeKey={[a.Apps.titles.crossmark]:o.CrossmarkThemeKey,[a.Apps.titles.embark]:o.EmbarkThemeKey},o.ToastColor={[i.theme1]:"light",[i.theme2]:"dark",[i.theme3]:"light",[i.theme4]:"light",[i.theme5]:"dark",[i.theme6]:"dark"},o.SpinnerColor={[i.theme1]:"black",[i.theme2]:"white",[i.theme3]:"black",[i.theme4]:"black",[i.theme5]:"light",[i.theme6]:"light"}},9815:(s,i,o)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.HashTypes=i.EncryptionAlgos=i.Projects=i.BasicUser=i.BasicNetwork=i.CatchAllEvent=i.TYPES=i.COMMANDS=i.EVENTS=i.Events=i.Models=i.Config=void 0;var a=o(2025),c=(Object.defineProperty(i,"Config",{enumerable:!0,get:function(){return a.Config}}),o(9291)),u=(Object.defineProperty(i,"Models",{enumerable:!0,get:function(){return c.Models}}),o(7268)),l=(Object.defineProperty(i,"Events",{enumerable:!0,get:function(){return u.Events}}),o(4151)),f=(Object.defineProperty(i,"EVENTS",{enumerable:!0,get:function(){return l.EVENTS}}),Object.defineProperty(i,"COMMANDS",{enumerable:!0,get:function(){return l.COMMANDS}}),Object.defineProperty(i,"TYPES",{enumerable:!0,get:function(){return l.TYPES}}),Object.defineProperty(i,"CatchAllEvent",{enumerable:!0,get:function(){return l.CatchAllEvent}}),o(5541));Object.defineProperty(i,"BasicNetwork",{enumerable:!0,get:function(){return f.BasicNetwork}}),Object.defineProperty(i,"BasicUser",{enumerable:!0,get:function(){return f.BasicUser}}),Object.defineProperty(i,"Projects",{enumerable:!0,get:function(){return f.Projects}}),Object.defineProperty(i,"EncryptionAlgos",{enumerable:!0,get:function(){return f.AllEncryptionTypes}}),Object.defineProperty(i,"HashTypes",{enumerable:!0,get:function(){return f.AllHashTypes}})}},n={};return function s(i){var o=n[i];return o===void 0&&(o=n[i]={exports:{}},r[i].call(o.exports,o,o.exports,s)),o.exports}(4240)})())})(Zv);var aB=Zv.exports;const cB=25*60*60*1e3;class Qv{constructor(e,r,n,s){this.url=typeof e=="string"?new E.Url(e):e,this.auth=n,this.wallet=s,this.client=new Cu.Client(Aw[r],{}),this.relayer=new ti(this.auth,this.url)}isXrplWallet(e){return e instanceof Cu.Wallet}isCrossmarkWallet(e){return e instanceof aB.vanilla}get htlcActorAddress(){return this.isXrplWallet(this.wallet)?this.wallet.classicAddress:this.isCrossmarkWallet(this.wallet)?this.wallet.sync.getAddress()??"":""}async initiate(e){try{return V.isXrplOrderResponse(e)?this.initiateFromOrderResponse(e):this.initiateFromOrder(e)}catch(r){return E.Err(`Failed to initiate: ${String(r)}`)}}async initiateFromOrderResponse(e){try{if(!this.htlcActorAddress)return E.Err("No HTLC actor address found");const r=e.escrow_create_tx,n={TransactionType:"EscrowCreate",Account:r.Account,Amount:r.Amount,Destination:r.Destination,Condition:r.Condition,CancelAfter:r.CancelAfter};return await this.submitTransaction(n)}catch(r){return E.Err(`Failed to initiate from order response: ${String(r)}`)}}async initiateFromOrder(e){try{if(!this.htlcActorAddress)return E.Err("No HTLC actor address found");const{source_swap:r}=e,n=E.trim0x(r.secret_hash),s={Account:this.htlcActorAddress,Amount:r.amount,Destination:r.redeemer,Condition:this.buildCondition(n),CancelAfter:Cu.isoTimeToRippleTime(new Date(new Date(r.created_at).getTime()+cB)),TransactionType:"EscrowCreate"};return await this.submitTransaction(s)}catch(r){return E.Err(`Failed to initiate from order: ${String(r)}`)}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?E.Err(n.error):E.Ok(n.val)}async refund(){return E.Err("Refund is taken care of by the relayer")}async submitTransaction(e){try{this.client.isConnected()||await this.client.connect();const r=this.htlcActorAddress;if(!r)return E.Err("No HTLC actor address found");const n=await this.client.autofill(e);n.Account=r;const s=await this.signPreparedTransaction(n),i=await this.client.submitAndWait(s),o=i.result.meta;return(o==null?void 0:o.TransactionResult)==="tesSUCCESS"?E.Ok(i.result.hash):E.Err(`Transaction failed: ${String((o==null?void 0:o.TransactionResult)??"Unknown error")}`)}catch(r){return E.Err(`Transaction submission failed: ${String(r)}`)}finally{this.client.isConnected()&&await this.client.disconnect()}}async signPreparedTransaction(e){if(this.isXrplWallet(this.wallet))return this.wallet.sign(e).tx_blob;if(this.isCrossmarkWallet(this.wallet))return this.wallet.sync.getAddress()||await this.wallet.async.signInAndWait(),(await this.wallet.async.signAndWait(e)).response.data.txBlob;throw new Error("Unsupported wallet type")}buildCondition(e){return"A0258020"+e.toUpperCase()+"810120"}}const uB=t=>{if(t)if(typeof t=="string"){const e=E.DigestKey.from(t);if(!e.ok)throw new Error(e.error);return e.val}else return t},vm=t=>typeof t=="string"?new E.ApiKey(t):t;class lB{constructor(e={}){const r={stdTTL:e.ttl?e.ttl/1e3:3600,checkperiod:600};this.cache=new c2(r)}makeKey(e,r){return`${e}:${r}`}set(e,r,n,s){const i=this.makeKey(e,r);s?this.cache.set(i,n,s/1e3):this.cache.set(i,n)}get(e,r){const n=this.makeKey(e,r);return this.cache.get(n)}remove(e,r){const n=this.makeKey(e,r);this.cache.del(n)}clear(e){if(e){const r=this.cache.keys().filter(n=>n.startsWith(`${e}:`));this.cache.del(r)}else this.cache.flushAll()}setBitcoinRedeem(e,r,n){this.set("bitcoinRedeem",e,r,n)}getBitcoinRedeem(e){return this.get("bitcoinRedeem",e)}setOrderExecution(e,r,n,s,i){const o=this.makeOrderKey(e,r),a={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:s};this.set("orderExecutor",o,a,i)}getOrderExecution(e,r){const n=this.makeOrderKey(e,r);return this.get("orderExecutor",n)}removeOrderExecution(e,r){const n=this.makeOrderKey(e,r);this.remove("orderExecutor",n)}makeOrderKey(e,r){return`${r}_${e.order_id??e.created_at}`}setSacpCache(e,r,n){this.set("refundSacp",e,r,n)}getSacpCache(e){return this.get("refundSacp",e)}has(e,r){const n=this.makeKey(e,r);return this.cache.has(n)}peek(e,r){return this.get(e,r)}getRemainingTTL(e,r){const n=this.makeKey(e,r),s=this.cache.getTtl(n);if(s===void 0)return-1;const i=Date.now();return Math.max(0,s-i)}}var ca,ua,la,Ce,Oi,Zn;class fB{constructor(e,r,n,s,i,o){Ur(this,ca);Ur(this,ua);Ur(this,la);Ur(this,Ce);Ur(this,Oi);Ur(this,Zn);this.isBackgroundServiceRunning=!1,this.stopBackgroundExecution=null,this.htlcs=r,this.events=o,bs(this,ca,e),bs(this,ua,n),bs(this,la,$i.fromDigestKey(e.digestKey)),bs(this,Ce,new lB),bs(this,Oi,s),bs(this,Zn,i)}async getAddressesFromHTLCs(){var n,s,i,o,a,c,u;const e=new Set;return[(n=this.htlcs.evm)==null?void 0:n.htlcActorAddress,(s=this.htlcs.sui)==null?void 0:s.htlcActorAddress,(i=this.htlcs.solana)==null?void 0:i.htlcActorAddress,(o=this.htlcs.starknet)==null?void 0:o.htlcActorAddress,(a=this.htlcs.bitcoin)==null?void 0:a.htlcActorAddress,(c=this.htlcs.tron)==null?void 0:c.htlcActorAddress,(u=this.htlcs.xrpl)==null?void 0:u.htlcActorAddress].filter(l=>!!l&&l.length>0).forEach(l=>e.add(l.toLowerCase())),Array.from(e)}start(e=5e3,r){this.isBackgroundServiceRunning||this.stopBackgroundExecution||(this.isBackgroundServiceRunning=!0,(async()=>{try{if(r){this.stop();return}const n=await this.execute(e);n&&(this.stopBackgroundExecution=n)}catch(n){console.error("Error starting background executor:",n),this.isBackgroundServiceRunning=!1}})())}stop(){if(this.stopBackgroundExecution){try{this.stopBackgroundExecution()}catch{console.error("Error stopping background executor")}this.stopBackgroundExecution=null}this.isBackgroundServiceRunning=!1}async execute(e=5e3){const r=await this.getAddressesFromHTLCs();r.length===0&&r.push(ge(this,ca).userId.toLowerCase());let n=!1,s=null;const i=async()=>{if(!n){n=!0;try{const o=r.map(async c=>{try{const u=await ge(this,ua).getOrders({from_owner:c,status:V.OrderLifecycle.pending,per_page:500});return u.ok?u.val.data:(this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u.error}`),[])}catch(u){return this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u}`),[]}}),a=await Promise.all(o);this.events.emit("onPendingOrdersChanged",a.flat()),await this.processOrderActions(a.flat())}finally{n=!1}}};return await i(),s=setInterval(i,e),()=>{s&&clearInterval(s)}}async processOrderActions(e){const r=new Set([V.OrderStatus.InitiateDetected,V.OrderStatus.AwaitingRefund,V.OrderStatus.Initiated,V.OrderStatus.RefundDetected,V.OrderStatus.Refunded,V.OrderStatus.Expired]),n=e.map(async s=>{try{V.isBitcoin(s.source_swap.chain)&&r.has(s.status)&&!V.isCompleted(s)&&await this.postRefundSACP(s),V.parseAction(s)===V.OrderAction.Redeem&&await this.handleRedeemAction(s)}catch(i){this.events.emit("error",s,`Error processing order ${s.order_id}: ${i}`)}});await Promise.all(n)}async handleRedeemAction(e){const r=await ge(this,la).generateSecret(e.nonce);if(!r.ok){this.events.emit("error",e,r.error);return}const n=E.trim0x(r.val.secretHash),s=E.trim0x(e.source_swap.secret_hash);if(n!==s){this.events.emit("log",e.order_id,"skipping redeem: secret hash mismatch");return}const i=r.val.secret,o=V.getBlockchainType(e.destination_swap.chain),c={[V.BlockchainType.evm]:()=>this.evmRedeem(e,i),[V.BlockchainType.bitcoin]:()=>this.btcRedeem(e,i),[V.BlockchainType.starknet]:()=>this.starknetRedeem(e,i),[V.BlockchainType.solana]:()=>this.solRedeem(e,i),[V.BlockchainType.xrpl]:()=>this.xrplRedeem(e,i),[V.BlockchainType.sui]:()=>this.suiRedeem(e,i),[V.BlockchainType.tron]:()=>this.tronRedeem(e,i)}[o];c?await c():this.events.emit("error",e,`Unsupported chain: ${e.destination_swap.chain}`)}async evmRedeem(e,r){if(this.events.emit("log",e.order_id,"executing evm redeem"),ge(this,Ce).getOrderExecution(e,V.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.evm){this.events.emit("error",e,"EVM HTLC is required");return}const s=await this.htlcs.evm.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,s.val),this.events.emit("success",e,V.OrderAction.Redeem,s.val)}async starknetRedeem(e,r){if(this.events.emit("log",e.order_id,"executing starknet redeem"),ge(this,Ce).getOrderExecution(e,V.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.starknet){this.events.emit("error",e,"Starknet HTLC is required");return}const s=await this.htlcs.starknet.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,s.val),this.events.emit("success",e,V.OrderAction.Redeem,s.val))}async solRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sol redeem"),ge(this,Ce).getOrderExecution(e,V.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.solana){this.events.emit("error",e,"Solana HTLC is required");return}const s=await this.htlcs.solana.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,s.val),this.events.emit("success",e,V.OrderAction.Redeem,s.val))}async suiRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sui redeem"),ge(this,Ce).getOrderExecution(e,V.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.sui){this.events.emit("error",e,"Sui HTLC is required");return}const s=await this.htlcs.sui.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,s.val),this.events.emit("success",e,V.OrderAction.Redeem,s.val))}async tronRedeem(e,r){if(this.events.emit("log",e.order_id,"executing tron redeem"),ge(this,Ce).getOrderExecution(e,V.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.tron){this.events.emit("error",e,"Tron HTLC is required");return}const s=await this.htlcs.tron.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,s.val),this.events.emit("success",e,V.OrderAction.Redeem,s.val))}async xrplRedeem(e,r){if(this.events.emit("log",e.order_id,"executing xrpl redeem"),ge(this,Ce).getOrderExecution(e,V.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.xrpl){this.events.emit("error",e,"XRPL HTLC is required");return}const s=await this.htlcs.xrpl.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(ge(this,Ce).setOrderExecution(e,V.OrderAction.Redeem,s.val),this.events.emit("success",e,V.OrderAction.Redeem,s.val))}async btcRedeem(e,r){var a,c;const n=(a=this.htlcs.bitcoin)==null?void 0:a.getProvider();if(!n){this.events.emit("error",e,"Bitcoin provider not found");return}const s=ge(this,Ce).getBitcoinRedeem(e.order_id),i=(c=e.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:c.split(":").at(0);if(!i){this.events.emit("error",e,"Failed to get initiate_tx_hash");return}let o=!1;if(s)if(s.redeemedFromUTXO&&s.redeemedFromUTXO!==i)o=!0,this.events.emit("log",e.order_id,"rbf btc redeem");else if(s.redeemedAt&&Date.now()-s.redeemedAt>1e3*60*15)this.events.emit("log",e.order_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.events.emit("log",e.order_id,"btcRedeem: already redeemed");return}else if(e.destination_swap.redeem_tx_hash&&!Number(e.destination_swap.redeem_block_number))try{const u=await(await n).getTransaction(e.destination_swap.redeem_tx_hash);let l=!1;for(const f of u.vin)if(f.txid===i){l=!0;break}if(l){this.events.emit("log",e.order_id,"already a valid redeem");let f=0;try{const[h]=await(await n).getTransactionTimes([e.destination_swap.redeem_tx_hash]);h!==0&&(f=h)}catch{f=Date.now()}ge(this,Ce).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:f,redeemTxHash:e.destination_swap.redeem_tx_hash});return}o=!0}catch(u){if(u.message.includes("Transaction not found"))o=!0;else{this.events.emit("error",e,"Failed to get redeem tx: "+u);return}}this.events.emit("log",e.order_id,"executing btc redeem");try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const u=await this.htlcs.bitcoin.getRedeemHex(e,E.trim0x(r),o?[i]:[]);if(!u.ok){this.events.emit("error",e,"Failed to get redeem hex");return}const l=await this.broadcastRedeemTx(u.val,e.order_id);if(!l.ok){this.events.emit("error",e,l.error||"Failed to broadcast redeem tx");return}o?(this.events.emit("log",e.order_id,"rbf: btc redeem success"),this.events.emit("rbf",e,l.val)):this.events.emit("success",e,V.OrderAction.Redeem,l.val),ge(this,Ce).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:l.val})}catch(u){this.events.emit("error",e,"Failed btc redeem: "+u)}}async postRefundSACP(e){if(e.source_swap.delegate)try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const n=await ge(this,Oi).getAuthHeaders();if(n.error){this.events.emit("error",e,"Failed to get auth headers: "+n.error);return}const s=await E.Fetcher.post(new E.Url(ge(this,Zn).baseurl).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:e.order_id}),headers:{"Content-Type":"application/json",...n.val}});if(s.error||!s.result){this.events.emit("error",e,"Failed to get hash while posting instant refund SACP: "+s.error);return}const i=await this.htlcs.bitcoin.generateInstantRefundSACPWithHash(s.result),o=new E.Url(ge(this,Zn).baseurl).endpoint("relayer/bitcoin/instant-refund");(await E.Fetcher.post(o,{headers:{"Content-Type":"application/json",...n.val},body:JSON.stringify({order_id:e.order_id,signatures:i.val})})).ok&&ge(this,Ce).setSacpCache(e.order_id,{initTxHash:e.source_swap.initiate_tx_hash})}catch(n){this.events.emit("error",e,"Failed to generate and post SACP: "+n);return}}async broadcastRedeemTx(e,r){try{if(!ge(this,Zn))return E.Err("API not found");const n=new E.Url(ge(this,Zn).relayer).endpoint("/bitcoin/redeem "),s=await ge(this,Oi).getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:e,order_id:r})})).json();return o.status==="Ok"&&o.result?E.Ok(o.result):E.Err(o.error)}catch(n){return E.Err("Failed to broadcast redeem tx: "+n)}}}ca=new WeakMap,ua=new WeakMap,la=new WeakMap,Ce=new WeakMap,Oi=new WeakMap,Zn=new WeakMap;const lo={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},gc={ALL:pe.Transaction.SIGHASH_ALL,NONE:pe.Transaction.SIGHASH_NONE,SINGLE:pe.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:pe.Transaction.SIGHASH_ALL|pe.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:pe.Transaction.SIGHASH_NONE|pe.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY};class Us{constructor(e,r){this._scriptType=e,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(e){const[r,n]=e.split(" "),s=await vp.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await vp.mixed().oneOf(Object.values(gc)).required().validate(parseInt(n));return new Us(s,i)}}const Ss={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(t,e)=>`fee exceeds amount: fee: ${t} > amount: ${e}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:t=>`swap not expired. Need ${t} more blocks`,MIN_AMOUNT:t=>`amount is too low. Minimum amount is ${t}`,INSUFFICIENT_FUNDS:(t,e)=>`insufficient funds, need ${e} but got ${t}`,AmtPlusFeeExceedsBalance:(t,e,r)=>`amount + fee exceeds balance. Need ${t+e} but got ${r}`},go={INVALID_SECRET_HASH:"invalid secret hash",INVALID_PUBKEY_OR_SECRET:"invalid public key or secret",INVALID_PUBKEY:"invalid public key",ORDER_NOT_EXPIRED:"you cannot refund before your transaction expires"},dB=(t,e,r=!1)=>{const n=o=>{try{o=pe.address.fromBech32(o).data.toString("hex")}catch(a){if(gd(a))(a.message.includes("Mixed-case string")||a.message.includes("too short"))&&(o=pe.address.fromBase58Check(o).hash.toString("hex"));else throw new Error(String(a))}return o},s=pe.script.fromASM(`
87
+ OP_IF
88
+ OP_SHA256
89
+ ${t.secretHash}
90
+ OP_EQUALVERIFY
91
+ OP_DUP
92
+ OP_HASH160
93
+ ${n(t.recipientAddress.address)}
94
+ OP_ELSE
95
+ ${pe.script.number.encode(t.expiryBlocks).toString("hex")}
96
+ OP_CHECKSEQUENCEVERIFY
97
+ OP_DROP
98
+ OP_DUP
99
+ OP_HASH160
100
+ ${n(t.refundAddress.address)}
101
+ OP_ENDIF
102
+ OP_EQUALVERIFY
103
+ OP_CHECKSIG
104
+ `.trim().replace(/\s+/g," ")),i=pe.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:e});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},Po={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var e2=(t=>(t[t.Bitcoin=0]="Bitcoin",t[t.EVM=1]="EVM",t))(e2||{});class hB{addSignatureSegwitV0(e=gc.ALL){return new Us("segwitV0",e)}addSignatureP2sh(e=gc.ALL){return new Us("p2shSignature",e)}addSignatureSegwitV1(e=gc.ALL){return new Us("segwitV1",e)}chain(){return e2.Bitcoin}async addAllInputs(e,r,n,s){const i=(s==null?void 0:s.utxos)||await n.getUTXOs(r);for(const o of i){const a=await n.getTxIndex(o.txid,r);e.addInput(bd(o.txid),a,s==null?void 0:s.nSequence)}return e}async suggestFee(e,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,e,r)}async toOutputScript(e){return pe.address.toOutputScript(e,await this.getNetwork())}totalValueFromUTXOs(e){return e.reduce((r,n)=>r+n.value,0)}async scriptToAddress(e){const r=pe.payments.p2wsh({redeem:{output:e},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(e){if(e.secretHash=E.trim0x(e.secretHash),e.secretHash.length!==64)throw new Error(go.INVALID_SECRET_HASH);const{script:r,address:n}=dB(e,await this.getNetwork());return new pB(this,{...e,redeemScript:r,scriptAddress:n})}getScriptType(e,r){try{if(pe.address.fromBase58Check(e).version===r.scriptHash)return Po.P2SH}catch{const s=pe.address.fromBech32(e);if(s.prefix!==r.bech32)throw new Error("Invalid address");if(s.version===0){if(s.data.length===32)return Po.P2WSH}else if(s.version===1&&s.data.length===32)return Po.P2TR}throw new Error("Unsupported script type")}}class pB{constructor(e,r){if(r.secretHash=E.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(go.INVALID_SECRET_HASH);this.wallet=e,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(e,r){e=E.trim0x(e);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(e,"hex"),pe.script.number.encode(1),this.swap.redeemScript],s=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!s)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,s,{witness:n,toAddress:r})}catch(i){throw gd(i)?i.message.includes("OP_EQUALVERIFY")?new Error(go.INVALID_PUBKEY_OR_SECRET):new Error(i.message):new Error(String(i))}}async refund(e){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),pe.script.number.encode(0),this.swap.redeemScript];try{const n=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!n)throw new Error("Could not generate p2wsh address for refund script");return await this.wallet.spend(this.swap.redeemScript,n,{toAddress:e,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw gd(n)?n.message.includes("OP_EQUALVERIFY")?new Error(go.INVALID_PUBKEY):n.message.includes("BIP")?new Error(go.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const If=(t,e,r,n)=>`m/${t}'/${e===xr.Mainnet?0:1}'/${r}'/0/${n??0}`,t2={bip44:(t,e,r)=>If("44",t,r??0,e),bip49:(t,e,r)=>If("49",t,r??0,e),bip84:(t,e,r)=>If("84",t,r??0,e)};function Bf(t){if(t===xr.Mainnet)return pe.networks.bitcoin;if(t===xr.Testnet)return pe.networks.testnet;if(t===xr.Regtest)return pe.networks.regtest;throw new Error("Invalid network")}function yB(t,e,r){if(!Ep.validateMnemonic(t))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??t2.bip44(e,(r==null?void 0:r.index)??0),s=u2.BIP32Factory(lr).fromSeed(Ep.mnemonicToSeedSync(t));return mB(s,n)}const mB=(t,e)=>{const r=t.derivePath(e).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};pe.initEccLib(lr);class Os extends hB{constructor({privateKey:e,provider:r,pkPath:n,pkType:s}){const i=ic.ECPairFactory(lr),o=Bf(r.getNetwork()),a=Buffer.from(e,"hex");if(a.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=s,this.signer=i.fromPrivateKey(a,{network:o}),this.provider=r,this.network=o}static fromMnemonic(e,r,n){const s=t2.bip84(r.getNetwork(),n==null?void 0:n.index),i=yB(e,r.getNetwork(),{path:s});return new Os({privateKey:i,provider:r,pkType:lo.p2wpkh,pkPath:s})}static fromPrivateKey(e,r,n){return new Os({privateKey:e,provider:r,pkType:(n==null?void 0:n.pkType)??lo.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(e){const r=ic.ECPairFactory(lr),n=Bf(e.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new Os({privateKey:s.privateKey.toString("hex"),provider:e,pkType:lo.p2wpkh,pkPath:"unknown"})}static fromWIF(e,r,n){const s=ic.ECPairFactory(lr),i=Bf(r.getNetwork()),o=s.fromWIF(e,i);if(!o.privateKey)throw new Error("Invalid WIF");return Os.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(e,r,{toAddress:n,fee:s,nSequence:i,unlockScript:o,witness:a}){var h;const c=this.getScriptType(r,this.network),u=await this.provider.getBalance(r);if(u===0)throw new Error(Ss.SCRIPT_NOT_FUNDED);let l=new pe.Transaction;if(l.version=2,s??(s=await this.provider.suggestFee(r,u,ki.FAST)),s>u)throw new Error(Ss.FEE_EXCEEDS_AMOUNT(s,u));const f=await this.provider.getUTXOs(r);l=await this.addAllInputs(l,r,this.provider,{nSequence:i,utxos:f}),l.addOutput(await this.toOutputScript(n??await this.getAddress()),u-s);for(let d=0;d<l.ins.length;d++)if(c===Po.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const p=[];for(const v of o)if(v instanceof Us){const S=v.sigHashType,T=l.hashForSignature(d,e,S);p.push(pe.script.signature.encode(Buffer.from(await this.sign(T.toString("hex")),"hex"),S))}else p.push(v);const m=(h=pe.payments.p2sh({redeem:{input:pe.script.compile(p),output:e},network:this.network}).redeem)==null?void 0:h.input;l.setInputScript(d,m)}else if(c===Po.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const p=[];for(const m of a)if(m instanceof Us){const v=m.sigHashType,S=l.hashForWitnessV0(d,e,f[d].value,v);p.push(pe.script.signature.encode(Buffer.from(await this.sign(S.toString("hex")),"hex"),v))}else p.push(m);l.setWitness(d,p)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(l.toHex())}async getAddress(){if(this.pkType===lo["p2wpkh-p2sh"]){const{address:r}=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network});if(!r)throw new Error("failed to get the p2wpkh-p2sh address");return r}const{address:e}=pe.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!e)throw new Error("failed to get the p2wpkh address");return e}getProvider(){return Promise.resolve(this.provider)}async getBalance(){return this.provider.getBalance(await this.getAddress())}getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(e,r,n,s,i,o){if(o||(o=await e.suggestFee(n,i,ki.FAST)),o>i)throw new Error(Ss.FEE_EXCEEDS_AMOUNT(o,i));const a=await e.getUTXOs(n,i+o),c=a.reduce((f,h)=>f+h.value,0);if(c<i+o)throw new Error(Ss.INSUFFICIENT_FUNDS(c,i+o));const u=new pe.Psbt({network:r});for(const f of a){const h=await e.getTransactionHex(f.txid);u.addInput({hash:bd(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(h,"hex")})}const l=c-i-o;return u.addOutput({address:s,value:i}),l>546&&u.addOutput({address:n,value:l}),{txHex:u.toHex(),utxoCount:a.length}}async _send(e,r,n){var u;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,ki.FAST)),n>r)throw new Error(Ss.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(Ss.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),o=i.reduce((l,f)=>l+f.value,0),a=new pe.Psbt({network:this.network});for(const l of i){const f=await this.provider.getTransactionHex(l.txid),h=await this.provider.getTransaction(l.txid);let d;this.pkType===lo["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(h.vout[l.vout].scriptpubkey,"hex"),value:l.value},redeemScript:(u=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:u.output}),a.addInput({hash:bd(l.txid),index:l.vout,nonWitnessUtxo:Buffer.from(f,"hex"),...d})}const c=o-r-n;return a.addOutput({address:e,value:r}),c>0&&a.addOutput({address:s,value:c}),a.signAllInputs(this.signer).finalizeAllInputs(),a.extractTransaction().toHex()}async send(e,r,n){const s=await this._send(e,r,n);return this.provider.broadcast(s)}async sign(e){return e=e.startsWith("0x")?e.slice(2):e,this.signer.sign(Buffer.from(e,"hex")).toString("hex")}async signSchnorr(e){return this.signer.signSchnorr(e)}}const bB=t=>t.map(e=>e),gB=t=>{if(t===E.Network.TESTNET)return wB;if(t===E.Network.MAINNET)return vB;throw new Error("Invalid network")},wB=["https://mempool.space/testnet4/api"],vB=["https://mempool.space/api","https://blockstream.info/api"],Em=t=>t.sort((e,r)=>e.status.confirmed!=r.status.confirmed?e.status.confirmed?-1:1:r.value-e.value);class r2{constructor(e,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?bB([r]):gB(e),this.network=sT(e)}async getTxIndex(e,r){const n=this.APIs.map(i=>`${i}/tx/${e}`),{vout:s}=await E.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return E.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:e})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,500))}throw new Error("failed to broadcast tx")}async getBalance(e){return(await this.getUTXOs(e)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(e){this.cacheTimeout=e}async getUTXOs(e,r){const n=this.utxosCache.get(e);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return Sm(n.utxos,r);const s=await E.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${e}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(e,{timestamp:Date.now(),utxos:s}),Sm(s,r)}async getTransactionHex(e){return E.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}/hex`))}async getTransaction(e){return E.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}`))}async getConfirmations(e){const r=await this.getTransaction(e);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===xr.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let e="";this.network===xr.Testnet&&(e="testnet4/");const r=`https://mempool.space/${e}api/v1/fees/recommended`,n=`https://blockstream.info/${e}api/fee-estimates`,s=await E.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(e,r){const n=await E.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${e}/txs`));if(r===cc.ALL)return n;if(r===cc.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===e));if(r===cc.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===e));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return E.Fetcher.getWithFallback(this.APIs.map(e=>`${e}/blocks/tip/height`))}async suggestFee(e,r,n){const i=(await this.getUTXOs(e,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[Xx[n]]*1.05)*(i*70+o*31+10)}async getTransactionTimes(e){const r=e.map(s=>`txId[]=${s}`).join("&");return(await E.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const Sm=(t,e)=>{if(Array.isArray(t)){if(e){const r=t.reduce((i,o)=>i+o.value,0);if(r<e)throw new Error(Ss.INSUFFICIENT_FUNDS(r,e));let n=BigInt(0);t.sort((i,o)=>o.value-i.value);const s=[];for(const i of t)if(n+=BigInt(i.value),s.push(i),n>=e)break;return Em(s)}return Em(t)}return[]};class EB extends E.EventBroker{emit(e,...r){super.emit(e,...r)}}class yp extends V.Orderbook{constructor(e){const{api:r,network:n}=md(e.environment);if(!r)throw new Error("API Key not found");super(new E.Url(r.baseurl)),this._redeemServiceEnabled=!0,this.executeInterval=5e3,this.network=n,this._api=r,this._digestKey=uB(e.digestKey),this._auth=vm(e.apiKey),this._quote=e.quote??new t1(this._api.baseurl,this._auth),this._htlcs=e.htlc??{},this._events=new EB,this._executor=this._digestKey?new fB(this._digestKey,this.htlcs,this,this._auth,this._api,this._events):void 0}setRedeemServiceEnabled(e){var r,n;if(this._redeemServiceEnabled=e,e)(r=this._executor)==null||r.stop();else{if(!this._digestKey)throw new Error("Digest key is required for manual secret management");if(this._secretManager=$i.fromDigestKey(this._digestKey.digestKey),!this._htlcs.bitcoin){const s=new r2(this.network);this._htlcs.bitcoin=new K0(Os.fromPrivateKey(this._digestKey.digestKey,s),this.network)}(n=this._executor)==null||n.start(this.executeInterval,this._redeemServiceEnabled)}return this}static fromWallets(e){const r=vm(e.apiKey),{api:n,network:s}=md(e.environment);if(!n)throw new Error("API not found, invalid environment "+e.environment);const i=e.wallets?{evm:e.wallets.evm?new l1(n.baseurl,e.wallets.evm,r):void 0,starknet:e.wallets.starknet?new y1(n.baseurl,e.wallets.starknet,s,r):void 0,solana:e.wallets.solana?new I1(e.wallets.solana,new E.Url(n.baseurl),s,r,{programAddress:e.solanaProgramAddress}):void 0,sui:e.wallets.sui?new iB(n.baseurl,e.wallets.sui,s,r):void 0,bitcoin:e.wallets.bitcoin?new K0(e.wallets.bitcoin,s):void 0,tron:e.wallets.tron?new oB(n.baseurl,s,r,e.wallets.tron):void 0,xrpl:e.wallets.xrpl?new Qv(n.baseurl,s,r,e.wallets.xrpl):void 0}:{};return new yp({htlc:i,...e})}get htlcs(){return{evm:this._htlcs.evm,starknet:this._htlcs.starknet,solana:this._htlcs.solana,sui:this._htlcs.sui,bitcoin:this._htlcs.bitcoin,tron:this._htlcs.tron,xrpl:this._htlcs.xrpl}}get quote(){return this._quote}get secretManager(){if(this._redeemServiceEnabled||!this._secretManager)throw new Error("Secret manager is not available");return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}get executor(){return this._executor}get redeemServiceEnabled(){return this._redeemServiceEnabled}async createSwap(e,r){const n=V.ChainAsset.from(e.fromAsset).blockchainType,s=await aT(n,this._htlcs);if(!s.ok)return E.Err(s.error);const i=await this.createOrder(e);if(!i.ok)return E.Err(i.error);const o=i.val;switch(r==null||r(wo.orderCreated),r==null||r(wo.orderInitiating),n){case V.BlockchainType.evm:if(!this._htlcs.evm||!V.isEvmOrderResponse(o))return E.Err("Order type does not match EVM blockchain type");{const a=await this._htlcs.evm.initiate(o);if(!a.ok)return E.Err(`EVM HTLC initiation failed: ${a.error}`)}break;case V.BlockchainType.solana:if(!this._htlcs.solana||!V.isSolanaOrderResponse(o))return E.Err("Order type does not match Solana blockchain type");{const a=await this._htlcs.solana.initiate(o);if(!a.ok)return E.Err(`Solana HTLC initiation failed: ${a.error}`)}break;case V.BlockchainType.starknet:if(!this._htlcs.starknet||!V.isStarknetOrderResponse(o))return E.Err("Order type does not match Starknet blockchain type");{const a=await this._htlcs.starknet.initiate(o);if(!a.ok)return E.Err(`Starknet HTLC initiation failed: ${a.error}`)}break;case V.BlockchainType.sui:if(!this._htlcs.sui||!V.isSuiOrderResponse(o))return E.Err("Order type does not match Sui blockchain type");{const a=await this._htlcs.sui.initiate(o);if(!a.ok)return E.Err(`Sui HTLC initiation failed: ${a.error}`)}break;case V.BlockchainType.tron:if(!this._htlcs.tron||!V.isEvmOrderResponse(o))return E.Err("Order type does not match Tron blockchain type");{const a=await this._htlcs.tron.initiate(o);if(!a.ok)return E.Err(`Tron HTLC initiation failed: ${a.error}`)}break;case V.BlockchainType.xrpl:if(!this._htlcs.xrpl||!V.isXrplOrderResponse(o))return E.Err("Order type does not match XRPL blockchain type");{const a=await this._htlcs.xrpl.initiate(o);if(!a.ok)return E.Err(`XRPL HTLC initiation failed: ${a.error}`)}break;case V.BlockchainType.bitcoin:return E.Ok(o);case V.BlockchainType.litecoin:return E.Ok(o);case V.BlockchainType.alpen_signet:return E.Ok(o);default:return E.Err("Unsupported blockchain type for swap initiation")}return r==null||r(wo.orderInitiated),E.Ok(o.order_id)}async createOrder(e){var T;if(E.hasKeys(e,["source","destination","nonce"]))return super.createOrder(e,this._auth);const r=e,n=await this.validateAndFillParams(r);if(!n.ok)return E.Err(n.error??"Validation failed");const{sendAddress:s,receiveAddress:i,fromAsset:o,toAsset:a}=n.val,c=Date.now().toString();let u;if(!this.redeemServiceEnabled){const g=await this.secretManager.generateSecret(c);if(!g.ok)return E.Err(g.error);u=g.val.secretHash}const l=(T=r.addresses)==null?void 0:T.bitcoin,f=V.isBitcoin(V.ChainAsset.from(r.fromAsset).chain),h=V.isBitcoin(V.ChainAsset.from(r.toAsset).chain),d=!!u,p={source:{asset:o.toString(),owner:!r.sourceAddress&&f?l??s:s,delegate:d&&f?s:null,amount:r.sendAmount},destination:{asset:a.toString(),owner:!r.destinationAddress&&h?l??i:i,delegate:d&&h?i:null,amount:r.receiveAmount},nonce:Number(c),...!this.redeemServiceEnabled&&u?{secret_hash:E.trim0x(u)}:{},solver_id:r.solverId,affiliate_fees:r.affiliateFee,slippage:0},m=await super.createOrder(p,this._auth);if(!m.ok)return E.Err(m.error);const v=V.ChainAsset.from(r.fromAsset).blockchainType,S=[V.BlockchainType.alpen_signet,V.BlockchainType.bitcoin,V.BlockchainType.litecoin].includes(v)?V.BlockchainType.bitcoin:[V.BlockchainType.tron].includes(v)?V.BlockchainType.evm:v;return m.val.type!==S?E.Err("Order response type does not match source blockchain type"):E.Ok(m.val)}async validateAndFillParams(e){var c;if(!e.fromAsset||!e.toAsset)return E.Err("Source and destination assets are required for swap");const r=V.ChainAsset.from(e.fromAsset),n=V.ChainAsset.from(e.toAsset);if(r.network!==n.network)return E.Err("Both assets should be on the same network (either mainnet or testnet)");const s=S0(e.sendAmount);if(!s.ok)return E.Err(s.error);const i=S0(e.receiveAmount);if(!i.ok)return E.Err(i.error);if(s<i)return E.Err("Send amount should be greater than receive amount");if(e.sourceAddress&&e.destinationAddress){const u=await this._getAddresses(r.blockchainType,{[r.blockchainType]:e.sourceAddress}),l=await this._getAddresses(n.blockchainType,{[n.blockchainType]:e.destinationAddress});return!u.ok||!l.ok?E.Err(u.error||l.error):E.Ok({sendAddress:u.val,receiveAddress:l.val,fromAsset:r,toAsset:n})}if((V.isBitcoin(V.ChainAsset.from(e.fromAsset).chain)||V.isBitcoin(V.ChainAsset.from(e.toAsset).chain))&&!((c=e.addresses)!=null&&c.bitcoin))return E.Err("Bitcoin address in addresses is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const o=await this._getAddresses(r.blockchainType,e.addresses);if(!o.ok)return E.Err(o.error);const a=await this._getAddresses(n.blockchainType,e.addresses);return a.ok?E.Ok({sendAddress:o.val,receiveAddress:a.val,fromAsset:r,toAsset:n}):E.Err(a.error)}async _getAddresses(e,r){var n;if(this._redeemServiceEnabled&&r&&r[e])return E.Ok(r[e]);switch(e){case V.BlockchainType.evm:return this._htlcs.evm?E.Ok(this._htlcs.evm.htlcActorAddress):E.Err("Please provide evmHTLC when initializing garden or pass EVM address in SwapParams");case V.BlockchainType.bitcoin:{const s=(n=this._htlcs.bitcoin)==null?void 0:n.getPublicKey;return!s||!eT(s)?E.Err("Invalid btc public key or pass Bitcoin address in SwapParams"):E.Ok($e(s))}case V.BlockchainType.solana:return this._htlcs.solana?E.Ok(this._htlcs.solana.htlcActorAddress):E.Err("Please provide solanaHTLC when initializing garden or pass Solana address in SwapParams");case V.BlockchainType.starknet:return this._htlcs.starknet?E.Ok(this._htlcs.starknet.htlcActorAddress):E.Err("Please provide starknetHTLC when initializing garden or pass Starknet address in SwapParams");case V.BlockchainType.sui:return this._htlcs.sui?E.Ok(this._htlcs.sui.htlcActorAddress):E.Err("Please provide suiHTLC when initializing garden or pass Sui address in SwapParams");case V.BlockchainType.tron:return this._htlcs.tron?E.Ok(this._htlcs.tron.htlcActorAddress):E.Err("Please provide tronHTLC when initializing garden or pass Tron address in SwapParams");case V.BlockchainType.xrpl:return this._htlcs.xrpl?E.Ok(this._htlcs.xrpl.htlcActorAddress):E.Err("Please provide xrplHTLC when initializing garden or pass XRPL address in SwapParams");default:return E.Err("Unsupported chain")}}on(e,r){return this._events.on(e,r),this}off(e,r){return this._events.off(e,r),this}}class SB{constructor(e,r,n){this.callData=new Xe.CallData(f1),this.account=e,this.starknetProvider=new Xe.RpcProvider({nodeUrl:r||(n?Qo[n].nodeUrl:Qo.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(e,r=!1){const n=r?e.destination_swap.asset:e.source_swap.asset;return new Xe.Contract({abi:p1,address:n,providerOrAccount:this.account})}async initiate(e){try{const n=await(await this.getHTLCContract(e)).token();if(!n)throw new Error("Token address retrieval failed");const s=Xe.num.toHex(n),i=Xe.cairo.uint256(BigInt(e.source_swap.amount));try{const u=await d1(this.account,s,e.source_swap.asset,BigInt(e.source_swap.amount),this.starknetProvider);if(u.error)return E.Err(u.error)}catch(u){return E.Err(`Allowance check failed: ${u}`)}const o=e.source_swap.secret_hash;if(!o)return E.Err("Invalid order: secret_hash is undefined");const a=E.hexToU128Array(o),c=await this.account.execute({contractAddress:e.source_swap.asset,entrypoint:"initiate",calldata:[e.source_swap.redeemer,e.source_swap.timelock.toString(),i.low.toString(),i.high.toString(),...a.map(u=>u.toString())]});if(!c.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return E.Ok(c.transaction_hash)}catch(r){return E.Err(`HTLC Initiation Error: ${r}`)}}async redeem(e,r){try{const n=await this.getHTLCContract(e,!0),s=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Xe.CallData.compile({swap_id:s,secret:E.hexToU32Array(r)})});return i.transaction_hash?E.Ok(i.transaction_hash):E.Err("Failed to redeem HTLC transaction")}catch{return E.Err("HTLC Redeem Error")}}async refund(e){try{const r=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,n=await this.getHTLCContract(e),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?E.Ok(s.transaction_hash):E.Err("Failed to refund HTLC transaction")}catch{return E.Err("HTLC Refund Error")}}}class AB{constructor(e){if(this.provider=e,!e)throw new Error("Provider is required");this.provider=e,this.program=new mr.Program(Ad,e)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return E.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=mr.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?E.Ok(c):E.Err("Failed to initiate HTLC transaction")}catch(r){return E.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(e,r){if(!e)return E.Err("Order is required");if(!r)return E.Err("Secret is required");const{secretHash:n}=es.from(e),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=mr.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=es.from(e);if(!this.swapAccount)return E.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(O1(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),a=await this.provider.sendAndConfirm(o);return a?E.Ok(a):E.Err("Failed to redeem HTLC transaction")}catch(i){return E.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(e){if(!e)return E.Err("Order is required");const{secretHash:r}=es.from(e),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=mr.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",e.source_swap.swap_id),!this.swapAccount)return E.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),i=await this.provider.sendAndConfirm(s);return i?E.Ok(i):E.Err("Failed to refund HTLC transaction")}catch(s){return E.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}exports.API=ac;exports.BaseError=q;exports.BitcoinNetwork=xr;exports.BitcoinProvider=r2;exports.BitcoinWallet=Os;exports.DEFAULT_AFFILIATE_ASSET=Kx;exports.EvmRelay=l1;exports.Garden=yp;exports.HttpRequestError=vi;exports.OrderCreationStatus=wo;exports.Quote=t1;exports.STARKNET_CONFIG=Qo;exports.SUI_CONFIG=yd;exports.SecretManager=$i;exports.SolanaHTLC=AB;exports.SolanaRelay=I1;exports.SolanaRelayerAddress=Ew;exports.StarknetHTLC=SB;exports.StarknetRelay=y1;exports.TRON_CONFIG=Sw;exports.XRPL_CONFIG=Aw;exports.XrplRelay=Qv;exports.alpenTestnet=c1;exports.botanixMainnet=i1;exports.call=Aa;exports.checkAllowance=So;exports.checkAllowanceAndApprove=d1;exports.concat=Jt;exports.constructOrderPair=tT;exports.decodeErrorResult=hb;exports.encodeAbiParameters=fs;exports.evmToViemChainMap=gu;exports.getChainNameFromChainId=u1;exports.getUrl=Vc;exports.hyperliquid=a1;exports.hyperliquidTestnet=o1;exports.isAddressEqual=Wi;exports.isAllowanceSufficient=h1;exports.isHex=_r;exports.localBatchGatewayRequest=vg;exports.localBatchGatewayUrl=xa;exports.resolveApiConfig=md;exports.solanaProgramAddress=pd;exports.stringify=Ye;exports.switchOrAddNetwork=Sd;exports.toXOnly=$e;exports.validateBTCAddress=rT;exports.validateLTCAddress=nT;